]> 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.5.  By combining all the individual C code files into this 
4 ** single large file, the entire code can be compiled as a one translation
5 ** unit.  This allows many compilers to do optimizations that would not be
6 ** possible if the files were compiled separately.  Performance improvements
7 ** of 5% or more are commonly seen when SQLite is compiled as a single
8 ** translation unit.
9 **
10 ** This file is all you need to compile SQLite.  To use SQLite in other
11 ** programs, you need this file and the "sqlite3.h" header file that defines
12 ** the programming interface to the SQLite library.  (If you do not have 
13 ** the "sqlite3.h" header file at hand, you will find a copy embedded within
14 ** the text of this file.  Search for "Begin file sqlite3.h" to find the start
15 ** of the embedded sqlite3.h header file.) Additional code files may be needed
16 ** if you want a wrapper to interface SQLite with your choice of programming
17 ** language. The code for the "sqlite3" command-line shell is also in a
18 ** separate file. This file contains only code for the core SQLite library.
19 */
20 #define SQLITE_CORE 1
21 #define SQLITE_AMALGAMATION 1
22 #ifndef SQLITE_PRIVATE
23 # define SQLITE_PRIVATE static
24 #endif
25 #ifndef SQLITE_API
26 # define SQLITE_API
27 #endif
28 /************** Begin file sqliteInt.h ***************************************/
29 /*
30 ** 2001 September 15
31 **
32 ** The author disclaims copyright to this source code.  In place of
33 ** a legal notice, here is a blessing:
34 **
35 **    May you do good and not evil.
36 **    May you find forgiveness for yourself and forgive others.
37 **    May you share freely, never taking more than you give.
38 **
39 *************************************************************************
40 ** Internal interface definitions for SQLite.
41 **
42 */
43 #ifndef _SQLITEINT_H_
44 #define _SQLITEINT_H_
45
46 /*
47 ** These #defines should enable >2GB file support on POSIX if the
48 ** underlying operating system supports it.  If the OS lacks
49 ** large file support, or if the OS is windows, these should be no-ops.
50 **
51 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
52 ** system #includes.  Hence, this block of code must be the very first
53 ** code in all source files.
54 **
55 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
56 ** on the compiler command line.  This is necessary if you are compiling
57 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
58 ** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
59 ** without this option, LFS is enable.  But LFS does not exist in the kernel
60 ** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
61 ** portability you should omit LFS.
62 **
63 ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
64 */
65 #ifndef SQLITE_DISABLE_LFS
66 # define _LARGE_FILE       1
67 # ifndef _FILE_OFFSET_BITS
68 #   define _FILE_OFFSET_BITS 64
69 # endif
70 # define _LARGEFILE_SOURCE 1
71 #endif
72
73 /*
74 ** Include the configuration header output by 'configure' if we're using the
75 ** autoconf-based build
76 */
77 #ifdef _HAVE_SQLITE_CONFIG_H
78 #include "config.h"
79 #endif
80
81 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
82 /************** Begin file sqliteLimit.h *************************************/
83 /*
84 ** 2007 May 7
85 **
86 ** The author disclaims copyright to this source code.  In place of
87 ** a legal notice, here is a blessing:
88 **
89 **    May you do good and not evil.
90 **    May you find forgiveness for yourself and forgive others.
91 **    May you share freely, never taking more than you give.
92 **
93 *************************************************************************
94 ** 
95 ** This file defines various limits of what SQLite can process.
96 */
97
98 /*
99 ** The maximum length of a TEXT or BLOB in bytes.   This also
100 ** limits the size of a row in a table or index.
101 **
102 ** The hard limit is the ability of a 32-bit signed integer
103 ** to count the size: 2^31-1 or 2147483647.
104 */
105 #ifndef SQLITE_MAX_LENGTH
106 # define SQLITE_MAX_LENGTH 1000000000
107 #endif
108
109 /*
110 ** This is the maximum number of
111 **
112 **    * Columns in a table
113 **    * Columns in an index
114 **    * Columns in a view
115 **    * Terms in the SET clause of an UPDATE statement
116 **    * Terms in the result set of a SELECT statement
117 **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
118 **    * Terms in the VALUES clause of an INSERT statement
119 **
120 ** The hard upper limit here is 32676.  Most database people will
121 ** tell you that in a well-normalized database, you usually should
122 ** not have more than a dozen or so columns in any table.  And if
123 ** that is the case, there is no point in having more than a few
124 ** dozen values in any of the other situations described above.
125 */
126 #ifndef SQLITE_MAX_COLUMN
127 # define SQLITE_MAX_COLUMN 2000
128 #endif
129
130 /*
131 ** The maximum length of a single SQL statement in bytes.
132 **
133 ** It used to be the case that setting this value to zero would
134 ** turn the limit off.  That is no longer true.  It is not possible
135 ** to turn this limit off.
136 */
137 #ifndef SQLITE_MAX_SQL_LENGTH
138 # define SQLITE_MAX_SQL_LENGTH 1000000000
139 #endif
140
141 /*
142 ** The maximum depth of an expression tree. This is limited to 
143 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might 
144 ** want to place more severe limits on the complexity of an 
145 ** expression.
146 **
147 ** A value of 0 used to mean that the limit was not enforced.
148 ** But that is no longer true.  The limit is now strictly enforced
149 ** at all times.
150 */
151 #ifndef SQLITE_MAX_EXPR_DEPTH
152 # define SQLITE_MAX_EXPR_DEPTH 1000
153 #endif
154
155 /*
156 ** The maximum number of terms in a compound SELECT statement.
157 ** The code generator for compound SELECT statements does one
158 ** level of recursion for each term.  A stack overflow can result
159 ** if the number of terms is too large.  In practice, most SQL
160 ** never has more than 3 or 4 terms.  Use a value of 0 to disable
161 ** any limit on the number of terms in a compount SELECT.
162 */
163 #ifndef SQLITE_MAX_COMPOUND_SELECT
164 # define SQLITE_MAX_COMPOUND_SELECT 500
165 #endif
166
167 /*
168 ** The maximum number of opcodes in a VDBE program.
169 ** Not currently enforced.
170 */
171 #ifndef SQLITE_MAX_VDBE_OP
172 # define SQLITE_MAX_VDBE_OP 25000
173 #endif
174
175 /*
176 ** The maximum number of arguments to an SQL function.
177 */
178 #ifndef SQLITE_MAX_FUNCTION_ARG
179 # define SQLITE_MAX_FUNCTION_ARG 127
180 #endif
181
182 /*
183 ** The maximum number of in-memory pages to use for the main database
184 ** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
185 */
186 #ifndef SQLITE_DEFAULT_CACHE_SIZE
187 # define SQLITE_DEFAULT_CACHE_SIZE  2000
188 #endif
189 #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
190 # define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
191 #endif
192
193 /*
194 ** The default number of frames to accumulate in the log file before
195 ** checkpointing the database in WAL mode.
196 */
197 #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
198 # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
199 #endif
200
201 /*
202 ** The maximum number of attached databases.  This must be between 0
203 ** and 30.  The upper bound on 30 is because a 32-bit integer bitmap
204 ** is used internally to track attached databases.
205 */
206 #ifndef SQLITE_MAX_ATTACHED
207 # define SQLITE_MAX_ATTACHED 10
208 #endif
209
210
211 /*
212 ** The maximum value of a ?nnn wildcard that the parser will accept.
213 */
214 #ifndef SQLITE_MAX_VARIABLE_NUMBER
215 # define SQLITE_MAX_VARIABLE_NUMBER 999
216 #endif
217
218 /* Maximum page size.  The upper bound on this value is 65536.  This a limit
219 ** imposed by the use of 16-bit offsets within each page.
220 **
221 ** Earlier versions of SQLite allowed the user to change this value at
222 ** compile time. This is no longer permitted, on the grounds that it creates
223 ** a library that is technically incompatible with an SQLite library 
224 ** compiled with a different limit. If a process operating on a database 
225 ** with a page-size of 65536 bytes crashes, then an instance of SQLite 
226 ** compiled with the default page-size limit will not be able to rollback 
227 ** the aborted transaction. This could lead to database corruption.
228 */
229 #ifdef SQLITE_MAX_PAGE_SIZE
230 # undef SQLITE_MAX_PAGE_SIZE
231 #endif
232 #define SQLITE_MAX_PAGE_SIZE 65536
233
234
235 /*
236 ** The default size of a database page.
237 */
238 #ifndef SQLITE_DEFAULT_PAGE_SIZE
239 # define SQLITE_DEFAULT_PAGE_SIZE 1024
240 #endif
241 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
242 # undef SQLITE_DEFAULT_PAGE_SIZE
243 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
244 #endif
245
246 /*
247 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
248 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
249 ** device characteristics (sector-size and atomic write() support),
250 ** SQLite may choose a larger value. This constant is the maximum value
251 ** SQLite will choose on its own.
252 */
253 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
254 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
255 #endif
256 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
257 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
258 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
259 #endif
260
261
262 /*
263 ** Maximum number of pages in one database file.
264 **
265 ** This is really just the default value for the max_page_count pragma.
266 ** This value can be lowered (or raised) at run-time using that the
267 ** max_page_count macro.
268 */
269 #ifndef SQLITE_MAX_PAGE_COUNT
270 # define SQLITE_MAX_PAGE_COUNT 1073741823
271 #endif
272
273 /*
274 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
275 ** operator.
276 */
277 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
278 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
279 #endif
280
281 /*
282 ** Maximum depth of recursion for triggers.
283 **
284 ** A value of 1 means that a trigger program will not be able to itself
285 ** fire any triggers. A value of 0 means that no trigger programs at all 
286 ** may be executed.
287 */
288 #ifndef SQLITE_MAX_TRIGGER_DEPTH
289 # define SQLITE_MAX_TRIGGER_DEPTH 1000
290 #endif
291
292 /************** End of sqliteLimit.h *****************************************/
293 /************** Continuing where we left off in sqliteInt.h ******************/
294
295 /* Disable nuisance warnings on Borland compilers */
296 #if defined(__BORLANDC__)
297 #pragma warn -rch /* unreachable code */
298 #pragma warn -ccc /* Condition is always true or false */
299 #pragma warn -aus /* Assigned value is never used */
300 #pragma warn -csu /* Comparing signed and unsigned */
301 #pragma warn -spa /* Suspicious pointer arithmetic */
302 #endif
303
304 /* Needed for various definitions... */
305 #ifndef _GNU_SOURCE
306 # define _GNU_SOURCE
307 #endif
308
309 /*
310 ** Include standard header files as necessary
311 */
312 #ifdef HAVE_STDINT_H
313 #include <stdint.h>
314 #endif
315 #ifdef HAVE_INTTYPES_H
316 #include <inttypes.h>
317 #endif
318
319 /*
320 ** The number of samples of an index that SQLite takes in order to 
321 ** construct a histogram of the table content when running ANALYZE
322 ** and with SQLITE_ENABLE_STAT2
323 */
324 #define SQLITE_INDEX_SAMPLES 10
325
326 /*
327 ** The following macros are used to cast pointers to integers and
328 ** integers to pointers.  The way you do this varies from one compiler
329 ** to the next, so we have developed the following set of #if statements
330 ** to generate appropriate macros for a wide range of compilers.
331 **
332 ** The correct "ANSI" way to do this is to use the intptr_t type. 
333 ** Unfortunately, that typedef is not available on all compilers, or
334 ** if it is available, it requires an #include of specific headers
335 ** that vary from one machine to the next.
336 **
337 ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
338 ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
339 ** So we have to define the macros in different ways depending on the
340 ** compiler.
341 */
342 #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
343 # define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
344 # define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
345 #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
346 # define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
347 # define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
348 #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
349 # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
350 # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
351 #else                          /* Generates a warning - but it always works */
352 # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
353 # define SQLITE_PTR_TO_INT(X)  ((int)(X))
354 #endif
355
356 /*
357 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
358 ** 0 means mutexes are permanently disable and the library is never
359 ** threadsafe.  1 means the library is serialized which is the highest
360 ** level of threadsafety.  2 means the libary is multithreaded - multiple
361 ** threads can use SQLite as long as no two threads try to use the same
362 ** database connection at the same time.
363 **
364 ** Older versions of SQLite used an optional THREADSAFE macro.
365 ** We support that for legacy.
366 */
367 #if !defined(SQLITE_THREADSAFE)
368 #if defined(THREADSAFE)
369 # define SQLITE_THREADSAFE THREADSAFE
370 #else
371 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
372 #endif
373 #endif
374
375 /*
376 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
377 ** It determines whether or not the features related to 
378 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
379 ** be overridden at runtime using the sqlite3_config() API.
380 */
381 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
382 # define SQLITE_DEFAULT_MEMSTATUS 1
383 #endif
384
385 /*
386 ** Exactly one of the following macros must be defined in order to
387 ** specify which memory allocation subsystem to use.
388 **
389 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
390 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
391 **
392 ** (Historical note:  There used to be several other options, but we've
393 ** pared it down to just these two.)
394 **
395 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
396 ** the default.
397 */
398 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)>1
399 # error "At most one of the following compile-time configuration options\
400  is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG"
401 #endif
402 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)==0
403 # define SQLITE_SYSTEM_MALLOC 1
404 #endif
405
406 /*
407 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
408 ** sizes of memory allocations below this value where possible.
409 */
410 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
411 # define SQLITE_MALLOC_SOFT_LIMIT 1024
412 #endif
413
414 /*
415 ** We need to define _XOPEN_SOURCE as follows in order to enable
416 ** recursive mutexes on most Unix systems.  But Mac OS X is different.
417 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
418 ** so it is omitted there.  See ticket #2673.
419 **
420 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
421 ** implemented on some systems.  So we avoid defining it at all
422 ** if it is already defined or if it is unneeded because we are
423 ** not doing a threadsafe build.  Ticket #2681.
424 **
425 ** See also ticket #2741.
426 */
427 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
428 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
429 #endif
430
431 /*
432 ** The TCL headers are only needed when compiling the TCL bindings.
433 */
434 #if defined(SQLITE_TCL) || defined(TCLSH)
435 # include <tcl.h>
436 #endif
437
438 /*
439 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
440 ** Setting NDEBUG makes the code smaller and run faster.  So the following
441 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
442 ** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
443 ** feature.
444 */
445 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
446 # define NDEBUG 1
447 #endif
448
449 /*
450 ** The testcase() macro is used to aid in coverage testing.  When 
451 ** doing coverage testing, the condition inside the argument to
452 ** testcase() must be evaluated both true and false in order to
453 ** get full branch coverage.  The testcase() macro is inserted
454 ** to help ensure adequate test coverage in places where simple
455 ** condition/decision coverage is inadequate.  For example, testcase()
456 ** can be used to make sure boundary values are tested.  For
457 ** bitmask tests, testcase() can be used to make sure each bit
458 ** is significant and used at least once.  On switch statements
459 ** where multiple cases go to the same block of code, testcase()
460 ** can insure that all cases are evaluated.
461 **
462 */
463 #ifdef SQLITE_COVERAGE_TEST
464 SQLITE_PRIVATE   void sqlite3Coverage(int);
465 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
466 #else
467 # define testcase(X)
468 #endif
469
470 /*
471 ** The TESTONLY macro is used to enclose variable declarations or
472 ** other bits of code that are needed to support the arguments
473 ** within testcase() and assert() macros.
474 */
475 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
476 # define TESTONLY(X)  X
477 #else
478 # define TESTONLY(X)
479 #endif
480
481 /*
482 ** Sometimes we need a small amount of code such as a variable initialization
483 ** to setup for a later assert() statement.  We do not want this code to
484 ** appear when assert() is disabled.  The following macro is therefore
485 ** used to contain that setup code.  The "VVA" acronym stands for
486 ** "Verification, Validation, and Accreditation".  In other words, the
487 ** code within VVA_ONLY() will only run during verification processes.
488 */
489 #ifndef NDEBUG
490 # define VVA_ONLY(X)  X
491 #else
492 # define VVA_ONLY(X)
493 #endif
494
495 /*
496 ** The ALWAYS and NEVER macros surround boolean expressions which 
497 ** are intended to always be true or false, respectively.  Such
498 ** expressions could be omitted from the code completely.  But they
499 ** are included in a few cases in order to enhance the resilience
500 ** of SQLite to unexpected behavior - to make the code "self-healing"
501 ** or "ductile" rather than being "brittle" and crashing at the first
502 ** hint of unplanned behavior.
503 **
504 ** In other words, ALWAYS and NEVER are added for defensive code.
505 **
506 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
507 ** be true and false so that the unreachable code then specify will
508 ** not be counted as untested code.
509 */
510 #if defined(SQLITE_COVERAGE_TEST)
511 # define ALWAYS(X)      (1)
512 # define NEVER(X)       (0)
513 #elif !defined(NDEBUG)
514 # define ALWAYS(X)      ((X)?1:(assert(0),0))
515 # define NEVER(X)       ((X)?(assert(0),1):0)
516 #else
517 # define ALWAYS(X)      (X)
518 # define NEVER(X)       (X)
519 #endif
520
521 /*
522 ** Return true (non-zero) if the input is a integer that is too large
523 ** to fit in 32-bits.  This macro is used inside of various testcase()
524 ** macros to verify that we have tested SQLite for large-file support.
525 */
526 #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
527
528 /*
529 ** The macro unlikely() is a hint that surrounds a boolean
530 ** expression that is usually false.  Macro likely() surrounds
531 ** a boolean expression that is usually true.  GCC is able to
532 ** use these hints to generate better code, sometimes.
533 */
534 #if defined(__GNUC__) && 0
535 # define likely(X)    __builtin_expect((X),1)
536 # define unlikely(X)  __builtin_expect((X),0)
537 #else
538 # define likely(X)    !!(X)
539 # define unlikely(X)  !!(X)
540 #endif
541
542 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
543 /************** Begin file sqlite3.h *****************************************/
544 /*
545 ** 2001 September 15
546 **
547 ** The author disclaims copyright to this source code.  In place of
548 ** a legal notice, here is a blessing:
549 **
550 **    May you do good and not evil.
551 **    May you find forgiveness for yourself and forgive others.
552 **    May you share freely, never taking more than you give.
553 **
554 *************************************************************************
555 ** This header file defines the interface that the SQLite library
556 ** presents to client programs.  If a C-function, structure, datatype,
557 ** or constant definition does not appear in this file, then it is
558 ** not a published API of SQLite, is subject to change without
559 ** notice, and should not be referenced by programs that use SQLite.
560 **
561 ** Some of the definitions that are in this file are marked as
562 ** "experimental".  Experimental interfaces are normally new
563 ** features recently added to SQLite.  We do not anticipate changes
564 ** to experimental interfaces but reserve the right to make minor changes
565 ** if experience from use "in the wild" suggest such changes are prudent.
566 **
567 ** The official C-language API documentation for SQLite is derived
568 ** from comments in this file.  This file is the authoritative source
569 ** on how SQLite interfaces are suppose to operate.
570 **
571 ** The name of this file under configuration management is "sqlite.h.in".
572 ** The makefile makes some minor changes to this file (such as inserting
573 ** the version number) and changes its name to "sqlite3.h" as
574 ** part of the build process.
575 */
576 #ifndef _SQLITE3_H_
577 #define _SQLITE3_H_
578 #include <stdarg.h>     /* Needed for the definition of va_list */
579
580 /*
581 ** Make sure we can call this stuff from C++.
582 */
583 #if 0
584 extern "C" {
585 #endif
586
587
588 /*
589 ** Add the ability to override 'extern'
590 */
591 #ifndef SQLITE_EXTERN
592 # define SQLITE_EXTERN extern
593 #endif
594
595 #ifndef SQLITE_API
596 # define SQLITE_API
597 #endif
598
599
600 /*
601 ** These no-op macros are used in front of interfaces to mark those
602 ** interfaces as either deprecated or experimental.  New applications
603 ** should not use deprecated interfaces - they are support for backwards
604 ** compatibility only.  Application writers should be aware that
605 ** experimental interfaces are subject to change in point releases.
606 **
607 ** These macros used to resolve to various kinds of compiler magic that
608 ** would generate warning messages when they were used.  But that
609 ** compiler magic ended up generating such a flurry of bug reports
610 ** that we have taken it all out and gone back to using simple
611 ** noop macros.
612 */
613 #define SQLITE_DEPRECATED
614 #define SQLITE_EXPERIMENTAL
615
616 /*
617 ** Ensure these symbols were not defined by some previous header file.
618 */
619 #ifdef SQLITE_VERSION
620 # undef SQLITE_VERSION
621 #endif
622 #ifdef SQLITE_VERSION_NUMBER
623 # undef SQLITE_VERSION_NUMBER
624 #endif
625
626 /*
627 ** CAPI3REF: Compile-Time Library Version Numbers
628 **
629 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
630 ** evaluates to a string literal that is the SQLite version in the
631 ** format "X.Y.Z" where X is the major version number (always 3 for
632 ** SQLite3) and Y is the minor version number and Z is the release number.)^
633 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
634 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
635 ** numbers used in [SQLITE_VERSION].)^
636 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
637 ** be larger than the release from which it is derived.  Either Y will
638 ** be held constant and Z will be incremented or else Y will be incremented
639 ** and Z will be reset to zero.
640 **
641 ** Since version 3.6.18, SQLite source code has been stored in the
642 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
643 ** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
644 ** a string which identifies a particular check-in of SQLite
645 ** within its configuration management system.  ^The SQLITE_SOURCE_ID
646 ** string contains the date and time of the check-in (UTC) and an SHA1
647 ** hash of the entire source tree.
648 **
649 ** See also: [sqlite3_libversion()],
650 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
651 ** [sqlite_version()] and [sqlite_source_id()].
652 */
653 #define SQLITE_VERSION        "3.7.5"
654 #define SQLITE_VERSION_NUMBER 3007005
655 #define SQLITE_SOURCE_ID      "2011-01-28 17:03:50 ed759d5a9edb3bba5f48f243df47be29e3fe8cd7"
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 /*
1030 ** CAPI3REF: Device Characteristics
1031 **
1032 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
1033 ** object returns an integer which is a vector of the these
1034 ** bit values expressing I/O characteristics of the mass storage
1035 ** device that holds the file that the [sqlite3_io_methods]
1036 ** refers to.
1037 **
1038 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1039 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1040 ** mean that writes of blocks that are nnn bytes in size and
1041 ** are aligned to an address which is an integer multiple of
1042 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1043 ** that when data is appended to a file, the data is appended
1044 ** first then the size of the file is extended, never the other
1045 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1046 ** information is written to disk in the same order as calls
1047 ** to xWrite().
1048 */
1049 #define SQLITE_IOCAP_ATOMIC                 0x00000001
1050 #define SQLITE_IOCAP_ATOMIC512              0x00000002
1051 #define SQLITE_IOCAP_ATOMIC1K               0x00000004
1052 #define SQLITE_IOCAP_ATOMIC2K               0x00000008
1053 #define SQLITE_IOCAP_ATOMIC4K               0x00000010
1054 #define SQLITE_IOCAP_ATOMIC8K               0x00000020
1055 #define SQLITE_IOCAP_ATOMIC16K              0x00000040
1056 #define SQLITE_IOCAP_ATOMIC32K              0x00000080
1057 #define SQLITE_IOCAP_ATOMIC64K              0x00000100
1058 #define SQLITE_IOCAP_SAFE_APPEND            0x00000200
1059 #define SQLITE_IOCAP_SEQUENTIAL             0x00000400
1060 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
1061
1062 /*
1063 ** CAPI3REF: File Locking Levels
1064 **
1065 ** SQLite uses one of these integer values as the second
1066 ** argument to calls it makes to the xLock() and xUnlock() methods
1067 ** of an [sqlite3_io_methods] object.
1068 */
1069 #define SQLITE_LOCK_NONE          0
1070 #define SQLITE_LOCK_SHARED        1
1071 #define SQLITE_LOCK_RESERVED      2
1072 #define SQLITE_LOCK_PENDING       3
1073 #define SQLITE_LOCK_EXCLUSIVE     4
1074
1075 /*
1076 ** CAPI3REF: Synchronization Type Flags
1077 **
1078 ** When SQLite invokes the xSync() method of an
1079 ** [sqlite3_io_methods] object it uses a combination of
1080 ** these integer values as the second argument.
1081 **
1082 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1083 ** sync operation only needs to flush data to mass storage.  Inode
1084 ** information need not be flushed. If the lower four bits of the flag
1085 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1086 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
1087 ** to use Mac OS X style fullsync instead of fsync().
1088 **
1089 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
1090 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1091 ** settings.  The [synchronous pragma] determines when calls to the
1092 ** xSync VFS method occur and applies uniformly across all platforms.
1093 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
1094 ** energetic or rigorous or forceful the sync operations are and
1095 ** only make a difference on Mac OSX for the default SQLite code.
1096 ** (Third-party VFS implementations might also make the distinction
1097 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
1098 ** operating systems natively supported by SQLite, only Mac OSX
1099 ** cares about the difference.)
1100 */
1101 #define SQLITE_SYNC_NORMAL        0x00002
1102 #define SQLITE_SYNC_FULL          0x00003
1103 #define SQLITE_SYNC_DATAONLY      0x00010
1104
1105 /*
1106 ** CAPI3REF: OS Interface Open File Handle
1107 **
1108 ** An [sqlite3_file] object represents an open file in the 
1109 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
1110 ** implementations will
1111 ** want to subclass this object by appending additional fields
1112 ** for their own use.  The pMethods entry is a pointer to an
1113 ** [sqlite3_io_methods] object that defines methods for performing
1114 ** I/O operations on the open file.
1115 */
1116 typedef struct sqlite3_file sqlite3_file;
1117 struct sqlite3_file {
1118   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1119 };
1120
1121 /*
1122 ** CAPI3REF: OS Interface File Virtual Methods Object
1123 **
1124 ** Every file opened by the [sqlite3_vfs] xOpen method populates an
1125 ** [sqlite3_file] object (or, more commonly, a subclass of the
1126 ** [sqlite3_file] object) with a pointer to an instance of this object.
1127 ** This object defines the methods used to perform various operations
1128 ** against the open file represented by the [sqlite3_file] object.
1129 **
1130 ** If the xOpen method sets the sqlite3_file.pMethods element 
1131 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1132 ** may be invoked even if the xOpen reported that it failed.  The
1133 ** only way to prevent a call to xClose following a failed xOpen
1134 ** is for the xOpen to set the sqlite3_file.pMethods element to NULL.
1135 **
1136 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1137 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1138 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1139 ** flag may be ORed in to indicate that only the data of the file
1140 ** and not its inode needs to be synced.
1141 **
1142 ** The integer values to xLock() and xUnlock() are one of
1143 ** <ul>
1144 ** <li> [SQLITE_LOCK_NONE],
1145 ** <li> [SQLITE_LOCK_SHARED],
1146 ** <li> [SQLITE_LOCK_RESERVED],
1147 ** <li> [SQLITE_LOCK_PENDING], or
1148 ** <li> [SQLITE_LOCK_EXCLUSIVE].
1149 ** </ul>
1150 ** xLock() increases the lock. xUnlock() decreases the lock.
1151 ** The xCheckReservedLock() method checks whether any database connection,
1152 ** either in this process or in some other process, is holding a RESERVED,
1153 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
1154 ** if such a lock exists and false otherwise.
1155 **
1156 ** The xFileControl() method is a generic interface that allows custom
1157 ** VFS implementations to directly control an open file using the
1158 ** [sqlite3_file_control()] interface.  The second "op" argument is an
1159 ** integer opcode.  The third argument is a generic pointer intended to
1160 ** point to a structure that may contain arguments or space in which to
1161 ** write return values.  Potential uses for xFileControl() might be
1162 ** functions to enable blocking locks with timeouts, to change the
1163 ** locking strategy (for example to use dot-file locks), to inquire
1164 ** about the status of a lock, or to break stale locks.  The SQLite
1165 ** core reserves all opcodes less than 100 for its own use.
1166 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1167 ** Applications that define a custom xFileControl method should use opcodes
1168 ** greater than 100 to avoid conflicts.  VFS implementations should
1169 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
1170 ** recognize.
1171 **
1172 ** The xSectorSize() method returns the sector size of the
1173 ** device that underlies the file.  The sector size is the
1174 ** minimum write that can be performed without disturbing
1175 ** other bytes in the file.  The xDeviceCharacteristics()
1176 ** method returns a bit vector describing behaviors of the
1177 ** underlying device:
1178 **
1179 ** <ul>
1180 ** <li> [SQLITE_IOCAP_ATOMIC]
1181 ** <li> [SQLITE_IOCAP_ATOMIC512]
1182 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1183 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1184 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1185 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1186 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1187 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1188 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1189 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1190 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1191 ** </ul>
1192 **
1193 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1194 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1195 ** mean that writes of blocks that are nnn bytes in size and
1196 ** are aligned to an address which is an integer multiple of
1197 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1198 ** that when data is appended to a file, the data is appended
1199 ** first then the size of the file is extended, never the other
1200 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1201 ** information is written to disk in the same order as calls
1202 ** to xWrite().
1203 **
1204 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1205 ** in the unread portions of the buffer with zeros.  A VFS that
1206 ** fails to zero-fill short reads might seem to work.  However,
1207 ** failure to zero-fill short reads will eventually lead to
1208 ** database corruption.
1209 */
1210 typedef struct sqlite3_io_methods sqlite3_io_methods;
1211 struct sqlite3_io_methods {
1212   int iVersion;
1213   int (*xClose)(sqlite3_file*);
1214   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1215   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1216   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1217   int (*xSync)(sqlite3_file*, int flags);
1218   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1219   int (*xLock)(sqlite3_file*, int);
1220   int (*xUnlock)(sqlite3_file*, int);
1221   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1222   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1223   int (*xSectorSize)(sqlite3_file*);
1224   int (*xDeviceCharacteristics)(sqlite3_file*);
1225   /* Methods above are valid for version 1 */
1226   int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1227   int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1228   void (*xShmBarrier)(sqlite3_file*);
1229   int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1230   /* Methods above are valid for version 2 */
1231   /* Additional methods may be added in future releases */
1232 };
1233
1234 /*
1235 ** CAPI3REF: Standard File Control Opcodes
1236 **
1237 ** These integer constants are opcodes for the xFileControl method
1238 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1239 ** interface.
1240 **
1241 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1242 ** opcode causes the xFileControl method to write the current state of
1243 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1244 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1245 ** into an integer that the pArg argument points to. This capability
1246 ** is used during testing and only needs to be supported when SQLITE_TEST
1247 ** is defined.
1248 **
1249 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1250 ** layer a hint of how large the database file will grow to be during the
1251 ** current transaction.  This hint is not guaranteed to be accurate but it
1252 ** is often close.  The underlying VFS might choose to preallocate database
1253 ** file space based on this hint in order to help writes to the database
1254 ** file run faster.
1255 **
1256 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1257 ** extends and truncates the database file in chunks of a size specified
1258 ** by the user. The fourth argument to [sqlite3_file_control()] should 
1259 ** point to an integer (type int) containing the new chunk-size to use
1260 ** for the nominated database. Allocating database file space in large
1261 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
1262 ** improve performance on some systems.
1263 **
1264 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1265 ** to the [sqlite3_file] object associated with a particular database
1266 ** connection.  See the [sqlite3_file_control()] documentation for
1267 ** additional information.
1268 **
1269 ** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
1270 ** SQLite and sent to all VFSes in place of a call to the xSync method
1271 ** when the database connection has [PRAGMA synchronous] set to OFF.)^
1272 ** Some specialized VFSes need this signal in order to operate correctly
1273 ** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most 
1274 ** VFSes do not need this signal and should silently ignore this opcode.
1275 ** Applications should not call [sqlite3_file_control()] with this
1276 ** opcode as doing so may disrupt the operation of the specilized VFSes
1277 ** that do require it.  
1278 */
1279 #define SQLITE_FCNTL_LOCKSTATE        1
1280 #define SQLITE_GET_LOCKPROXYFILE      2
1281 #define SQLITE_SET_LOCKPROXYFILE      3
1282 #define SQLITE_LAST_ERRNO             4
1283 #define SQLITE_FCNTL_SIZE_HINT        5
1284 #define SQLITE_FCNTL_CHUNK_SIZE       6
1285 #define SQLITE_FCNTL_FILE_POINTER     7
1286 #define SQLITE_FCNTL_SYNC_OMITTED     8
1287
1288
1289 /*
1290 ** CAPI3REF: Mutex Handle
1291 **
1292 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1293 ** abstract type for a mutex object.  The SQLite core never looks
1294 ** at the internal representation of an [sqlite3_mutex].  It only
1295 ** deals with pointers to the [sqlite3_mutex] object.
1296 **
1297 ** Mutexes are created using [sqlite3_mutex_alloc()].
1298 */
1299 typedef struct sqlite3_mutex sqlite3_mutex;
1300
1301 /*
1302 ** CAPI3REF: OS Interface Object
1303 **
1304 ** An instance of the sqlite3_vfs object defines the interface between
1305 ** the SQLite core and the underlying operating system.  The "vfs"
1306 ** in the name of the object stands for "virtual file system".
1307 **
1308 ** The value of the iVersion field is initially 1 but may be larger in
1309 ** future versions of SQLite.  Additional fields may be appended to this
1310 ** object when the iVersion value is increased.  Note that the structure
1311 ** of the sqlite3_vfs object changes in the transaction between
1312 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1313 ** modified.
1314 **
1315 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1316 ** structure used by this VFS.  mxPathname is the maximum length of
1317 ** a pathname in this VFS.
1318 **
1319 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1320 ** the pNext pointer.  The [sqlite3_vfs_register()]
1321 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1322 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1323 ** searches the list.  Neither the application code nor the VFS
1324 ** implementation should use the pNext pointer.
1325 **
1326 ** The pNext field is the only field in the sqlite3_vfs
1327 ** structure that SQLite will ever modify.  SQLite will only access
1328 ** or modify this field while holding a particular static mutex.
1329 ** The application should never modify anything within the sqlite3_vfs
1330 ** object once the object has been registered.
1331 **
1332 ** The zName field holds the name of the VFS module.  The name must
1333 ** be unique across all VFS modules.
1334 **
1335 ** ^SQLite guarantees that the zFilename parameter to xOpen
1336 ** is either a NULL pointer or string obtained
1337 ** from xFullPathname() with an optional suffix added.
1338 ** ^If a suffix is added to the zFilename parameter, it will
1339 ** consist of a single "-" character followed by no more than
1340 ** 10 alphanumeric and/or "-" characters.
1341 ** ^SQLite further guarantees that
1342 ** the string will be valid and unchanged until xClose() is
1343 ** called. Because of the previous sentence,
1344 ** the [sqlite3_file] can safely store a pointer to the
1345 ** filename if it needs to remember the filename for some reason.
1346 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1347 ** must invent its own temporary name for the file.  ^Whenever the 
1348 ** xFilename parameter is NULL it will also be the case that the
1349 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1350 **
1351 ** The flags argument to xOpen() includes all bits set in
1352 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1353 ** or [sqlite3_open16()] is used, then flags includes at least
1354 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. 
1355 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1356 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1357 **
1358 ** ^(SQLite will also add one of the following flags to the xOpen()
1359 ** call, depending on the object being opened:
1360 **
1361 ** <ul>
1362 ** <li>  [SQLITE_OPEN_MAIN_DB]
1363 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1364 ** <li>  [SQLITE_OPEN_TEMP_DB]
1365 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1366 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1367 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1368 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1369 ** <li>  [SQLITE_OPEN_WAL]
1370 ** </ul>)^
1371 **
1372 ** The file I/O implementation can use the object type flags to
1373 ** change the way it deals with files.  For example, an application
1374 ** that does not care about crash recovery or rollback might make
1375 ** the open of a journal file a no-op.  Writes to this journal would
1376 ** also be no-ops, and any attempt to read the journal would return
1377 ** SQLITE_IOERR.  Or the implementation might recognize that a database
1378 ** file will be doing page-aligned sector reads and writes in a random
1379 ** order and set up its I/O subsystem accordingly.
1380 **
1381 ** SQLite might also add one of the following flags to the xOpen method:
1382 **
1383 ** <ul>
1384 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1385 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1386 ** </ul>
1387 **
1388 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1389 ** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
1390 ** will be set for TEMP databases and their journals, transient
1391 ** databases, and subjournals.
1392 **
1393 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1394 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1395 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1396 ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the 
1397 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1398 ** be created, and that it is an error if it already exists.
1399 ** It is <i>not</i> used to indicate the file should be opened 
1400 ** for exclusive access.
1401 **
1402 ** ^At least szOsFile bytes of memory are allocated by SQLite
1403 ** to hold the  [sqlite3_file] structure passed as the third
1404 ** argument to xOpen.  The xOpen method does not have to
1405 ** allocate the structure; it should just fill it in.  Note that
1406 ** the xOpen method must set the sqlite3_file.pMethods to either
1407 ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1408 ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1409 ** element will be valid after xOpen returns regardless of the success
1410 ** or failure of the xOpen call.
1411 **
1412 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1413 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1414 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1415 ** to test whether a file is at least readable.   The file can be a
1416 ** directory.
1417 **
1418 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1419 ** output buffer xFullPathname.  The exact size of the output buffer
1420 ** is also passed as a parameter to both  methods. If the output buffer
1421 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1422 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1423 ** to prevent this by setting mxPathname to a sufficiently large value.
1424 **
1425 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1426 ** interfaces are not strictly a part of the filesystem, but they are
1427 ** included in the VFS structure for completeness.
1428 ** The xRandomness() function attempts to return nBytes bytes
1429 ** of good-quality randomness into zOut.  The return value is
1430 ** the actual number of bytes of randomness obtained.
1431 ** The xSleep() method causes the calling thread to sleep for at
1432 ** least the number of microseconds given.  ^The xCurrentTime()
1433 ** method returns a Julian Day Number for the current date and time as
1434 ** a floating point value.
1435 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1436 ** Day Number multipled by 86400000 (the number of milliseconds in 
1437 ** a 24-hour day).  
1438 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1439 ** date and time if that method is available (if iVersion is 2 or 
1440 ** greater and the function pointer is not NULL) and will fall back
1441 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1442 */
1443 typedef struct sqlite3_vfs sqlite3_vfs;
1444 struct sqlite3_vfs {
1445   int iVersion;            /* Structure version number (currently 2) */
1446   int szOsFile;            /* Size of subclassed sqlite3_file */
1447   int mxPathname;          /* Maximum file pathname length */
1448   sqlite3_vfs *pNext;      /* Next registered VFS */
1449   const char *zName;       /* Name of this virtual file system */
1450   void *pAppData;          /* Pointer to application-specific data */
1451   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1452                int flags, int *pOutFlags);
1453   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1454   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1455   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1456   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1457   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1458   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1459   void (*xDlClose)(sqlite3_vfs*, void*);
1460   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1461   int (*xSleep)(sqlite3_vfs*, int microseconds);
1462   int (*xCurrentTime)(sqlite3_vfs*, double*);
1463   int (*xGetLastError)(sqlite3_vfs*, int, char *);
1464   /*
1465   ** The methods above are in version 1 of the sqlite_vfs object
1466   ** definition.  Those that follow are added in version 2 or later
1467   */
1468   int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1469   /*
1470   ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1471   ** New fields may be appended in figure versions.  The iVersion
1472   ** value will increment whenever this happens. 
1473   */
1474 };
1475
1476 /*
1477 ** CAPI3REF: Flags for the xAccess VFS method
1478 **
1479 ** These integer constants can be used as the third parameter to
1480 ** the xAccess method of an [sqlite3_vfs] object.  They determine
1481 ** what kind of permissions the xAccess method is looking for.
1482 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1483 ** simply checks whether the file exists.
1484 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1485 ** checks whether the named directory is both readable and writable
1486 ** (in other words, if files can be added, removed, and renamed within
1487 ** the directory).
1488 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1489 ** [temp_store_directory pragma], though this could change in a future
1490 ** release of SQLite.
1491 ** With SQLITE_ACCESS_READ, the xAccess method
1492 ** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1493 ** currently unused, though it might be used in a future release of
1494 ** SQLite.
1495 */
1496 #define SQLITE_ACCESS_EXISTS    0
1497 #define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1498 #define SQLITE_ACCESS_READ      2   /* Unused */
1499
1500 /*
1501 ** CAPI3REF: Flags for the xShmLock VFS method
1502 **
1503 ** These integer constants define the various locking operations
1504 ** allowed by the xShmLock method of [sqlite3_io_methods].  The
1505 ** following are the only legal combinations of flags to the
1506 ** xShmLock method:
1507 **
1508 ** <ul>
1509 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1510 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1511 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1512 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1513 ** </ul>
1514 **
1515 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1516 ** was given no the corresponding lock.  
1517 **
1518 ** The xShmLock method can transition between unlocked and SHARED or
1519 ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1520 ** and EXCLUSIVE.
1521 */
1522 #define SQLITE_SHM_UNLOCK       1
1523 #define SQLITE_SHM_LOCK         2
1524 #define SQLITE_SHM_SHARED       4
1525 #define SQLITE_SHM_EXCLUSIVE    8
1526
1527 /*
1528 ** CAPI3REF: Maximum xShmLock index
1529 **
1530 ** The xShmLock method on [sqlite3_io_methods] may use values
1531 ** between 0 and this upper bound as its "offset" argument.
1532 ** The SQLite core will never attempt to acquire or release a
1533 ** lock outside of this range
1534 */
1535 #define SQLITE_SHM_NLOCK        8
1536
1537
1538 /*
1539 ** CAPI3REF: Initialize The SQLite Library
1540 **
1541 ** ^The sqlite3_initialize() routine initializes the
1542 ** SQLite library.  ^The sqlite3_shutdown() routine
1543 ** deallocates any resources that were allocated by sqlite3_initialize().
1544 ** These routines are designed to aid in process initialization and
1545 ** shutdown on embedded systems.  Workstation applications using
1546 ** SQLite normally do not need to invoke either of these routines.
1547 **
1548 ** A call to sqlite3_initialize() is an "effective" call if it is
1549 ** the first time sqlite3_initialize() is invoked during the lifetime of
1550 ** the process, or if it is the first time sqlite3_initialize() is invoked
1551 ** following a call to sqlite3_shutdown().  ^(Only an effective call
1552 ** of sqlite3_initialize() does any initialization.  All other calls
1553 ** are harmless no-ops.)^
1554 **
1555 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1556 ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1557 ** an effective call to sqlite3_shutdown() does any deinitialization.
1558 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1559 **
1560 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1561 ** is not.  The sqlite3_shutdown() interface must only be called from a
1562 ** single thread.  All open [database connections] must be closed and all
1563 ** other SQLite resources must be deallocated prior to invoking
1564 ** sqlite3_shutdown().
1565 **
1566 ** Among other things, ^sqlite3_initialize() will invoke
1567 ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1568 ** will invoke sqlite3_os_end().
1569 **
1570 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1571 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1572 ** the library (perhaps it is unable to allocate a needed resource such
1573 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1574 **
1575 ** ^The sqlite3_initialize() routine is called internally by many other
1576 ** SQLite interfaces so that an application usually does not need to
1577 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1578 ** calls sqlite3_initialize() so the SQLite library will be automatically
1579 ** initialized when [sqlite3_open()] is called if it has not be initialized
1580 ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1581 ** compile-time option, then the automatic calls to sqlite3_initialize()
1582 ** are omitted and the application must call sqlite3_initialize() directly
1583 ** prior to using any other SQLite interface.  For maximum portability,
1584 ** it is recommended that applications always invoke sqlite3_initialize()
1585 ** directly prior to using any other SQLite interface.  Future releases
1586 ** of SQLite may require this.  In other words, the behavior exhibited
1587 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1588 ** default behavior in some future release of SQLite.
1589 **
1590 ** The sqlite3_os_init() routine does operating-system specific
1591 ** initialization of the SQLite library.  The sqlite3_os_end()
1592 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
1593 ** performed by these routines include allocation or deallocation
1594 ** of static resources, initialization of global variables,
1595 ** setting up a default [sqlite3_vfs] module, or setting up
1596 ** a default configuration using [sqlite3_config()].
1597 **
1598 ** The application should never invoke either sqlite3_os_init()
1599 ** or sqlite3_os_end() directly.  The application should only invoke
1600 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1601 ** interface is called automatically by sqlite3_initialize() and
1602 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1603 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1604 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1605 ** When [custom builds | built for other platforms]
1606 ** (using the [SQLITE_OS_OTHER=1] compile-time
1607 ** option) the application must supply a suitable implementation for
1608 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1609 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1610 ** must return [SQLITE_OK] on success and some other [error code] upon
1611 ** failure.
1612 */
1613 SQLITE_API int sqlite3_initialize(void);
1614 SQLITE_API int sqlite3_shutdown(void);
1615 SQLITE_API int sqlite3_os_init(void);
1616 SQLITE_API int sqlite3_os_end(void);
1617
1618 /*
1619 ** CAPI3REF: Configuring The SQLite Library
1620 **
1621 ** The sqlite3_config() interface is used to make global configuration
1622 ** changes to SQLite in order to tune SQLite to the specific needs of
1623 ** the application.  The default configuration is recommended for most
1624 ** applications and so this routine is usually not necessary.  It is
1625 ** provided to support rare applications with unusual needs.
1626 **
1627 ** The sqlite3_config() interface is not threadsafe.  The application
1628 ** must insure that no other SQLite interfaces are invoked by other
1629 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1630 ** may only be invoked prior to library initialization using
1631 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1632 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1633 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1634 ** Note, however, that ^sqlite3_config() can be called as part of the
1635 ** implementation of an application-defined [sqlite3_os_init()].
1636 **
1637 ** The first argument to sqlite3_config() is an integer
1638 ** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
1639 ** what property of SQLite is to be configured.  Subsequent arguments
1640 ** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
1641 ** in the first argument.
1642 **
1643 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1644 ** ^If the option is unknown or SQLite is unable to set the option
1645 ** then this routine returns a non-zero [error code].
1646 */
1647 SQLITE_API int sqlite3_config(int, ...);
1648
1649 /*
1650 ** CAPI3REF: Configure database connections
1651 **
1652 ** The sqlite3_db_config() interface is used to make configuration
1653 ** changes to a [database connection].  The interface is similar to
1654 ** [sqlite3_config()] except that the changes apply to a single
1655 ** [database connection] (specified in the first argument).  The
1656 ** sqlite3_db_config() interface should only be used immediately after
1657 ** the database connection is created using [sqlite3_open()],
1658 ** [sqlite3_open16()], or [sqlite3_open_v2()].  
1659 **
1660 ** The second argument to sqlite3_db_config(D,V,...)  is the
1661 ** configuration verb - an integer code that indicates what
1662 ** aspect of the [database connection] is being configured.
1663 ** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE].
1664 ** New verbs are likely to be added in future releases of SQLite.
1665 ** Additional arguments depend on the verb.
1666 **
1667 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1668 ** the call is considered successful.
1669 */
1670 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1671
1672 /*
1673 ** CAPI3REF: Memory Allocation Routines
1674 **
1675 ** An instance of this object defines the interface between SQLite
1676 ** and low-level memory allocation routines.
1677 **
1678 ** This object is used in only one place in the SQLite interface.
1679 ** A pointer to an instance of this object is the argument to
1680 ** [sqlite3_config()] when the configuration option is
1681 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  
1682 ** By creating an instance of this object
1683 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1684 ** during configuration, an application can specify an alternative
1685 ** memory allocation subsystem for SQLite to use for all of its
1686 ** dynamic memory needs.
1687 **
1688 ** Note that SQLite comes with several [built-in memory allocators]
1689 ** that are perfectly adequate for the overwhelming majority of applications
1690 ** and that this object is only useful to a tiny minority of applications
1691 ** with specialized memory allocation requirements.  This object is
1692 ** also used during testing of SQLite in order to specify an alternative
1693 ** memory allocator that simulates memory out-of-memory conditions in
1694 ** order to verify that SQLite recovers gracefully from such
1695 ** conditions.
1696 **
1697 ** The xMalloc and xFree methods must work like the
1698 ** malloc() and free() functions from the standard C library.
1699 ** The xRealloc method must work like realloc() from the standard C library
1700 ** with the exception that if the second argument to xRealloc is zero,
1701 ** xRealloc must be a no-op - it must not perform any allocation or
1702 ** deallocation.  ^SQLite guarantees that the second argument to
1703 ** xRealloc is always a value returned by a prior call to xRoundup.
1704 ** And so in cases where xRoundup always returns a positive number,
1705 ** xRealloc can perform exactly as the standard library realloc() and
1706 ** still be in compliance with this specification.
1707 **
1708 ** xSize should return the allocated size of a memory allocation
1709 ** previously obtained from xMalloc or xRealloc.  The allocated size
1710 ** is always at least as big as the requested size but may be larger.
1711 **
1712 ** The xRoundup method returns what would be the allocated size of
1713 ** a memory allocation given a particular requested size.  Most memory
1714 ** allocators round up memory allocations at least to the next multiple
1715 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1716 ** Every memory allocation request coming in through [sqlite3_malloc()]
1717 ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, 
1718 ** that causes the corresponding memory allocation to fail.
1719 **
1720 ** The xInit method initializes the memory allocator.  (For example,
1721 ** it might allocate any require mutexes or initialize internal data
1722 ** structures.  The xShutdown method is invoked (indirectly) by
1723 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1724 ** by xInit.  The pAppData pointer is used as the only parameter to
1725 ** xInit and xShutdown.
1726 **
1727 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1728 ** the xInit method, so the xInit method need not be threadsafe.  The
1729 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1730 ** not need to be threadsafe either.  For all other methods, SQLite
1731 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1732 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1733 ** it is by default) and so the methods are automatically serialized.
1734 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1735 ** methods must be threadsafe or else make their own arrangements for
1736 ** serialization.
1737 **
1738 ** SQLite will never invoke xInit() more than once without an intervening
1739 ** call to xShutdown().
1740 */
1741 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1742 struct sqlite3_mem_methods {
1743   void *(*xMalloc)(int);         /* Memory allocation function */
1744   void (*xFree)(void*);          /* Free a prior allocation */
1745   void *(*xRealloc)(void*,int);  /* Resize an allocation */
1746   int (*xSize)(void*);           /* Return the size of an allocation */
1747   int (*xRoundup)(int);          /* Round up request size to allocation size */
1748   int (*xInit)(void*);           /* Initialize the memory allocator */
1749   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1750   void *pAppData;                /* Argument to xInit() and xShutdown() */
1751 };
1752
1753 /*
1754 ** CAPI3REF: Configuration Options
1755 **
1756 ** These constants are the available integer configuration options that
1757 ** can be passed as the first argument to the [sqlite3_config()] interface.
1758 **
1759 ** New configuration options may be added in future releases of SQLite.
1760 ** Existing configuration options might be discontinued.  Applications
1761 ** should check the return code from [sqlite3_config()] to make sure that
1762 ** the call worked.  The [sqlite3_config()] interface will return a
1763 ** non-zero [error code] if a discontinued or unsupported configuration option
1764 ** is invoked.
1765 **
1766 ** <dl>
1767 ** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1768 ** <dd>There are no arguments to this option.  ^This option sets the
1769 ** [threading mode] to Single-thread.  In other words, it disables
1770 ** all mutexing and puts SQLite into a mode where it can only be used
1771 ** by a single thread.   ^If SQLite is compiled with
1772 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1773 ** it is not possible to change the [threading mode] from its default
1774 ** value of Single-thread and so [sqlite3_config()] will return 
1775 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1776 ** configuration option.</dd>
1777 **
1778 ** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1779 ** <dd>There are no arguments to this option.  ^This option sets the
1780 ** [threading mode] to Multi-thread.  In other words, it disables
1781 ** mutexing on [database connection] and [prepared statement] objects.
1782 ** The application is responsible for serializing access to
1783 ** [database connections] and [prepared statements].  But other mutexes
1784 ** are enabled so that SQLite will be safe to use in a multi-threaded
1785 ** environment as long as no two threads attempt to use the same
1786 ** [database connection] at the same time.  ^If SQLite is compiled with
1787 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1788 ** it is not possible to set the Multi-thread [threading mode] and
1789 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1790 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1791 **
1792 ** <dt>SQLITE_CONFIG_SERIALIZED</dt>
1793 ** <dd>There are no arguments to this option.  ^This option sets the
1794 ** [threading mode] to Serialized. In other words, this option enables
1795 ** all mutexes including the recursive
1796 ** mutexes on [database connection] and [prepared statement] objects.
1797 ** In this mode (which is the default when SQLite is compiled with
1798 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1799 ** to [database connections] and [prepared statements] so that the
1800 ** application is free to use the same [database connection] or the
1801 ** same [prepared statement] in different threads at the same time.
1802 ** ^If SQLite is compiled with
1803 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1804 ** it is not possible to set the Serialized [threading mode] and
1805 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1806 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1807 **
1808 ** <dt>SQLITE_CONFIG_MALLOC</dt>
1809 ** <dd> ^(This option takes a single argument which is a pointer to an
1810 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1811 ** alternative low-level memory allocation routines to be used in place of
1812 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
1813 ** its own private copy of the content of the [sqlite3_mem_methods] structure
1814 ** before the [sqlite3_config()] call returns.</dd>
1815 **
1816 ** <dt>SQLITE_CONFIG_GETMALLOC</dt>
1817 ** <dd> ^(This option takes a single argument which is a pointer to an
1818 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1819 ** structure is filled with the currently defined memory allocation routines.)^
1820 ** This option can be used to overload the default memory allocation
1821 ** routines with a wrapper that simulations memory allocation failure or
1822 ** tracks memory usage, for example. </dd>
1823 **
1824 ** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1825 ** <dd> ^This option takes single argument of type int, interpreted as a 
1826 ** boolean, which enables or disables the collection of memory allocation 
1827 ** statistics. ^(When memory allocation statistics are disabled, the 
1828 ** following SQLite interfaces become non-operational:
1829 **   <ul>
1830 **   <li> [sqlite3_memory_used()]
1831 **   <li> [sqlite3_memory_highwater()]
1832 **   <li> [sqlite3_soft_heap_limit64()]
1833 **   <li> [sqlite3_status()]
1834 **   </ul>)^
1835 ** ^Memory allocation statistics are enabled by default unless SQLite is
1836 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1837 ** allocation statistics are disabled by default.
1838 ** </dd>
1839 **
1840 ** <dt>SQLITE_CONFIG_SCRATCH</dt>
1841 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1842 ** scratch memory.  There are three arguments:  A pointer an 8-byte
1843 ** aligned memory buffer from which the scrach allocations will be
1844 ** drawn, the size of each scratch allocation (sz),
1845 ** and the maximum number of scratch allocations (N).  The sz
1846 ** argument must be a multiple of 16.
1847 ** The first argument must be a pointer to an 8-byte aligned buffer
1848 ** of at least sz*N bytes of memory.
1849 ** ^SQLite will use no more than two scratch buffers per thread.  So
1850 ** N should be set to twice the expected maximum number of threads.
1851 ** ^SQLite will never require a scratch buffer that is more than 6
1852 ** times the database page size. ^If SQLite needs needs additional
1853 ** scratch memory beyond what is provided by this configuration option, then 
1854 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1855 **
1856 ** <dt>SQLITE_CONFIG_PAGECACHE</dt>
1857 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1858 ** the database page cache with the default page cache implemenation.  
1859 ** This configuration should not be used if an application-define page
1860 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
1861 ** There are three arguments to this option: A pointer to 8-byte aligned
1862 ** memory, the size of each page buffer (sz), and the number of pages (N).
1863 ** The sz argument should be the size of the largest database page
1864 ** (a power of two between 512 and 32768) plus a little extra for each
1865 ** page header.  ^The page header size is 20 to 40 bytes depending on
1866 ** the host architecture.  ^It is harmless, apart from the wasted memory,
1867 ** to make sz a little too large.  The first
1868 ** argument should point to an allocation of at least sz*N bytes of memory.
1869 ** ^SQLite will use the memory provided by the first argument to satisfy its
1870 ** memory needs for the first N pages that it adds to cache.  ^If additional
1871 ** page cache memory is needed beyond what is provided by this option, then
1872 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1873 ** The pointer in the first argument must
1874 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1875 ** will be undefined.</dd>
1876 **
1877 ** <dt>SQLITE_CONFIG_HEAP</dt>
1878 ** <dd> ^This option specifies a static memory buffer that SQLite will use
1879 ** for all of its dynamic memory allocation needs beyond those provided
1880 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1881 ** There are three arguments: An 8-byte aligned pointer to the memory,
1882 ** the number of bytes in the memory buffer, and the minimum allocation size.
1883 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1884 ** to using its default memory allocator (the system malloc() implementation),
1885 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
1886 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1887 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1888 ** allocator is engaged to handle all of SQLites memory allocation needs.
1889 ** The first pointer (the memory pointer) must be aligned to an 8-byte
1890 ** boundary or subsequent behavior of SQLite will be undefined.</dd>
1891 **
1892 ** <dt>SQLITE_CONFIG_MUTEX</dt>
1893 ** <dd> ^(This option takes a single argument which is a pointer to an
1894 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
1895 ** alternative low-level mutex routines to be used in place
1896 ** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
1897 ** content of the [sqlite3_mutex_methods] structure before the call to
1898 ** [sqlite3_config()] returns. ^If SQLite is compiled with
1899 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1900 ** the entire mutexing subsystem is omitted from the build and hence calls to
1901 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1902 ** return [SQLITE_ERROR].</dd>
1903 **
1904 ** <dt>SQLITE_CONFIG_GETMUTEX</dt>
1905 ** <dd> ^(This option takes a single argument which is a pointer to an
1906 ** instance of the [sqlite3_mutex_methods] structure.  The
1907 ** [sqlite3_mutex_methods]
1908 ** structure is filled with the currently defined mutex routines.)^
1909 ** This option can be used to overload the default mutex allocation
1910 ** routines with a wrapper used to track mutex usage for performance
1911 ** profiling or testing, for example.   ^If SQLite is compiled with
1912 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1913 ** the entire mutexing subsystem is omitted from the build and hence calls to
1914 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1915 ** return [SQLITE_ERROR].</dd>
1916 **
1917 ** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1918 ** <dd> ^(This option takes two arguments that determine the default
1919 ** memory allocation for the lookaside memory allocator on each
1920 ** [database connection].  The first argument is the
1921 ** size of each lookaside buffer slot and the second is the number of
1922 ** slots allocated to each database connection.)^  ^(This option sets the
1923 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1924 ** verb to [sqlite3_db_config()] can be used to change the lookaside
1925 ** configuration on individual connections.)^ </dd>
1926 **
1927 ** <dt>SQLITE_CONFIG_PCACHE</dt>
1928 ** <dd> ^(This option takes a single argument which is a pointer to
1929 ** an [sqlite3_pcache_methods] object.  This object specifies the interface
1930 ** to a custom page cache implementation.)^  ^SQLite makes a copy of the
1931 ** object and uses it for page cache memory allocations.</dd>
1932 **
1933 ** <dt>SQLITE_CONFIG_GETPCACHE</dt>
1934 ** <dd> ^(This option takes a single argument which is a pointer to an
1935 ** [sqlite3_pcache_methods] object.  SQLite copies of the current
1936 ** page cache implementation into that object.)^ </dd>
1937 **
1938 ** <dt>SQLITE_CONFIG_LOG</dt>
1939 ** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
1940 ** function with a call signature of void(*)(void*,int,const char*), 
1941 ** and a pointer to void. ^If the function pointer is not NULL, it is
1942 ** invoked by [sqlite3_log()] to process each logging event.  ^If the
1943 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
1944 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
1945 ** passed through as the first parameter to the application-defined logger
1946 ** function whenever that function is invoked.  ^The second parameter to
1947 ** the logger function is a copy of the first parameter to the corresponding
1948 ** [sqlite3_log()] call and is intended to be a [result code] or an
1949 ** [extended result code].  ^The third parameter passed to the logger is
1950 ** log message after formatting via [sqlite3_snprintf()].
1951 ** The SQLite logging interface is not reentrant; the logger function
1952 ** supplied by the application must not invoke any SQLite interface.
1953 ** In a multi-threaded application, the application-defined logger
1954 ** function must be threadsafe. </dd>
1955 **
1956 ** </dl>
1957 */
1958 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
1959 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
1960 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
1961 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
1962 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
1963 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
1964 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
1965 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
1966 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
1967 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
1968 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
1969 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 
1970 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
1971 #define SQLITE_CONFIG_PCACHE       14  /* sqlite3_pcache_methods* */
1972 #define SQLITE_CONFIG_GETPCACHE    15  /* sqlite3_pcache_methods* */
1973 #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
1974
1975 /*
1976 ** CAPI3REF: Database Connection Configuration Options
1977 **
1978 ** These constants are the available integer configuration options that
1979 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
1980 **
1981 ** New configuration options may be added in future releases of SQLite.
1982 ** Existing configuration options might be discontinued.  Applications
1983 ** should check the return code from [sqlite3_db_config()] to make sure that
1984 ** the call worked.  ^The [sqlite3_db_config()] interface will return a
1985 ** non-zero [error code] if a discontinued or unsupported configuration option
1986 ** is invoked.
1987 **
1988 ** <dl>
1989 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
1990 ** <dd> ^This option takes three additional arguments that determine the 
1991 ** [lookaside memory allocator] configuration for the [database connection].
1992 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
1993 ** pointer to an memory buffer to use for lookaside memory.
1994 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
1995 ** may be NULL in which case SQLite will allocate the
1996 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
1997 ** size of each lookaside buffer slot.  ^The third argument is the number of
1998 ** slots.  The size of the buffer in the first argument must be greater than
1999 ** or equal to the product of the second and third arguments.  The buffer
2000 ** must be aligned to an 8-byte boundary.  ^If the second argument to
2001 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2002 ** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
2003 ** configuration for a database connection can only be changed when that
2004 ** connection is not currently using lookaside memory, or in other words
2005 ** when the "current value" returned by
2006 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2007 ** Any attempt to change the lookaside memory configuration when lookaside
2008 ** memory is in use leaves the configuration unchanged and returns 
2009 ** [SQLITE_BUSY].)^</dd>
2010 **
2011 ** </dl>
2012 */
2013 #define SQLITE_DBCONFIG_LOOKASIDE    1001  /* void* int int */
2014
2015
2016 /*
2017 ** CAPI3REF: Enable Or Disable Extended Result Codes
2018 **
2019 ** ^The sqlite3_extended_result_codes() routine enables or disables the
2020 ** [extended result codes] feature of SQLite. ^The extended result
2021 ** codes are disabled by default for historical compatibility.
2022 */
2023 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
2024
2025 /*
2026 ** CAPI3REF: Last Insert Rowid
2027 **
2028 ** ^Each entry in an SQLite table has a unique 64-bit signed
2029 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2030 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2031 ** names are not also used by explicitly declared columns. ^If
2032 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
2033 ** is another alias for the rowid.
2034 **
2035 ** ^This routine returns the [rowid] of the most recent
2036 ** successful [INSERT] into the database from the [database connection]
2037 ** in the first argument.  ^If no successful [INSERT]s
2038 ** have ever occurred on that database connection, zero is returned.
2039 **
2040 ** ^(If an [INSERT] occurs within a trigger, then the [rowid] of the inserted
2041 ** row is returned by this routine as long as the trigger is running.
2042 ** But once the trigger terminates, the value returned by this routine
2043 ** reverts to the last value inserted before the trigger fired.)^
2044 **
2045 ** ^An [INSERT] that fails due to a constraint violation is not a
2046 ** successful [INSERT] and does not change the value returned by this
2047 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2048 ** and INSERT OR ABORT make no changes to the return value of this
2049 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
2050 ** encounters a constraint violation, it does not fail.  The
2051 ** INSERT continues to completion after deleting rows that caused
2052 ** the constraint problem so INSERT OR REPLACE will always change
2053 ** the return value of this interface.)^
2054 **
2055 ** ^For the purposes of this routine, an [INSERT] is considered to
2056 ** be successful even if it is subsequently rolled back.
2057 **
2058 ** This function is accessible to SQL statements via the
2059 ** [last_insert_rowid() SQL function].
2060 **
2061 ** If a separate thread performs a new [INSERT] on the same
2062 ** database connection while the [sqlite3_last_insert_rowid()]
2063 ** function is running and thus changes the last insert [rowid],
2064 ** then the value returned by [sqlite3_last_insert_rowid()] is
2065 ** unpredictable and might not equal either the old or the new
2066 ** last insert [rowid].
2067 */
2068 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2069
2070 /*
2071 ** CAPI3REF: Count The Number Of Rows Modified
2072 **
2073 ** ^This function returns the number of database rows that were changed
2074 ** or inserted or deleted by the most recently completed SQL statement
2075 ** on the [database connection] specified by the first parameter.
2076 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2077 ** or [DELETE] statement are counted.  Auxiliary changes caused by
2078 ** triggers or [foreign key actions] are not counted.)^ Use the
2079 ** [sqlite3_total_changes()] function to find the total number of changes
2080 ** including changes caused by triggers and foreign key actions.
2081 **
2082 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2083 ** are not counted.  Only real table changes are counted.
2084 **
2085 ** ^(A "row change" is a change to a single row of a single table
2086 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
2087 ** are changed as side effects of [REPLACE] constraint resolution,
2088 ** rollback, ABORT processing, [DROP TABLE], or by any other
2089 ** mechanisms do not count as direct row changes.)^
2090 **
2091 ** A "trigger context" is a scope of execution that begins and
2092 ** ends with the script of a [CREATE TRIGGER | trigger]. 
2093 ** Most SQL statements are
2094 ** evaluated outside of any trigger.  This is the "top level"
2095 ** trigger context.  If a trigger fires from the top level, a
2096 ** new trigger context is entered for the duration of that one
2097 ** trigger.  Subtriggers create subcontexts for their duration.
2098 **
2099 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
2100 ** not create a new trigger context.
2101 **
2102 ** ^This function returns the number of direct row changes in the
2103 ** most recent INSERT, UPDATE, or DELETE statement within the same
2104 ** trigger context.
2105 **
2106 ** ^Thus, when called from the top level, this function returns the
2107 ** number of changes in the most recent INSERT, UPDATE, or DELETE
2108 ** that also occurred at the top level.  ^(Within the body of a trigger,
2109 ** the sqlite3_changes() interface can be called to find the number of
2110 ** changes in the most recently completed INSERT, UPDATE, or DELETE
2111 ** statement within the body of the same trigger.
2112 ** However, the number returned does not include changes
2113 ** caused by subtriggers since those have their own context.)^
2114 **
2115 ** See also the [sqlite3_total_changes()] interface, the
2116 ** [count_changes pragma], and the [changes() SQL function].
2117 **
2118 ** If a separate thread makes changes on the same database connection
2119 ** while [sqlite3_changes()] is running then the value returned
2120 ** is unpredictable and not meaningful.
2121 */
2122 SQLITE_API int sqlite3_changes(sqlite3*);
2123
2124 /*
2125 ** CAPI3REF: Total Number Of Rows Modified
2126 **
2127 ** ^This function returns the number of row changes caused by [INSERT],
2128 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2129 ** ^(The count returned by sqlite3_total_changes() includes all changes
2130 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
2131 ** [foreign key actions]. However,
2132 ** the count does not include changes used to implement [REPLACE] constraints,
2133 ** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
2134 ** count does not include rows of views that fire an [INSTEAD OF trigger],
2135 ** though if the INSTEAD OF trigger makes changes of its own, those changes 
2136 ** are counted.)^
2137 ** ^The sqlite3_total_changes() function counts the changes as soon as
2138 ** the statement that makes them is completed (when the statement handle
2139 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
2140 **
2141 ** See also the [sqlite3_changes()] interface, the
2142 ** [count_changes pragma], and the [total_changes() SQL function].
2143 **
2144 ** If a separate thread makes changes on the same database connection
2145 ** while [sqlite3_total_changes()] is running then the value
2146 ** returned is unpredictable and not meaningful.
2147 */
2148 SQLITE_API int sqlite3_total_changes(sqlite3*);
2149
2150 /*
2151 ** CAPI3REF: Interrupt A Long-Running Query
2152 **
2153 ** ^This function causes any pending database operation to abort and
2154 ** return at its earliest opportunity. This routine is typically
2155 ** called in response to a user action such as pressing "Cancel"
2156 ** or Ctrl-C where the user wants a long query operation to halt
2157 ** immediately.
2158 **
2159 ** ^It is safe to call this routine from a thread different from the
2160 ** thread that is currently running the database operation.  But it
2161 ** is not safe to call this routine with a [database connection] that
2162 ** is closed or might close before sqlite3_interrupt() returns.
2163 **
2164 ** ^If an SQL operation is very nearly finished at the time when
2165 ** sqlite3_interrupt() is called, then it might not have an opportunity
2166 ** to be interrupted and might continue to completion.
2167 **
2168 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2169 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2170 ** that is inside an explicit transaction, then the entire transaction
2171 ** will be rolled back automatically.
2172 **
2173 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2174 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
2175 ** that are started after the sqlite3_interrupt() call and before the 
2176 ** running statements reaches zero are interrupted as if they had been
2177 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2178 ** that are started after the running statement count reaches zero are
2179 ** not effected by the sqlite3_interrupt().
2180 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2181 ** SQL statements is a no-op and has no effect on SQL statements
2182 ** that are started after the sqlite3_interrupt() call returns.
2183 **
2184 ** If the database connection closes while [sqlite3_interrupt()]
2185 ** is running then bad things will likely happen.
2186 */
2187 SQLITE_API void sqlite3_interrupt(sqlite3*);
2188
2189 /*
2190 ** CAPI3REF: Determine If An SQL Statement Is Complete
2191 **
2192 ** These routines are useful during command-line input to determine if the
2193 ** currently entered text seems to form a complete SQL statement or
2194 ** if additional input is needed before sending the text into
2195 ** SQLite for parsing.  ^These routines return 1 if the input string
2196 ** appears to be a complete SQL statement.  ^A statement is judged to be
2197 ** complete if it ends with a semicolon token and is not a prefix of a
2198 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2199 ** string literals or quoted identifier names or comments are not
2200 ** independent tokens (they are part of the token in which they are
2201 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
2202 ** and comments that follow the final semicolon are ignored.
2203 **
2204 ** ^These routines return 0 if the statement is incomplete.  ^If a
2205 ** memory allocation fails, then SQLITE_NOMEM is returned.
2206 **
2207 ** ^These routines do not parse the SQL statements thus
2208 ** will not detect syntactically incorrect SQL.
2209 **
2210 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior 
2211 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2212 ** automatically by sqlite3_complete16().  If that initialization fails,
2213 ** then the return value from sqlite3_complete16() will be non-zero
2214 ** regardless of whether or not the input SQL is complete.)^
2215 **
2216 ** The input to [sqlite3_complete()] must be a zero-terminated
2217 ** UTF-8 string.
2218 **
2219 ** The input to [sqlite3_complete16()] must be a zero-terminated
2220 ** UTF-16 string in native byte order.
2221 */
2222 SQLITE_API int sqlite3_complete(const char *sql);
2223 SQLITE_API int sqlite3_complete16(const void *sql);
2224
2225 /*
2226 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2227 **
2228 ** ^This routine sets a callback function that might be invoked whenever
2229 ** an attempt is made to open a database table that another thread
2230 ** or process has locked.
2231 **
2232 ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2233 ** is returned immediately upon encountering the lock.  ^If the busy callback
2234 ** is not NULL, then the callback might be invoked with two arguments.
2235 **
2236 ** ^The first argument to the busy handler is a copy of the void* pointer which
2237 ** is the third argument to sqlite3_busy_handler().  ^The second argument to
2238 ** the busy handler callback is the number of times that the busy handler has
2239 ** been invoked for this locking event.  ^If the
2240 ** busy callback returns 0, then no additional attempts are made to
2241 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2242 ** ^If the callback returns non-zero, then another attempt
2243 ** is made to open the database for reading and the cycle repeats.
2244 **
2245 ** The presence of a busy handler does not guarantee that it will be invoked
2246 ** when there is lock contention. ^If SQLite determines that invoking the busy
2247 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2248 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2249 ** Consider a scenario where one process is holding a read lock that
2250 ** it is trying to promote to a reserved lock and
2251 ** a second process is holding a reserved lock that it is trying
2252 ** to promote to an exclusive lock.  The first process cannot proceed
2253 ** because it is blocked by the second and the second process cannot
2254 ** proceed because it is blocked by the first.  If both processes
2255 ** invoke the busy handlers, neither will make any progress.  Therefore,
2256 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2257 ** will induce the first process to release its read lock and allow
2258 ** the second process to proceed.
2259 **
2260 ** ^The default busy callback is NULL.
2261 **
2262 ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2263 ** when SQLite is in the middle of a large transaction where all the
2264 ** changes will not fit into the in-memory cache.  SQLite will
2265 ** already hold a RESERVED lock on the database file, but it needs
2266 ** to promote this lock to EXCLUSIVE so that it can spill cache
2267 ** pages into the database file without harm to concurrent
2268 ** readers.  ^If it is unable to promote the lock, then the in-memory
2269 ** cache will be left in an inconsistent state and so the error
2270 ** code is promoted from the relatively benign [SQLITE_BUSY] to
2271 ** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
2272 ** forces an automatic rollback of the changes.  See the
2273 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2274 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2275 ** this is important.
2276 **
2277 ** ^(There can only be a single busy handler defined for each
2278 ** [database connection].  Setting a new busy handler clears any
2279 ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2280 ** will also set or clear the busy handler.
2281 **
2282 ** The busy callback should not take any actions which modify the
2283 ** database connection that invoked the busy handler.  Any such actions
2284 ** result in undefined behavior.
2285 ** 
2286 ** A busy handler must not close the database connection
2287 ** or [prepared statement] that invoked the busy handler.
2288 */
2289 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2290
2291 /*
2292 ** CAPI3REF: Set A Busy Timeout
2293 **
2294 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2295 ** for a specified amount of time when a table is locked.  ^The handler
2296 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2297 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2298 ** the handler returns 0 which causes [sqlite3_step()] to return
2299 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2300 **
2301 ** ^Calling this routine with an argument less than or equal to zero
2302 ** turns off all busy handlers.
2303 **
2304 ** ^(There can only be a single busy handler for a particular
2305 ** [database connection] any any given moment.  If another busy handler
2306 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
2307 ** this routine, that other busy handler is cleared.)^
2308 */
2309 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2310
2311 /*
2312 ** CAPI3REF: Convenience Routines For Running Queries
2313 **
2314 ** This is a legacy interface that is preserved for backwards compatibility.
2315 ** Use of this interface is not recommended.
2316 **
2317 ** Definition: A <b>result table</b> is memory data structure created by the
2318 ** [sqlite3_get_table()] interface.  A result table records the
2319 ** complete query results from one or more queries.
2320 **
2321 ** The table conceptually has a number of rows and columns.  But
2322 ** these numbers are not part of the result table itself.  These
2323 ** numbers are obtained separately.  Let N be the number of rows
2324 ** and M be the number of columns.
2325 **
2326 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2327 ** There are (N+1)*M elements in the array.  The first M pointers point
2328 ** to zero-terminated strings that  contain the names of the columns.
2329 ** The remaining entries all point to query results.  NULL values result
2330 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2331 ** string representation as returned by [sqlite3_column_text()].
2332 **
2333 ** A result table might consist of one or more memory allocations.
2334 ** It is not safe to pass a result table directly to [sqlite3_free()].
2335 ** A result table should be deallocated using [sqlite3_free_table()].
2336 **
2337 ** ^(As an example of the result table format, suppose a query result
2338 ** is as follows:
2339 **
2340 ** <blockquote><pre>
2341 **        Name        | Age
2342 **        -----------------------
2343 **        Alice       | 43
2344 **        Bob         | 28
2345 **        Cindy       | 21
2346 ** </pre></blockquote>
2347 **
2348 ** There are two column (M==2) and three rows (N==3).  Thus the
2349 ** result table has 8 entries.  Suppose the result table is stored
2350 ** in an array names azResult.  Then azResult holds this content:
2351 **
2352 ** <blockquote><pre>
2353 **        azResult&#91;0] = "Name";
2354 **        azResult&#91;1] = "Age";
2355 **        azResult&#91;2] = "Alice";
2356 **        azResult&#91;3] = "43";
2357 **        azResult&#91;4] = "Bob";
2358 **        azResult&#91;5] = "28";
2359 **        azResult&#91;6] = "Cindy";
2360 **        azResult&#91;7] = "21";
2361 ** </pre></blockquote>)^
2362 **
2363 ** ^The sqlite3_get_table() function evaluates one or more
2364 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2365 ** string of its 2nd parameter and returns a result table to the
2366 ** pointer given in its 3rd parameter.
2367 **
2368 ** After the application has finished with the result from sqlite3_get_table(),
2369 ** it must pass the result table pointer to sqlite3_free_table() in order to
2370 ** release the memory that was malloced.  Because of the way the
2371 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2372 ** function must not try to call [sqlite3_free()] directly.  Only
2373 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2374 **
2375 ** The sqlite3_get_table() interface is implemented as a wrapper around
2376 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2377 ** to any internal data structures of SQLite.  It uses only the public
2378 ** interface defined here.  As a consequence, errors that occur in the
2379 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2380 ** reflected in subsequent calls to [sqlite3_errcode()] or
2381 ** [sqlite3_errmsg()].
2382 */
2383 SQLITE_API int sqlite3_get_table(
2384   sqlite3 *db,          /* An open database */
2385   const char *zSql,     /* SQL to be evaluated */
2386   char ***pazResult,    /* Results of the query */
2387   int *pnRow,           /* Number of result rows written here */
2388   int *pnColumn,        /* Number of result columns written here */
2389   char **pzErrmsg       /* Error msg written here */
2390 );
2391 SQLITE_API void sqlite3_free_table(char **result);
2392
2393 /*
2394 ** CAPI3REF: Formatted String Printing Functions
2395 **
2396 ** These routines are work-alikes of the "printf()" family of functions
2397 ** from the standard C library.
2398 **
2399 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2400 ** results into memory obtained from [sqlite3_malloc()].
2401 ** The strings returned by these two routines should be
2402 ** released by [sqlite3_free()].  ^Both routines return a
2403 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2404 ** memory to hold the resulting string.
2405 **
2406 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2407 ** the standard C library.  The result is written into the
2408 ** buffer supplied as the second parameter whose size is given by
2409 ** the first parameter. Note that the order of the
2410 ** first two parameters is reversed from snprintf().)^  This is an
2411 ** historical accident that cannot be fixed without breaking
2412 ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2413 ** returns a pointer to its buffer instead of the number of
2414 ** characters actually written into the buffer.)^  We admit that
2415 ** the number of characters written would be a more useful return
2416 ** value but we cannot change the implementation of sqlite3_snprintf()
2417 ** now without breaking compatibility.
2418 **
2419 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2420 ** guarantees that the buffer is always zero-terminated.  ^The first
2421 ** parameter "n" is the total size of the buffer, including space for
2422 ** the zero terminator.  So the longest string that can be completely
2423 ** written will be n-1 characters.
2424 **
2425 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2426 **
2427 ** These routines all implement some additional formatting
2428 ** options that are useful for constructing SQL statements.
2429 ** All of the usual printf() formatting options apply.  In addition, there
2430 ** is are "%q", "%Q", and "%z" options.
2431 **
2432 ** ^(The %q option works like %s in that it substitutes a null-terminated
2433 ** string from the argument list.  But %q also doubles every '\'' character.
2434 ** %q is designed for use inside a string literal.)^  By doubling each '\''
2435 ** character it escapes that character and allows it to be inserted into
2436 ** the string.
2437 **
2438 ** For example, assume the string variable zText contains text as follows:
2439 **
2440 ** <blockquote><pre>
2441 **  char *zText = "It's a happy day!";
2442 ** </pre></blockquote>
2443 **
2444 ** One can use this text in an SQL statement as follows:
2445 **
2446 ** <blockquote><pre>
2447 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2448 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2449 **  sqlite3_free(zSQL);
2450 ** </pre></blockquote>
2451 **
2452 ** Because the %q format string is used, the '\'' character in zText
2453 ** is escaped and the SQL generated is as follows:
2454 **
2455 ** <blockquote><pre>
2456 **  INSERT INTO table1 VALUES('It''s a happy day!')
2457 ** </pre></blockquote>
2458 **
2459 ** This is correct.  Had we used %s instead of %q, the generated SQL
2460 ** would have looked like this:
2461 **
2462 ** <blockquote><pre>
2463 **  INSERT INTO table1 VALUES('It's a happy day!');
2464 ** </pre></blockquote>
2465 **
2466 ** This second example is an SQL syntax error.  As a general rule you should
2467 ** always use %q instead of %s when inserting text into a string literal.
2468 **
2469 ** ^(The %Q option works like %q except it also adds single quotes around
2470 ** the outside of the total string.  Additionally, if the parameter in the
2471 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2472 ** single quotes).)^  So, for example, one could say:
2473 **
2474 ** <blockquote><pre>
2475 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2476 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2477 **  sqlite3_free(zSQL);
2478 ** </pre></blockquote>
2479 **
2480 ** The code above will render a correct SQL statement in the zSQL
2481 ** variable even if the zText variable is a NULL pointer.
2482 **
2483 ** ^(The "%z" formatting option works like "%s" but with the
2484 ** addition that after the string has been read and copied into
2485 ** the result, [sqlite3_free()] is called on the input string.)^
2486 */
2487 SQLITE_API char *sqlite3_mprintf(const char*,...);
2488 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2489 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2490 SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
2491
2492 /*
2493 ** CAPI3REF: Memory Allocation Subsystem
2494 **
2495 ** The SQLite core uses these three routines for all of its own
2496 ** internal memory allocation needs. "Core" in the previous sentence
2497 ** does not include operating-system specific VFS implementation.  The
2498 ** Windows VFS uses native malloc() and free() for some operations.
2499 **
2500 ** ^The sqlite3_malloc() routine returns a pointer to a block
2501 ** of memory at least N bytes in length, where N is the parameter.
2502 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2503 ** memory, it returns a NULL pointer.  ^If the parameter N to
2504 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2505 ** a NULL pointer.
2506 **
2507 ** ^Calling sqlite3_free() with a pointer previously returned
2508 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2509 ** that it might be reused.  ^The sqlite3_free() routine is
2510 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2511 ** to sqlite3_free() is harmless.  After being freed, memory
2512 ** should neither be read nor written.  Even reading previously freed
2513 ** memory might result in a segmentation fault or other severe error.
2514 ** Memory corruption, a segmentation fault, or other severe error
2515 ** might result if sqlite3_free() is called with a non-NULL pointer that
2516 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2517 **
2518 ** ^(The sqlite3_realloc() interface attempts to resize a
2519 ** prior memory allocation to be at least N bytes, where N is the
2520 ** second parameter.  The memory allocation to be resized is the first
2521 ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2522 ** is a NULL pointer then its behavior is identical to calling
2523 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2524 ** ^If the second parameter to sqlite3_realloc() is zero or
2525 ** negative then the behavior is exactly the same as calling
2526 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2527 ** ^sqlite3_realloc() returns a pointer to a memory allocation
2528 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2529 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2530 ** of the prior allocation are copied into the beginning of buffer returned
2531 ** by sqlite3_realloc() and the prior allocation is freed.
2532 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
2533 ** is not freed.
2534 **
2535 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2536 ** is always aligned to at least an 8 byte boundary, or to a
2537 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2538 ** option is used.
2539 **
2540 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2541 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2542 ** implementation of these routines to be omitted.  That capability
2543 ** is no longer provided.  Only built-in memory allocators can be used.
2544 **
2545 ** The Windows OS interface layer calls
2546 ** the system malloc() and free() directly when converting
2547 ** filenames between the UTF-8 encoding used by SQLite
2548 ** and whatever filename encoding is used by the particular Windows
2549 ** installation.  Memory allocation errors are detected, but
2550 ** they are reported back as [SQLITE_CANTOPEN] or
2551 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2552 **
2553 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2554 ** must be either NULL or else pointers obtained from a prior
2555 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2556 ** not yet been released.
2557 **
2558 ** The application must not read or write any part of
2559 ** a block of memory after it has been released using
2560 ** [sqlite3_free()] or [sqlite3_realloc()].
2561 */
2562 SQLITE_API void *sqlite3_malloc(int);
2563 SQLITE_API void *sqlite3_realloc(void*, int);
2564 SQLITE_API void sqlite3_free(void*);
2565
2566 /*
2567 ** CAPI3REF: Memory Allocator Statistics
2568 **
2569 ** SQLite provides these two interfaces for reporting on the status
2570 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2571 ** routines, which form the built-in memory allocation subsystem.
2572 **
2573 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2574 ** of memory currently outstanding (malloced but not freed).
2575 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2576 ** value of [sqlite3_memory_used()] since the high-water mark
2577 ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2578 ** [sqlite3_memory_highwater()] include any overhead
2579 ** added by SQLite in its implementation of [sqlite3_malloc()],
2580 ** but not overhead added by the any underlying system library
2581 ** routines that [sqlite3_malloc()] may call.
2582 **
2583 ** ^The memory high-water mark is reset to the current value of
2584 ** [sqlite3_memory_used()] if and only if the parameter to
2585 ** [sqlite3_memory_highwater()] is true.  ^The value returned
2586 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2587 ** prior to the reset.
2588 */
2589 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2590 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2591
2592 /*
2593 ** CAPI3REF: Pseudo-Random Number Generator
2594 **
2595 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2596 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2597 ** already uses the largest possible [ROWID].  The PRNG is also used for
2598 ** the build-in random() and randomblob() SQL functions.  This interface allows
2599 ** applications to access the same PRNG for other purposes.
2600 **
2601 ** ^A call to this routine stores N bytes of randomness into buffer P.
2602 **
2603 ** ^The first time this routine is invoked (either internally or by
2604 ** the application) the PRNG is seeded using randomness obtained
2605 ** from the xRandomness method of the default [sqlite3_vfs] object.
2606 ** ^On all subsequent invocations, the pseudo-randomness is generated
2607 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2608 ** method.
2609 */
2610 SQLITE_API void sqlite3_randomness(int N, void *P);
2611
2612 /*
2613 ** CAPI3REF: Compile-Time Authorization Callbacks
2614 **
2615 ** ^This routine registers a authorizer callback with a particular
2616 ** [database connection], supplied in the first argument.
2617 ** ^The authorizer callback is invoked as SQL statements are being compiled
2618 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2619 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2620 ** points during the compilation process, as logic is being created
2621 ** to perform various actions, the authorizer callback is invoked to
2622 ** see if those actions are allowed.  ^The authorizer callback should
2623 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2624 ** specific action but allow the SQL statement to continue to be
2625 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2626 ** rejected with an error.  ^If the authorizer callback returns
2627 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2628 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2629 ** the authorizer will fail with an error message.
2630 **
2631 ** When the callback returns [SQLITE_OK], that means the operation
2632 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2633 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2634 ** authorizer will fail with an error message explaining that
2635 ** access is denied. 
2636 **
2637 ** ^The first parameter to the authorizer callback is a copy of the third
2638 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2639 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2640 ** the particular action to be authorized. ^The third through sixth parameters
2641 ** to the callback are zero-terminated strings that contain additional
2642 ** details about the action to be authorized.
2643 **
2644 ** ^If the action code is [SQLITE_READ]
2645 ** and the callback returns [SQLITE_IGNORE] then the
2646 ** [prepared statement] statement is constructed to substitute
2647 ** a NULL value in place of the table column that would have
2648 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2649 ** return can be used to deny an untrusted user access to individual
2650 ** columns of a table.
2651 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2652 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2653 ** [truncate optimization] is disabled and all rows are deleted individually.
2654 **
2655 ** An authorizer is used when [sqlite3_prepare | preparing]
2656 ** SQL statements from an untrusted source, to ensure that the SQL statements
2657 ** do not try to access data they are not allowed to see, or that they do not
2658 ** try to execute malicious statements that damage the database.  For
2659 ** example, an application may allow a user to enter arbitrary
2660 ** SQL queries for evaluation by a database.  But the application does
2661 ** not want the user to be able to make arbitrary changes to the
2662 ** database.  An authorizer could then be put in place while the
2663 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2664 ** disallows everything except [SELECT] statements.
2665 **
2666 ** Applications that need to process SQL from untrusted sources
2667 ** might also consider lowering resource limits using [sqlite3_limit()]
2668 ** and limiting database size using the [max_page_count] [PRAGMA]
2669 ** in addition to using an authorizer.
2670 **
2671 ** ^(Only a single authorizer can be in place on a database connection
2672 ** at a time.  Each call to sqlite3_set_authorizer overrides the
2673 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2674 ** The authorizer is disabled by default.
2675 **
2676 ** The authorizer callback must not do anything that will modify
2677 ** the database connection that invoked the authorizer callback.
2678 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2679 ** database connections for the meaning of "modify" in this paragraph.
2680 **
2681 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2682 ** statement might be re-prepared during [sqlite3_step()] due to a 
2683 ** schema change.  Hence, the application should ensure that the
2684 ** correct authorizer callback remains in place during the [sqlite3_step()].
2685 **
2686 ** ^Note that the authorizer callback is invoked only during
2687 ** [sqlite3_prepare()] or its variants.  Authorization is not
2688 ** performed during statement evaluation in [sqlite3_step()], unless
2689 ** as stated in the previous paragraph, sqlite3_step() invokes
2690 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2691 */
2692 SQLITE_API int sqlite3_set_authorizer(
2693   sqlite3*,
2694   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2695   void *pUserData
2696 );
2697
2698 /*
2699 ** CAPI3REF: Authorizer Return Codes
2700 **
2701 ** The [sqlite3_set_authorizer | authorizer callback function] must
2702 ** return either [SQLITE_OK] or one of these two constants in order
2703 ** to signal SQLite whether or not the action is permitted.  See the
2704 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2705 ** information.
2706 */
2707 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2708 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2709
2710 /*
2711 ** CAPI3REF: Authorizer Action Codes
2712 **
2713 ** The [sqlite3_set_authorizer()] interface registers a callback function
2714 ** that is invoked to authorize certain SQL statement actions.  The
2715 ** second parameter to the callback is an integer code that specifies
2716 ** what action is being authorized.  These are the integer action codes that
2717 ** the authorizer callback may be passed.
2718 **
2719 ** These action code values signify what kind of operation is to be
2720 ** authorized.  The 3rd and 4th parameters to the authorization
2721 ** callback function will be parameters or NULL depending on which of these
2722 ** codes is used as the second parameter.  ^(The 5th parameter to the
2723 ** authorizer callback is the name of the database ("main", "temp",
2724 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2725 ** is the name of the inner-most trigger or view that is responsible for
2726 ** the access attempt or NULL if this access attempt is directly from
2727 ** top-level SQL code.
2728 */
2729 /******************************************* 3rd ************ 4th ***********/
2730 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2731 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2732 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2733 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2734 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2735 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2736 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2737 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2738 #define SQLITE_DELETE                9   /* Table Name      NULL            */
2739 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2740 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2741 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2742 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2743 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2744 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2745 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2746 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2747 #define SQLITE_INSERT               18   /* Table Name      NULL            */
2748 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2749 #define SQLITE_READ                 20   /* Table Name      Column Name     */
2750 #define SQLITE_SELECT               21   /* NULL            NULL            */
2751 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
2752 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2753 #define SQLITE_ATTACH               24   /* Filename        NULL            */
2754 #define SQLITE_DETACH               25   /* Database Name   NULL            */
2755 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2756 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
2757 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2758 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2759 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2760 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2761 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
2762 #define SQLITE_COPY                  0   /* No longer used */
2763
2764 /*
2765 ** CAPI3REF: Tracing And Profiling Functions
2766 **
2767 ** These routines register callback functions that can be used for
2768 ** tracing and profiling the execution of SQL statements.
2769 **
2770 ** ^The callback function registered by sqlite3_trace() is invoked at
2771 ** various times when an SQL statement is being run by [sqlite3_step()].
2772 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2773 ** SQL statement text as the statement first begins executing.
2774 ** ^(Additional sqlite3_trace() callbacks might occur
2775 ** as each triggered subprogram is entered.  The callbacks for triggers
2776 ** contain a UTF-8 SQL comment that identifies the trigger.)^
2777 **
2778 ** ^The callback function registered by sqlite3_profile() is invoked
2779 ** as each SQL statement finishes.  ^The profile callback contains
2780 ** the original statement text and an estimate of wall-clock time
2781 ** of how long that statement took to run.  ^The profile callback
2782 ** time is in units of nanoseconds, however the current implementation
2783 ** is only capable of millisecond resolution so the six least significant
2784 ** digits in the time are meaningless.  Future versions of SQLite
2785 ** might provide greater resolution on the profiler callback.  The
2786 ** sqlite3_profile() function is considered experimental and is
2787 ** subject to change in future versions of SQLite.
2788 */
2789 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2790 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2791    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2792
2793 /*
2794 ** CAPI3REF: Query Progress Callbacks
2795 **
2796 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
2797 ** function X to be invoked periodically during long running calls to
2798 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
2799 ** database connection D.  An example use for this
2800 ** interface is to keep a GUI updated during a large query.
2801 **
2802 ** ^The parameter P is passed through as the only parameter to the 
2803 ** callback function X.  ^The parameter N is the number of 
2804 ** [virtual machine instructions] that are evaluated between successive
2805 ** invocations of the callback X.
2806 **
2807 ** ^Only a single progress handler may be defined at one time per
2808 ** [database connection]; setting a new progress handler cancels the
2809 ** old one.  ^Setting parameter X to NULL disables the progress handler.
2810 ** ^The progress handler is also disabled by setting N to a value less
2811 ** than 1.
2812 **
2813 ** ^If the progress callback returns non-zero, the operation is
2814 ** interrupted.  This feature can be used to implement a
2815 ** "Cancel" button on a GUI progress dialog box.
2816 **
2817 ** The progress handler callback must not do anything that will modify
2818 ** the database connection that invoked the progress handler.
2819 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2820 ** database connections for the meaning of "modify" in this paragraph.
2821 **
2822 */
2823 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2824
2825 /*
2826 ** CAPI3REF: Opening A New Database Connection
2827 **
2828 ** ^These routines open an SQLite database file whose name is given by the
2829 ** filename argument. ^The filename argument is interpreted as UTF-8 for
2830 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2831 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
2832 ** returned in *ppDb, even if an error occurs.  The only exception is that
2833 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2834 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2835 ** object.)^ ^(If the database is opened (and/or created) successfully, then
2836 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
2837 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2838 ** an English language description of the error following a failure of any
2839 ** of the sqlite3_open() routines.
2840 **
2841 ** ^The default encoding for the database will be UTF-8 if
2842 ** sqlite3_open() or sqlite3_open_v2() is called and
2843 ** UTF-16 in the native byte order if sqlite3_open16() is used.
2844 **
2845 ** Whether or not an error occurs when it is opened, resources
2846 ** associated with the [database connection] handle should be released by
2847 ** passing it to [sqlite3_close()] when it is no longer required.
2848 **
2849 ** The sqlite3_open_v2() interface works like sqlite3_open()
2850 ** except that it accepts two additional parameters for additional control
2851 ** over the new database connection.  ^(The flags parameter to
2852 ** sqlite3_open_v2() can take one of
2853 ** the following three values, optionally combined with the 
2854 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
2855 ** and/or [SQLITE_OPEN_PRIVATECACHE] flags:)^
2856 **
2857 ** <dl>
2858 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
2859 ** <dd>The database is opened in read-only mode.  If the database does not
2860 ** already exist, an error is returned.</dd>)^
2861 **
2862 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
2863 ** <dd>The database is opened for reading and writing if possible, or reading
2864 ** only if the file is write protected by the operating system.  In either
2865 ** case the database must already exist, otherwise an error is returned.</dd>)^
2866 **
2867 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2868 ** <dd>The database is opened for reading and writing, and is created if
2869 ** it does not already exist. This is the behavior that is always used for
2870 ** sqlite3_open() and sqlite3_open16().</dd>)^
2871 ** </dl>
2872 **
2873 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
2874 ** combinations shown above or one of the combinations shown above combined
2875 ** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
2876 ** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_PRIVATECACHE] flags,
2877 ** then the behavior is undefined.
2878 **
2879 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2880 ** opens in the multi-thread [threading mode] as long as the single-thread
2881 ** mode has not been set at compile-time or start-time.  ^If the
2882 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
2883 ** in the serialized [threading mode] unless single-thread was
2884 ** previously selected at compile-time or start-time.
2885 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
2886 ** eligible to use [shared cache mode], regardless of whether or not shared
2887 ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
2888 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
2889 ** participate in [shared cache mode] even if it is enabled.
2890 **
2891 ** ^If the filename is ":memory:", then a private, temporary in-memory database
2892 ** is created for the connection.  ^This in-memory database will vanish when
2893 ** the database connection is closed.  Future versions of SQLite might
2894 ** make use of additional special filenames that begin with the ":" character.
2895 ** It is recommended that when a database filename actually does begin with
2896 ** a ":" character you should prefix the filename with a pathname such as
2897 ** "./" to avoid ambiguity.
2898 **
2899 ** ^If the filename is an empty string, then a private, temporary
2900 ** on-disk database will be created.  ^This private database will be
2901 ** automatically deleted as soon as the database connection is closed.
2902 **
2903 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
2904 ** [sqlite3_vfs] object that defines the operating system interface that
2905 ** the new database connection should use.  ^If the fourth parameter is
2906 ** a NULL pointer then the default [sqlite3_vfs] object is used.
2907 **
2908 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
2909 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
2910 ** codepage is currently defined.  Filenames containing international
2911 ** characters must be converted to UTF-8 prior to passing them into
2912 ** sqlite3_open() or sqlite3_open_v2().
2913 */
2914 SQLITE_API int sqlite3_open(
2915   const char *filename,   /* Database filename (UTF-8) */
2916   sqlite3 **ppDb          /* OUT: SQLite db handle */
2917 );
2918 SQLITE_API int sqlite3_open16(
2919   const void *filename,   /* Database filename (UTF-16) */
2920   sqlite3 **ppDb          /* OUT: SQLite db handle */
2921 );
2922 SQLITE_API int sqlite3_open_v2(
2923   const char *filename,   /* Database filename (UTF-8) */
2924   sqlite3 **ppDb,         /* OUT: SQLite db handle */
2925   int flags,              /* Flags */
2926   const char *zVfs        /* Name of VFS module to use */
2927 );
2928
2929 /*
2930 ** CAPI3REF: Error Codes And Messages
2931 **
2932 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
2933 ** [extended result code] for the most recent failed sqlite3_* API call
2934 ** associated with a [database connection]. If a prior API call failed
2935 ** but the most recent API call succeeded, the return value from
2936 ** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
2937 ** interface is the same except that it always returns the 
2938 ** [extended result code] even when extended result codes are
2939 ** disabled.
2940 **
2941 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
2942 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
2943 ** ^(Memory to hold the error message string is managed internally.
2944 ** The application does not need to worry about freeing the result.
2945 ** However, the error string might be overwritten or deallocated by
2946 ** subsequent calls to other SQLite interface functions.)^
2947 **
2948 ** When the serialized [threading mode] is in use, it might be the
2949 ** case that a second error occurs on a separate thread in between
2950 ** the time of the first error and the call to these interfaces.
2951 ** When that happens, the second error will be reported since these
2952 ** interfaces always report the most recent result.  To avoid
2953 ** this, each thread can obtain exclusive use of the [database connection] D
2954 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
2955 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
2956 ** all calls to the interfaces listed here are completed.
2957 **
2958 ** If an interface fails with SQLITE_MISUSE, that means the interface
2959 ** was invoked incorrectly by the application.  In that case, the
2960 ** error code and message may or may not be set.
2961 */
2962 SQLITE_API int sqlite3_errcode(sqlite3 *db);
2963 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
2964 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
2965 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
2966
2967 /*
2968 ** CAPI3REF: SQL Statement Object
2969 ** KEYWORDS: {prepared statement} {prepared statements}
2970 **
2971 ** An instance of this object represents a single SQL statement.
2972 ** This object is variously known as a "prepared statement" or a
2973 ** "compiled SQL statement" or simply as a "statement".
2974 **
2975 ** The life of a statement object goes something like this:
2976 **
2977 ** <ol>
2978 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
2979 **      function.
2980 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
2981 **      interfaces.
2982 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
2983 ** <li> Reset the statement using [sqlite3_reset()] then go back
2984 **      to step 2.  Do this zero or more times.
2985 ** <li> Destroy the object using [sqlite3_finalize()].
2986 ** </ol>
2987 **
2988 ** Refer to documentation on individual methods above for additional
2989 ** information.
2990 */
2991 typedef struct sqlite3_stmt sqlite3_stmt;
2992
2993 /*
2994 ** CAPI3REF: Run-time Limits
2995 **
2996 ** ^(This interface allows the size of various constructs to be limited
2997 ** on a connection by connection basis.  The first parameter is the
2998 ** [database connection] whose limit is to be set or queried.  The
2999 ** second parameter is one of the [limit categories] that define a
3000 ** class of constructs to be size limited.  The third parameter is the
3001 ** new limit for that construct.)^
3002 **
3003 ** ^If the new limit is a negative number, the limit is unchanged.
3004 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a 
3005 ** [limits | hard upper bound]
3006 ** set at compile-time by a C preprocessor macro called
3007 ** [limits | SQLITE_MAX_<i>NAME</i>].
3008 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3009 ** ^Attempts to increase a limit above its hard upper bound are
3010 ** silently truncated to the hard upper bound.
3011 **
3012 ** ^Regardless of whether or not the limit was changed, the 
3013 ** [sqlite3_limit()] interface returns the prior value of the limit.
3014 ** ^Hence, to find the current value of a limit without changing it,
3015 ** simply invoke this interface with the third parameter set to -1.
3016 **
3017 ** Run-time limits are intended for use in applications that manage
3018 ** both their own internal database and also databases that are controlled
3019 ** by untrusted external sources.  An example application might be a
3020 ** web browser that has its own databases for storing history and
3021 ** separate databases controlled by JavaScript applications downloaded
3022 ** off the Internet.  The internal databases can be given the
3023 ** large, default limits.  Databases managed by external sources can
3024 ** be given much smaller limits designed to prevent a denial of service
3025 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3026 ** interface to further control untrusted SQL.  The size of the database
3027 ** created by an untrusted script can be contained using the
3028 ** [max_page_count] [PRAGMA].
3029 **
3030 ** New run-time limit categories may be added in future releases.
3031 */
3032 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3033
3034 /*
3035 ** CAPI3REF: Run-Time Limit Categories
3036 ** KEYWORDS: {limit category} {*limit categories}
3037 **
3038 ** These constants define various performance limits
3039 ** that can be lowered at run-time using [sqlite3_limit()].
3040 ** The synopsis of the meanings of the various limits is shown below.
3041 ** Additional information is available at [limits | Limits in SQLite].
3042 **
3043 ** <dl>
3044 ** ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3045 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3046 **
3047 ** ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3048 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3049 **
3050 ** ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3051 ** <dd>The maximum number of columns in a table definition or in the
3052 ** result set of a [SELECT] or the maximum number of columns in an index
3053 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3054 **
3055 ** ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3056 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3057 **
3058 ** ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3059 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3060 **
3061 ** ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3062 ** <dd>The maximum number of instructions in a virtual machine program
3063 ** used to implement an SQL statement.  This limit is not currently
3064 ** enforced, though that might be added in some future release of
3065 ** SQLite.</dd>)^
3066 **
3067 ** ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3068 ** <dd>The maximum number of arguments on a function.</dd>)^
3069 **
3070 ** ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3071 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3072 **
3073 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3074 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3075 ** [GLOB] operators.</dd>)^
3076 **
3077 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3078 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3079 **
3080 ** ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3081 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3082 ** </dl>
3083 */
3084 #define SQLITE_LIMIT_LENGTH                    0
3085 #define SQLITE_LIMIT_SQL_LENGTH                1
3086 #define SQLITE_LIMIT_COLUMN                    2
3087 #define SQLITE_LIMIT_EXPR_DEPTH                3
3088 #define SQLITE_LIMIT_COMPOUND_SELECT           4
3089 #define SQLITE_LIMIT_VDBE_OP                   5
3090 #define SQLITE_LIMIT_FUNCTION_ARG              6
3091 #define SQLITE_LIMIT_ATTACHED                  7
3092 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3093 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
3094 #define SQLITE_LIMIT_TRIGGER_DEPTH            10
3095
3096 /*
3097 ** CAPI3REF: Compiling An SQL Statement
3098 ** KEYWORDS: {SQL statement compiler}
3099 **
3100 ** To execute an SQL query, it must first be compiled into a byte-code
3101 ** program using one of these routines.
3102 **
3103 ** The first argument, "db", is a [database connection] obtained from a
3104 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3105 ** [sqlite3_open16()].  The database connection must not have been closed.
3106 **
3107 ** The second argument, "zSql", is the statement to be compiled, encoded
3108 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3109 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3110 ** use UTF-16.
3111 **
3112 ** ^If the nByte argument is less than zero, then zSql is read up to the
3113 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
3114 ** number of  bytes read from zSql.  ^When nByte is non-negative, the
3115 ** zSql string ends at either the first '\000' or '\u0000' character or
3116 ** the nByte-th byte, whichever comes first. If the caller knows
3117 ** that the supplied string is nul-terminated, then there is a small
3118 ** performance advantage to be gained by passing an nByte parameter that
3119 ** is equal to the number of bytes in the input string <i>including</i>
3120 ** the nul-terminator bytes.
3121 **
3122 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3123 ** past the end of the first SQL statement in zSql.  These routines only
3124 ** compile the first statement in zSql, so *pzTail is left pointing to
3125 ** what remains uncompiled.
3126 **
3127 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3128 ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3129 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
3130 ** string or a comment) then *ppStmt is set to NULL.
3131 ** The calling procedure is responsible for deleting the compiled
3132 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3133 ** ppStmt may not be NULL.
3134 **
3135 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3136 ** otherwise an [error code] is returned.
3137 **
3138 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3139 ** recommended for all new programs. The two older interfaces are retained
3140 ** for backwards compatibility, but their use is discouraged.
3141 ** ^In the "v2" interfaces, the prepared statement
3142 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3143 ** original SQL text. This causes the [sqlite3_step()] interface to
3144 ** behave differently in three ways:
3145 **
3146 ** <ol>
3147 ** <li>
3148 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3149 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3150 ** statement and try to run it again.
3151 ** </li>
3152 **
3153 ** <li>
3154 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3155 ** [error codes] or [extended error codes].  ^The legacy behavior was that
3156 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3157 ** and the application would have to make a second call to [sqlite3_reset()]
3158 ** in order to find the underlying cause of the problem. With the "v2" prepare
3159 ** interfaces, the underlying reason for the error is returned immediately.
3160 ** </li>
3161 **
3162 ** <li>
3163 ** ^If the specific value bound to [parameter | host parameter] in the 
3164 ** WHERE clause might influence the choice of query plan for a statement,
3165 ** then the statement will be automatically recompiled, as if there had been 
3166 ** a schema change, on the first  [sqlite3_step()] call following any change
3167 ** to the [sqlite3_bind_text | bindings] of that [parameter]. 
3168 ** ^The specific value of WHERE-clause [parameter] might influence the 
3169 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3170 ** or [GLOB] operator or if the parameter is compared to an indexed column
3171 ** and the [SQLITE_ENABLE_STAT2] compile-time option is enabled.
3172 ** the 
3173 ** </li>
3174 ** </ol>
3175 */
3176 SQLITE_API int sqlite3_prepare(
3177   sqlite3 *db,            /* Database handle */
3178   const char *zSql,       /* SQL statement, UTF-8 encoded */
3179   int nByte,              /* Maximum length of zSql in bytes. */
3180   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3181   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3182 );
3183 SQLITE_API int sqlite3_prepare_v2(
3184   sqlite3 *db,            /* Database handle */
3185   const char *zSql,       /* SQL statement, UTF-8 encoded */
3186   int nByte,              /* Maximum length of zSql in bytes. */
3187   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3188   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3189 );
3190 SQLITE_API int sqlite3_prepare16(
3191   sqlite3 *db,            /* Database handle */
3192   const void *zSql,       /* SQL statement, UTF-16 encoded */
3193   int nByte,              /* Maximum length of zSql in bytes. */
3194   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3195   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3196 );
3197 SQLITE_API int sqlite3_prepare16_v2(
3198   sqlite3 *db,            /* Database handle */
3199   const void *zSql,       /* SQL statement, UTF-16 encoded */
3200   int nByte,              /* Maximum length of zSql in bytes. */
3201   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3202   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3203 );
3204
3205 /*
3206 ** CAPI3REF: Retrieving Statement SQL
3207 **
3208 ** ^This interface can be used to retrieve a saved copy of the original
3209 ** SQL text used to create a [prepared statement] if that statement was
3210 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3211 */
3212 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3213
3214 /*
3215 ** CAPI3REF: Determine If An SQL Statement Writes The Database
3216 **
3217 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if 
3218 ** and only if the [prepared statement] X makes no direct changes to
3219 ** the content of the database file.
3220 **
3221 ** Note that [application-defined SQL functions] or
3222 ** [virtual tables] might change the database indirectly as a side effect.  
3223 ** ^(For example, if an application defines a function "eval()" that 
3224 ** calls [sqlite3_exec()], then the following SQL statement would
3225 ** change the database file through side-effects:
3226 **
3227 ** <blockquote><pre>
3228 **    SELECT eval('DELETE FROM t1') FROM t2;
3229 ** </pre></blockquote>
3230 **
3231 ** But because the [SELECT] statement does not change the database file
3232 ** directly, sqlite3_stmt_readonly() would still return true.)^
3233 **
3234 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3235 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3236 ** since the statements themselves do not actually modify the database but
3237 ** rather they control the timing of when other statements modify the 
3238 ** database.  ^The [ATTACH] and [DETACH] statements also cause
3239 ** sqlite3_stmt_readonly() to return true since, while those statements
3240 ** change the configuration of a database connection, they do not make 
3241 ** changes to the content of the database files on disk.
3242 */
3243 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3244
3245 /*
3246 ** CAPI3REF: Dynamically Typed Value Object
3247 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3248 **
3249 ** SQLite uses the sqlite3_value object to represent all values
3250 ** that can be stored in a database table. SQLite uses dynamic typing
3251 ** for the values it stores.  ^Values stored in sqlite3_value objects
3252 ** can be integers, floating point values, strings, BLOBs, or NULL.
3253 **
3254 ** An sqlite3_value object may be either "protected" or "unprotected".
3255 ** Some interfaces require a protected sqlite3_value.  Other interfaces
3256 ** will accept either a protected or an unprotected sqlite3_value.
3257 ** Every interface that accepts sqlite3_value arguments specifies
3258 ** whether or not it requires a protected sqlite3_value.
3259 **
3260 ** The terms "protected" and "unprotected" refer to whether or not
3261 ** a mutex is held.  A internal mutex is held for a protected
3262 ** sqlite3_value object but no mutex is held for an unprotected
3263 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
3264 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3265 ** or if SQLite is run in one of reduced mutex modes 
3266 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3267 ** then there is no distinction between protected and unprotected
3268 ** sqlite3_value objects and they can be used interchangeably.  However,
3269 ** for maximum code portability it is recommended that applications
3270 ** still make the distinction between protected and unprotected
3271 ** sqlite3_value objects even when not strictly required.
3272 **
3273 ** ^The sqlite3_value objects that are passed as parameters into the
3274 ** implementation of [application-defined SQL functions] are protected.
3275 ** ^The sqlite3_value object returned by
3276 ** [sqlite3_column_value()] is unprotected.
3277 ** Unprotected sqlite3_value objects may only be used with
3278 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3279 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3280 ** interfaces require protected sqlite3_value objects.
3281 */
3282 typedef struct Mem sqlite3_value;
3283
3284 /*
3285 ** CAPI3REF: SQL Function Context Object
3286 **
3287 ** The context in which an SQL function executes is stored in an
3288 ** sqlite3_context object.  ^A pointer to an sqlite3_context object
3289 ** is always first parameter to [application-defined SQL functions].
3290 ** The application-defined SQL function implementation will pass this
3291 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3292 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3293 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3294 ** and/or [sqlite3_set_auxdata()].
3295 */
3296 typedef struct sqlite3_context sqlite3_context;
3297
3298 /*
3299 ** CAPI3REF: Binding Values To Prepared Statements
3300 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3301 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3302 **
3303 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3304 ** literals may be replaced by a [parameter] that matches one of following
3305 ** templates:
3306 **
3307 ** <ul>
3308 ** <li>  ?
3309 ** <li>  ?NNN
3310 ** <li>  :VVV
3311 ** <li>  @VVV
3312 ** <li>  $VVV
3313 ** </ul>
3314 **
3315 ** In the templates above, NNN represents an integer literal,
3316 ** and VVV represents an alphanumeric identifier.)^  ^The values of these
3317 ** parameters (also called "host parameter names" or "SQL parameters")
3318 ** can be set using the sqlite3_bind_*() routines defined here.
3319 **
3320 ** ^The first argument to the sqlite3_bind_*() routines is always
3321 ** a pointer to the [sqlite3_stmt] object returned from
3322 ** [sqlite3_prepare_v2()] or its variants.
3323 **
3324 ** ^The second argument is the index of the SQL parameter to be set.
3325 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3326 ** SQL parameter is used more than once, second and subsequent
3327 ** occurrences have the same index as the first occurrence.
3328 ** ^The index for named parameters can be looked up using the
3329 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3330 ** for "?NNN" parameters is the value of NNN.
3331 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3332 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3333 **
3334 ** ^The third argument is the value to bind to the parameter.
3335 **
3336 ** ^(In those routines that have a fourth argument, its value is the
3337 ** number of bytes in the parameter.  To be clear: the value is the
3338 ** number of <u>bytes</u> in the value, not the number of characters.)^
3339 ** ^If the fourth parameter is negative, the length of the string is
3340 ** the number of bytes up to the first zero terminator.
3341 **
3342 ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3343 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3344 ** string after SQLite has finished with it.  ^The destructor is called
3345 ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
3346 ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.  
3347 ** ^If the fifth argument is
3348 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3349 ** information is in static, unmanaged space and does not need to be freed.
3350 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3351 ** SQLite makes its own private copy of the data immediately, before
3352 ** the sqlite3_bind_*() routine returns.
3353 **
3354 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3355 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3356 ** (just an integer to hold its size) while it is being processed.
3357 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3358 ** content is later written using
3359 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3360 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3361 **
3362 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3363 ** for the [prepared statement] or with a prepared statement for which
3364 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3365 ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3366 ** routine is passed a [prepared statement] that has been finalized, the
3367 ** result is undefined and probably harmful.
3368 **
3369 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3370 ** ^Unbound parameters are interpreted as NULL.
3371 **
3372 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3373 ** [error code] if anything goes wrong.
3374 ** ^[SQLITE_RANGE] is returned if the parameter
3375 ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3376 **
3377 ** See also: [sqlite3_bind_parameter_count()],
3378 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3379 */
3380 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3381 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3382 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3383 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3384 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3385 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3386 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3387 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3388 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3389
3390 /*
3391 ** CAPI3REF: Number Of SQL Parameters
3392 **
3393 ** ^This routine can be used to find the number of [SQL parameters]
3394 ** in a [prepared statement].  SQL parameters are tokens of the
3395 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3396 ** placeholders for values that are [sqlite3_bind_blob | bound]
3397 ** to the parameters at a later time.
3398 **
3399 ** ^(This routine actually returns the index of the largest (rightmost)
3400 ** parameter. For all forms except ?NNN, this will correspond to the
3401 ** number of unique parameters.  If parameters of the ?NNN form are used,
3402 ** there may be gaps in the list.)^
3403 **
3404 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3405 ** [sqlite3_bind_parameter_name()], and
3406 ** [sqlite3_bind_parameter_index()].
3407 */
3408 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3409
3410 /*
3411 ** CAPI3REF: Name Of A Host Parameter
3412 **
3413 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
3414 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3415 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3416 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3417 ** respectively.
3418 ** In other words, the initial ":" or "$" or "@" or "?"
3419 ** is included as part of the name.)^
3420 ** ^Parameters of the form "?" without a following integer have no name
3421 ** and are referred to as "nameless" or "anonymous parameters".
3422 **
3423 ** ^The first host parameter has an index of 1, not 0.
3424 **
3425 ** ^If the value N is out of range or if the N-th parameter is
3426 ** nameless, then NULL is returned.  ^The returned string is
3427 ** always in UTF-8 encoding even if the named parameter was
3428 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3429 ** [sqlite3_prepare16_v2()].
3430 **
3431 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3432 ** [sqlite3_bind_parameter_count()], and
3433 ** [sqlite3_bind_parameter_index()].
3434 */
3435 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3436
3437 /*
3438 ** CAPI3REF: Index Of A Parameter With A Given Name
3439 **
3440 ** ^Return the index of an SQL parameter given its name.  ^The
3441 ** index value returned is suitable for use as the second
3442 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3443 ** is returned if no matching parameter is found.  ^The parameter
3444 ** name must be given in UTF-8 even if the original statement
3445 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3446 **
3447 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3448 ** [sqlite3_bind_parameter_count()], and
3449 ** [sqlite3_bind_parameter_index()].
3450 */
3451 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3452
3453 /*
3454 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3455 **
3456 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3457 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3458 ** ^Use this routine to reset all host parameters to NULL.
3459 */
3460 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3461
3462 /*
3463 ** CAPI3REF: Number Of Columns In A Result Set
3464 **
3465 ** ^Return the number of columns in the result set returned by the
3466 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3467 ** statement that does not return data (for example an [UPDATE]).
3468 **
3469 ** See also: [sqlite3_data_count()]
3470 */
3471 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3472
3473 /*
3474 ** CAPI3REF: Column Names In A Result Set
3475 **
3476 ** ^These routines return the name assigned to a particular column
3477 ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3478 ** interface returns a pointer to a zero-terminated UTF-8 string
3479 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3480 ** UTF-16 string.  ^The first parameter is the [prepared statement]
3481 ** that implements the [SELECT] statement. ^The second parameter is the
3482 ** column number.  ^The leftmost column is number 0.
3483 **
3484 ** ^The returned string pointer is valid until either the [prepared statement]
3485 ** is destroyed by [sqlite3_finalize()] or until the next call to
3486 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3487 **
3488 ** ^If sqlite3_malloc() fails during the processing of either routine
3489 ** (for example during a conversion from UTF-8 to UTF-16) then a
3490 ** NULL pointer is returned.
3491 **
3492 ** ^The name of a result column is the value of the "AS" clause for
3493 ** that column, if there is an AS clause.  If there is no AS clause
3494 ** then the name of the column is unspecified and may change from
3495 ** one release of SQLite to the next.
3496 */
3497 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3498 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3499
3500 /*
3501 ** CAPI3REF: Source Of Data In A Query Result
3502 **
3503 ** ^These routines provide a means to determine the database, table, and
3504 ** table column that is the origin of a particular result column in
3505 ** [SELECT] statement.
3506 ** ^The name of the database or table or column can be returned as
3507 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3508 ** the database name, the _table_ routines return the table name, and
3509 ** the origin_ routines return the column name.
3510 ** ^The returned string is valid until the [prepared statement] is destroyed
3511 ** using [sqlite3_finalize()] or until the same information is requested
3512 ** again in a different encoding.
3513 **
3514 ** ^The names returned are the original un-aliased names of the
3515 ** database, table, and column.
3516 **
3517 ** ^The first argument to these interfaces is a [prepared statement].
3518 ** ^These functions return information about the Nth result column returned by
3519 ** the statement, where N is the second function argument.
3520 ** ^The left-most column is column 0 for these routines.
3521 **
3522 ** ^If the Nth column returned by the statement is an expression or
3523 ** subquery and is not a column value, then all of these functions return
3524 ** NULL.  ^These routine might also return NULL if a memory allocation error
3525 ** occurs.  ^Otherwise, they return the name of the attached database, table,
3526 ** or column that query result column was extracted from.
3527 **
3528 ** ^As with all other SQLite APIs, those whose names end with "16" return
3529 ** UTF-16 encoded strings and the other functions return UTF-8.
3530 **
3531 ** ^These APIs are only available if the library was compiled with the
3532 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3533 **
3534 ** If two or more threads call one or more of these routines against the same
3535 ** prepared statement and column at the same time then the results are
3536 ** undefined.
3537 **
3538 ** If two or more threads call one or more
3539 ** [sqlite3_column_database_name | column metadata interfaces]
3540 ** for the same [prepared statement] and result column
3541 ** at the same time then the results are undefined.
3542 */
3543 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3544 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3545 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3546 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3547 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3548 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3549
3550 /*
3551 ** CAPI3REF: Declared Datatype Of A Query Result
3552 **
3553 ** ^(The first parameter is a [prepared statement].
3554 ** If this statement is a [SELECT] statement and the Nth column of the
3555 ** returned result set of that [SELECT] is a table column (not an
3556 ** expression or subquery) then the declared type of the table
3557 ** column is returned.)^  ^If the Nth column of the result set is an
3558 ** expression or subquery, then a NULL pointer is returned.
3559 ** ^The returned string is always UTF-8 encoded.
3560 **
3561 ** ^(For example, given the database schema:
3562 **
3563 ** CREATE TABLE t1(c1 VARIANT);
3564 **
3565 ** and the following statement to be compiled:
3566 **
3567 ** SELECT c1 + 1, c1 FROM t1;
3568 **
3569 ** this routine would return the string "VARIANT" for the second result
3570 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
3571 **
3572 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
3573 ** is declared to contain a particular type does not mean that the
3574 ** data stored in that column is of the declared type.  SQLite is
3575 ** strongly typed, but the typing is dynamic not static.  ^Type
3576 ** is associated with individual values, not with the containers
3577 ** used to hold those values.
3578 */
3579 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3580 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3581
3582 /*
3583 ** CAPI3REF: Evaluate An SQL Statement
3584 **
3585 ** After a [prepared statement] has been prepared using either
3586 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3587 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3588 ** must be called one or more times to evaluate the statement.
3589 **
3590 ** The details of the behavior of the sqlite3_step() interface depend
3591 ** on whether the statement was prepared using the newer "v2" interface
3592 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3593 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3594 ** new "v2" interface is recommended for new applications but the legacy
3595 ** interface will continue to be supported.
3596 **
3597 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3598 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3599 ** ^With the "v2" interface, any of the other [result codes] or
3600 ** [extended result codes] might be returned as well.
3601 **
3602 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3603 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
3604 ** or occurs outside of an explicit transaction, then you can retry the
3605 ** statement.  If the statement is not a [COMMIT] and occurs within a
3606 ** explicit transaction then you should rollback the transaction before
3607 ** continuing.
3608 **
3609 ** ^[SQLITE_DONE] means that the statement has finished executing
3610 ** successfully.  sqlite3_step() should not be called again on this virtual
3611 ** machine without first calling [sqlite3_reset()] to reset the virtual
3612 ** machine back to its initial state.
3613 **
3614 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3615 ** is returned each time a new row of data is ready for processing by the
3616 ** caller. The values may be accessed using the [column access functions].
3617 ** sqlite3_step() is called again to retrieve the next row of data.
3618 **
3619 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
3620 ** violation) has occurred.  sqlite3_step() should not be called again on
3621 ** the VM. More information may be found by calling [sqlite3_errmsg()].
3622 ** ^With the legacy interface, a more specific error code (for example,
3623 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3624 ** can be obtained by calling [sqlite3_reset()] on the
3625 ** [prepared statement].  ^In the "v2" interface,
3626 ** the more specific error code is returned directly by sqlite3_step().
3627 **
3628 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3629 ** Perhaps it was called on a [prepared statement] that has
3630 ** already been [sqlite3_finalize | finalized] or on one that had
3631 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
3632 ** be the case that the same database connection is being used by two or
3633 ** more threads at the same moment in time.
3634 **
3635 ** For all versions of SQLite up to and including 3.6.23.1, a call to
3636 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
3637 ** other than [SQLITE_ROW] before any subsequent invocation of
3638 ** sqlite3_step().  Failure to reset the prepared statement using 
3639 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
3640 ** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began
3641 ** calling [sqlite3_reset()] automatically in this circumstance rather
3642 ** than returning [SQLITE_MISUSE].  This is not considered a compatibility
3643 ** break because any application that ever receives an SQLITE_MISUSE error
3644 ** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
3645 ** can be used to restore the legacy behavior.
3646 **
3647 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3648 ** API always returns a generic error code, [SQLITE_ERROR], following any
3649 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
3650 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
3651 ** specific [error codes] that better describes the error.
3652 ** We admit that this is a goofy design.  The problem has been fixed
3653 ** with the "v2" interface.  If you prepare all of your SQL statements
3654 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
3655 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
3656 ** then the more specific [error codes] are returned directly
3657 ** by sqlite3_step().  The use of the "v2" interface is recommended.
3658 */
3659 SQLITE_API int sqlite3_step(sqlite3_stmt*);
3660
3661 /*
3662 ** CAPI3REF: Number of columns in a result set
3663 **
3664 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
3665 ** current row of the result set of [prepared statement] P.
3666 ** ^If prepared statement P does not have results ready to return
3667 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
3668 ** interfaces) then sqlite3_data_count(P) returns 0.
3669 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
3670 **
3671 ** See also: [sqlite3_column_count()]
3672 */
3673 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3674
3675 /*
3676 ** CAPI3REF: Fundamental Datatypes
3677 ** KEYWORDS: SQLITE_TEXT
3678 **
3679 ** ^(Every value in SQLite has one of five fundamental datatypes:
3680 **
3681 ** <ul>
3682 ** <li> 64-bit signed integer
3683 ** <li> 64-bit IEEE floating point number
3684 ** <li> string
3685 ** <li> BLOB
3686 ** <li> NULL
3687 ** </ul>)^
3688 **
3689 ** These constants are codes for each of those types.
3690 **
3691 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
3692 ** for a completely different meaning.  Software that links against both
3693 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
3694 ** SQLITE_TEXT.
3695 */
3696 #define SQLITE_INTEGER  1
3697 #define SQLITE_FLOAT    2
3698 #define SQLITE_BLOB     4
3699 #define SQLITE_NULL     5
3700 #ifdef SQLITE_TEXT
3701 # undef SQLITE_TEXT
3702 #else
3703 # define SQLITE_TEXT     3
3704 #endif
3705 #define SQLITE3_TEXT     3
3706
3707 /*
3708 ** CAPI3REF: Result Values From A Query
3709 ** KEYWORDS: {column access functions}
3710 **
3711 ** These routines form the "result set" interface.
3712 **
3713 ** ^These routines return information about a single column of the current
3714 ** result row of a query.  ^In every case the first argument is a pointer
3715 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
3716 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
3717 ** and the second argument is the index of the column for which information
3718 ** should be returned. ^The leftmost column of the result set has the index 0.
3719 ** ^The number of columns in the result can be determined using
3720 ** [sqlite3_column_count()].
3721 **
3722 ** If the SQL statement does not currently point to a valid row, or if the
3723 ** column index is out of range, the result is undefined.
3724 ** These routines may only be called when the most recent call to
3725 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
3726 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
3727 ** If any of these routines are called after [sqlite3_reset()] or
3728 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
3729 ** something other than [SQLITE_ROW], the results are undefined.
3730 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
3731 ** are called from a different thread while any of these routines
3732 ** are pending, then the results are undefined.
3733 **
3734 ** ^The sqlite3_column_type() routine returns the
3735 ** [SQLITE_INTEGER | datatype code] for the initial data type
3736 ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
3737 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
3738 ** returned by sqlite3_column_type() is only meaningful if no type
3739 ** conversions have occurred as described below.  After a type conversion,
3740 ** the value returned by sqlite3_column_type() is undefined.  Future
3741 ** versions of SQLite may change the behavior of sqlite3_column_type()
3742 ** following a type conversion.
3743 **
3744 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
3745 ** routine returns the number of bytes in that BLOB or string.
3746 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3747 ** the string to UTF-8 and then returns the number of bytes.
3748 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
3749 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3750 ** the number of bytes in that string.
3751 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
3752 **
3753 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
3754 ** routine returns the number of bytes in that BLOB or string.
3755 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
3756 ** the string to UTF-16 and then returns the number of bytes.
3757 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
3758 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
3759 ** the number of bytes in that string.
3760 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
3761 **
3762 ** ^The values returned by [sqlite3_column_bytes()] and 
3763 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
3764 ** of the string.  ^For clarity: the values returned by
3765 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
3766 ** bytes in the string, not the number of characters.
3767 **
3768 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
3769 ** even empty strings, are always zero terminated.  ^The return
3770 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
3771 **
3772 ** ^The object returned by [sqlite3_column_value()] is an
3773 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
3774 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
3775 ** If the [unprotected sqlite3_value] object returned by
3776 ** [sqlite3_column_value()] is used in any other way, including calls
3777 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
3778 ** or [sqlite3_value_bytes()], then the behavior is undefined.
3779 **
3780 ** These routines attempt to convert the value where appropriate.  ^For
3781 ** example, if the internal representation is FLOAT and a text result
3782 ** is requested, [sqlite3_snprintf()] is used internally to perform the
3783 ** conversion automatically.  ^(The following table details the conversions
3784 ** that are applied:
3785 **
3786 ** <blockquote>
3787 ** <table border="1">
3788 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
3789 **
3790 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
3791 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
3792 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
3793 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
3794 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
3795 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
3796 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
3797 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
3798 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
3799 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
3800 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
3801 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
3802 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
3803 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
3804 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
3805 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
3806 ** </table>
3807 ** </blockquote>)^
3808 **
3809 ** The table above makes reference to standard C library functions atoi()
3810 ** and atof().  SQLite does not really use these functions.  It has its
3811 ** own equivalent internal routines.  The atoi() and atof() names are
3812 ** used in the table for brevity and because they are familiar to most
3813 ** C programmers.
3814 **
3815 ** Note that when type conversions occur, pointers returned by prior
3816 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
3817 ** sqlite3_column_text16() may be invalidated.
3818 ** Type conversions and pointer invalidations might occur
3819 ** in the following cases:
3820 **
3821 ** <ul>
3822 ** <li> The initial content is a BLOB and sqlite3_column_text() or
3823 **      sqlite3_column_text16() is called.  A zero-terminator might
3824 **      need to be added to the string.</li>
3825 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
3826 **      sqlite3_column_text16() is called.  The content must be converted
3827 **      to UTF-16.</li>
3828 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
3829 **      sqlite3_column_text() is called.  The content must be converted
3830 **      to UTF-8.</li>
3831 ** </ul>
3832 **
3833 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
3834 ** not invalidate a prior pointer, though of course the content of the buffer
3835 ** that the prior pointer references will have been modified.  Other kinds
3836 ** of conversion are done in place when it is possible, but sometimes they
3837 ** are not possible and in those cases prior pointers are invalidated.
3838 **
3839 ** The safest and easiest to remember policy is to invoke these routines
3840 ** in one of the following ways:
3841 **
3842 ** <ul>
3843 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
3844 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
3845 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
3846 ** </ul>
3847 **
3848 ** In other words, you should call sqlite3_column_text(),
3849 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
3850 ** into the desired format, then invoke sqlite3_column_bytes() or
3851 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
3852 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
3853 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
3854 ** with calls to sqlite3_column_bytes().
3855 **
3856 ** ^The pointers returned are valid until a type conversion occurs as
3857 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
3858 ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
3859 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
3860 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
3861 ** [sqlite3_free()].
3862 **
3863 ** ^(If a memory allocation error occurs during the evaluation of any
3864 ** of these routines, a default value is returned.  The default value
3865 ** is either the integer 0, the floating point number 0.0, or a NULL
3866 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
3867 ** [SQLITE_NOMEM].)^
3868 */
3869 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
3870 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
3871 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
3872 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
3873 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
3874 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
3875 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
3876 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
3877 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
3878 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
3879
3880 /*
3881 ** CAPI3REF: Destroy A Prepared Statement Object
3882 **
3883 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
3884 ** ^If the most recent evaluation of the statement encountered no errors or
3885 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
3886 ** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
3887 ** sqlite3_finalize(S) returns the appropriate [error code] or
3888 ** [extended error code].
3889 **
3890 ** ^The sqlite3_finalize(S) routine can be called at any point during
3891 ** the life cycle of [prepared statement] S:
3892 ** before statement S is ever evaluated, after
3893 ** one or more calls to [sqlite3_reset()], or after any call
3894 ** to [sqlite3_step()] regardless of whether or not the statement has
3895 ** completed execution.
3896 **
3897 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
3898 **
3899 ** The application must finalize every [prepared statement] in order to avoid
3900 ** resource leaks.  It is a grievous error for the application to try to use
3901 ** a prepared statement after it has been finalized.  Any use of a prepared
3902 ** statement after it has been finalized can result in undefined and
3903 ** undesirable behavior such as segfaults and heap corruption.
3904 */
3905 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
3906
3907 /*
3908 ** CAPI3REF: Reset A Prepared Statement Object
3909 **
3910 ** The sqlite3_reset() function is called to reset a [prepared statement]
3911 ** object back to its initial state, ready to be re-executed.
3912 ** ^Any SQL statement variables that had values bound to them using
3913 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
3914 ** Use [sqlite3_clear_bindings()] to reset the bindings.
3915 **
3916 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
3917 ** back to the beginning of its program.
3918 **
3919 ** ^If the most recent call to [sqlite3_step(S)] for the
3920 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
3921 ** or if [sqlite3_step(S)] has never before been called on S,
3922 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
3923 **
3924 ** ^If the most recent call to [sqlite3_step(S)] for the
3925 ** [prepared statement] S indicated an error, then
3926 ** [sqlite3_reset(S)] returns an appropriate [error code].
3927 **
3928 ** ^The [sqlite3_reset(S)] interface does not change the values
3929 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
3930 */
3931 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
3932
3933 /*
3934 ** CAPI3REF: Create Or Redefine SQL Functions
3935 ** KEYWORDS: {function creation routines}
3936 ** KEYWORDS: {application-defined SQL function}
3937 ** KEYWORDS: {application-defined SQL functions}
3938 **
3939 ** ^These functions (collectively known as "function creation routines")
3940 ** are used to add SQL functions or aggregates or to redefine the behavior
3941 ** of existing SQL functions or aggregates.  The only differences between
3942 ** these routines are the text encoding expected for
3943 ** the the second parameter (the name of the function being created)
3944 ** and the presence or absence of a destructor callback for
3945 ** the application data pointer.
3946 **
3947 ** ^The first parameter is the [database connection] to which the SQL
3948 ** function is to be added.  ^If an application uses more than one database
3949 ** connection then application-defined SQL functions must be added
3950 ** to each database connection separately.
3951 **
3952 ** ^The second parameter is the name of the SQL function to be created or
3953 ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
3954 ** representation, exclusive of the zero-terminator.  ^Note that the name
3955 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.  
3956 ** ^Any attempt to create a function with a longer name
3957 ** will result in [SQLITE_MISUSE] being returned.
3958 **
3959 ** ^The third parameter (nArg)
3960 ** is the number of arguments that the SQL function or
3961 ** aggregate takes. ^If this parameter is -1, then the SQL function or
3962 ** aggregate may take any number of arguments between 0 and the limit
3963 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
3964 ** parameter is less than -1 or greater than 127 then the behavior is
3965 ** undefined.
3966 **
3967 ** ^The fourth parameter, eTextRep, specifies what
3968 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
3969 ** its parameters.  Every SQL function implementation must be able to work
3970 ** with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
3971 ** more efficient with one encoding than another.  ^An application may
3972 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
3973 ** times with the same function but with different values of eTextRep.
3974 ** ^When multiple implementations of the same function are available, SQLite
3975 ** will pick the one that involves the least amount of data conversion.
3976 ** If there is only a single implementation which does not care what text
3977 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
3978 **
3979 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
3980 ** function can gain access to this pointer using [sqlite3_user_data()].)^
3981 **
3982 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
3983 ** pointers to C-language functions that implement the SQL function or
3984 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
3985 ** callback only; NULL pointers must be passed as the xStep and xFinal
3986 ** parameters. ^An aggregate SQL function requires an implementation of xStep
3987 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
3988 ** SQL function or aggregate, pass NULL poiners for all three function
3989 ** callbacks.
3990 **
3991 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
3992 ** then it is destructor for the application data pointer. 
3993 ** The destructor is invoked when the function is deleted, either by being
3994 ** overloaded or when the database connection closes.)^
3995 ** ^The destructor is also invoked if the call to
3996 ** sqlite3_create_function_v2() fails.
3997 ** ^When the destructor callback of the tenth parameter is invoked, it
3998 ** is passed a single argument which is a copy of the application data 
3999 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
4000 **
4001 ** ^It is permitted to register multiple implementations of the same
4002 ** functions with the same name but with either differing numbers of
4003 ** arguments or differing preferred text encodings.  ^SQLite will use
4004 ** the implementation that most closely matches the way in which the
4005 ** SQL function is used.  ^A function implementation with a non-negative
4006 ** nArg parameter is a better match than a function implementation with
4007 ** a negative nArg.  ^A function where the preferred text encoding
4008 ** matches the database encoding is a better
4009 ** match than a function where the encoding is different.  
4010 ** ^A function where the encoding difference is between UTF16le and UTF16be
4011 ** is a closer match than a function where the encoding difference is
4012 ** between UTF8 and UTF16.
4013 **
4014 ** ^Built-in functions may be overloaded by new application-defined functions.
4015 **
4016 ** ^An application-defined function is permitted to call other
4017 ** SQLite interfaces.  However, such calls must not
4018 ** close the database connection nor finalize or reset the prepared
4019 ** statement in which the function is running.
4020 */
4021 SQLITE_API int sqlite3_create_function(
4022   sqlite3 *db,
4023   const char *zFunctionName,
4024   int nArg,
4025   int eTextRep,
4026   void *pApp,
4027   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4028   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4029   void (*xFinal)(sqlite3_context*)
4030 );
4031 SQLITE_API int sqlite3_create_function16(
4032   sqlite3 *db,
4033   const void *zFunctionName,
4034   int nArg,
4035   int eTextRep,
4036   void *pApp,
4037   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4038   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4039   void (*xFinal)(sqlite3_context*)
4040 );
4041 SQLITE_API int sqlite3_create_function_v2(
4042   sqlite3 *db,
4043   const char *zFunctionName,
4044   int nArg,
4045   int eTextRep,
4046   void *pApp,
4047   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4048   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4049   void (*xFinal)(sqlite3_context*),
4050   void(*xDestroy)(void*)
4051 );
4052
4053 /*
4054 ** CAPI3REF: Text Encodings
4055 **
4056 ** These constant define integer codes that represent the various
4057 ** text encodings supported by SQLite.
4058 */
4059 #define SQLITE_UTF8           1
4060 #define SQLITE_UTF16LE        2
4061 #define SQLITE_UTF16BE        3
4062 #define SQLITE_UTF16          4    /* Use native byte order */
4063 #define SQLITE_ANY            5    /* sqlite3_create_function only */
4064 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4065
4066 /*
4067 ** CAPI3REF: Deprecated Functions
4068 ** DEPRECATED
4069 **
4070 ** These functions are [deprecated].  In order to maintain
4071 ** backwards compatibility with older code, these functions continue 
4072 ** to be supported.  However, new applications should avoid
4073 ** the use of these functions.  To help encourage people to avoid
4074 ** using these functions, we are not going to tell you what they do.
4075 */
4076 #ifndef SQLITE_OMIT_DEPRECATED
4077 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4078 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4079 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4080 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4081 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4082 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
4083 #endif
4084
4085 /*
4086 ** CAPI3REF: Obtaining SQL Function Parameter Values
4087 **
4088 ** The C-language implementation of SQL functions and aggregates uses
4089 ** this set of interface routines to access the parameter values on
4090 ** the function or aggregate.
4091 **
4092 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4093 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4094 ** define callbacks that implement the SQL functions and aggregates.
4095 ** The 3rd parameter to these callbacks is an array of pointers to
4096 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4097 ** each parameter to the SQL function.  These routines are used to
4098 ** extract values from the [sqlite3_value] objects.
4099 **
4100 ** These routines work only with [protected sqlite3_value] objects.
4101 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4102 ** object results in undefined behavior.
4103 **
4104 ** ^These routines work just like the corresponding [column access functions]
4105 ** except that  these routines take a single [protected sqlite3_value] object
4106 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4107 **
4108 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4109 ** in the native byte-order of the host machine.  ^The
4110 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4111 ** extract UTF-16 strings as big-endian and little-endian respectively.
4112 **
4113 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
4114 ** numeric affinity to the value.  This means that an attempt is
4115 ** made to convert the value to an integer or floating point.  If
4116 ** such a conversion is possible without loss of information (in other
4117 ** words, if the value is a string that looks like a number)
4118 ** then the conversion is performed.  Otherwise no conversion occurs.
4119 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4120 **
4121 ** Please pay particular attention to the fact that the pointer returned
4122 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4123 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4124 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4125 ** or [sqlite3_value_text16()].
4126 **
4127 ** These routines must be called from the same thread as
4128 ** the SQL function that supplied the [sqlite3_value*] parameters.
4129 */
4130 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4131 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4132 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4133 SQLITE_API double sqlite3_value_double(sqlite3_value*);
4134 SQLITE_API int sqlite3_value_int(sqlite3_value*);
4135 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4136 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4137 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4138 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4139 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4140 SQLITE_API int sqlite3_value_type(sqlite3_value*);
4141 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4142
4143 /*
4144 ** CAPI3REF: Obtain Aggregate Function Context
4145 **
4146 ** Implementations of aggregate SQL functions use this
4147 ** routine to allocate memory for storing their state.
4148 **
4149 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called 
4150 ** for a particular aggregate function, SQLite
4151 ** allocates N of memory, zeroes out that memory, and returns a pointer
4152 ** to the new memory. ^On second and subsequent calls to
4153 ** sqlite3_aggregate_context() for the same aggregate function instance,
4154 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
4155 ** called once for each invocation of the xStep callback and then one
4156 ** last time when the xFinal callback is invoked.  ^(When no rows match
4157 ** an aggregate query, the xStep() callback of the aggregate function
4158 ** implementation is never called and xFinal() is called exactly once.
4159 ** In those cases, sqlite3_aggregate_context() might be called for the
4160 ** first time from within xFinal().)^
4161 **
4162 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
4163 ** less than or equal to zero or if a memory allocate error occurs.
4164 **
4165 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4166 ** determined by the N parameter on first successful call.  Changing the
4167 ** value of N in subsequent call to sqlite3_aggregate_context() within
4168 ** the same aggregate function instance will not resize the memory
4169 ** allocation.)^
4170 **
4171 ** ^SQLite automatically frees the memory allocated by 
4172 ** sqlite3_aggregate_context() when the aggregate query concludes.
4173 **
4174 ** The first parameter must be a copy of the
4175 ** [sqlite3_context | SQL function context] that is the first parameter
4176 ** to the xStep or xFinal callback routine that implements the aggregate
4177 ** function.
4178 **
4179 ** This routine must be called from the same thread in which
4180 ** the aggregate SQL function is running.
4181 */
4182 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4183
4184 /*
4185 ** CAPI3REF: User Data For Functions
4186 **
4187 ** ^The sqlite3_user_data() interface returns a copy of
4188 ** the pointer that was the pUserData parameter (the 5th parameter)
4189 ** of the [sqlite3_create_function()]
4190 ** and [sqlite3_create_function16()] routines that originally
4191 ** registered the application defined function.
4192 **
4193 ** This routine must be called from the same thread in which
4194 ** the application-defined function is running.
4195 */
4196 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4197
4198 /*
4199 ** CAPI3REF: Database Connection For Functions
4200 **
4201 ** ^The sqlite3_context_db_handle() interface returns a copy of
4202 ** the pointer to the [database connection] (the 1st parameter)
4203 ** of the [sqlite3_create_function()]
4204 ** and [sqlite3_create_function16()] routines that originally
4205 ** registered the application defined function.
4206 */
4207 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4208
4209 /*
4210 ** CAPI3REF: Function Auxiliary Data
4211 **
4212 ** The following two functions may be used by scalar SQL functions to
4213 ** associate metadata with argument values. If the same value is passed to
4214 ** multiple invocations of the same SQL function during query execution, under
4215 ** some circumstances the associated metadata may be preserved. This may
4216 ** be used, for example, to add a regular-expression matching scalar
4217 ** function. The compiled version of the regular expression is stored as
4218 ** metadata associated with the SQL value passed as the regular expression
4219 ** pattern.  The compiled regular expression can be reused on multiple
4220 ** invocations of the same function so that the original pattern string
4221 ** does not need to be recompiled on each invocation.
4222 **
4223 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4224 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4225 ** value to the application-defined function. ^If no metadata has been ever
4226 ** been set for the Nth argument of the function, or if the corresponding
4227 ** function parameter has changed since the meta-data was set,
4228 ** then sqlite3_get_auxdata() returns a NULL pointer.
4229 **
4230 ** ^The sqlite3_set_auxdata() interface saves the metadata
4231 ** pointed to by its 3rd parameter as the metadata for the N-th
4232 ** argument of the application-defined function.  Subsequent
4233 ** calls to sqlite3_get_auxdata() might return this data, if it has
4234 ** not been destroyed.
4235 ** ^If it is not NULL, SQLite will invoke the destructor
4236 ** function given by the 4th parameter to sqlite3_set_auxdata() on
4237 ** the metadata when the corresponding function parameter changes
4238 ** or when the SQL statement completes, whichever comes first.
4239 **
4240 ** SQLite is free to call the destructor and drop metadata on any
4241 ** parameter of any function at any time.  ^The only guarantee is that
4242 ** the destructor will be called before the metadata is dropped.
4243 **
4244 ** ^(In practice, metadata is preserved between function calls for
4245 ** expressions that are constant at compile time. This includes literal
4246 ** values and [parameters].)^
4247 **
4248 ** These routines must be called from the same thread in which
4249 ** the SQL function is running.
4250 */
4251 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4252 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4253
4254
4255 /*
4256 ** CAPI3REF: Constants Defining Special Destructor Behavior
4257 **
4258 ** These are special values for the destructor that is passed in as the
4259 ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
4260 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4261 ** and will never change.  It does not need to be destroyed.  ^The
4262 ** SQLITE_TRANSIENT value means that the content will likely change in
4263 ** the near future and that SQLite should make its own private copy of
4264 ** the content before returning.
4265 **
4266 ** The typedef is necessary to work around problems in certain
4267 ** C++ compilers.  See ticket #2191.
4268 */
4269 typedef void (*sqlite3_destructor_type)(void*);
4270 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4271 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4272
4273 /*
4274 ** CAPI3REF: Setting The Result Of An SQL Function
4275 **
4276 ** These routines are used by the xFunc or xFinal callbacks that
4277 ** implement SQL functions and aggregates.  See
4278 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4279 ** for additional information.
4280 **
4281 ** These functions work very much like the [parameter binding] family of
4282 ** functions used to bind values to host parameters in prepared statements.
4283 ** Refer to the [SQL parameter] documentation for additional information.
4284 **
4285 ** ^The sqlite3_result_blob() interface sets the result from
4286 ** an application-defined function to be the BLOB whose content is pointed
4287 ** to by the second parameter and which is N bytes long where N is the
4288 ** third parameter.
4289 **
4290 ** ^The sqlite3_result_zeroblob() interfaces set the result of
4291 ** the application-defined function to be a BLOB containing all zero
4292 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4293 **
4294 ** ^The sqlite3_result_double() interface sets the result from
4295 ** an application-defined function to be a floating point value specified
4296 ** by its 2nd argument.
4297 **
4298 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4299 ** cause the implemented SQL function to throw an exception.
4300 ** ^SQLite uses the string pointed to by the
4301 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4302 ** as the text of an error message.  ^SQLite interprets the error
4303 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
4304 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4305 ** byte order.  ^If the third parameter to sqlite3_result_error()
4306 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4307 ** message all text up through the first zero character.
4308 ** ^If the third parameter to sqlite3_result_error() or
4309 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4310 ** bytes (not characters) from the 2nd parameter as the error message.
4311 ** ^The sqlite3_result_error() and sqlite3_result_error16()
4312 ** routines make a private copy of the error message text before
4313 ** they return.  Hence, the calling function can deallocate or
4314 ** modify the text after they return without harm.
4315 ** ^The sqlite3_result_error_code() function changes the error code
4316 ** returned by SQLite as a result of an error in a function.  ^By default,
4317 ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4318 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4319 **
4320 ** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
4321 ** indicating that a string or BLOB is too long to represent.
4322 **
4323 ** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
4324 ** indicating that a memory allocation failed.
4325 **
4326 ** ^The sqlite3_result_int() interface sets the return value
4327 ** of the application-defined function to be the 32-bit signed integer
4328 ** value given in the 2nd argument.
4329 ** ^The sqlite3_result_int64() interface sets the return value
4330 ** of the application-defined function to be the 64-bit signed integer
4331 ** value given in the 2nd argument.
4332 **
4333 ** ^The sqlite3_result_null() interface sets the return value
4334 ** of the application-defined function to be NULL.
4335 **
4336 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
4337 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4338 ** set the return value of the application-defined function to be
4339 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4340 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4341 ** ^SQLite takes the text result from the application from
4342 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4343 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4344 ** is negative, then SQLite takes result text from the 2nd parameter
4345 ** through the first zero character.
4346 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4347 ** is non-negative, then as many bytes (not characters) of the text
4348 ** pointed to by the 2nd parameter are taken as the application-defined
4349 ** function result.
4350 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4351 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4352 ** function as the destructor on the text or BLOB result when it has
4353 ** finished using that result.
4354 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4355 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4356 ** assumes that the text or BLOB result is in constant space and does not
4357 ** copy the content of the parameter nor call a destructor on the content
4358 ** when it has finished using that result.
4359 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4360 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4361 ** then SQLite makes a copy of the result into space obtained from
4362 ** from [sqlite3_malloc()] before it returns.
4363 **
4364 ** ^The sqlite3_result_value() interface sets the result of
4365 ** the application-defined function to be a copy the
4366 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4367 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4368 ** so that the [sqlite3_value] specified in the parameter may change or
4369 ** be deallocated after sqlite3_result_value() returns without harm.
4370 ** ^A [protected sqlite3_value] object may always be used where an
4371 ** [unprotected sqlite3_value] object is required, so either
4372 ** kind of [sqlite3_value] object can be used with this interface.
4373 **
4374 ** If these routines are called from within the different thread
4375 ** than the one containing the application-defined function that received
4376 ** the [sqlite3_context] pointer, the results are undefined.
4377 */
4378 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4379 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4380 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4381 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4382 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4383 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4384 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4385 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4386 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4387 SQLITE_API void sqlite3_result_null(sqlite3_context*);
4388 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4389 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4390 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4391 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4392 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4393 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4394
4395 /*
4396 ** CAPI3REF: Define New Collating Sequences
4397 **
4398 ** ^These functions add, remove, or modify a [collation] associated
4399 ** with the [database connection] specified as the first argument.
4400 **
4401 ** ^The name of the collation is a UTF-8 string
4402 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4403 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4404 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4405 ** considered to be the same name.
4406 **
4407 ** ^(The third argument (eTextRep) must be one of the constants:
4408 ** <ul>
4409 ** <li> [SQLITE_UTF8],
4410 ** <li> [SQLITE_UTF16LE],
4411 ** <li> [SQLITE_UTF16BE],
4412 ** <li> [SQLITE_UTF16], or
4413 ** <li> [SQLITE_UTF16_ALIGNED].
4414 ** </ul>)^
4415 ** ^The eTextRep argument determines the encoding of strings passed
4416 ** to the collating function callback, xCallback.
4417 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4418 ** force strings to be UTF16 with native byte order.
4419 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4420 ** on an even byte address.
4421 **
4422 ** ^The fourth argument, pArg, is a application data pointer that is passed
4423 ** through as the first argument to the collating function callback.
4424 **
4425 ** ^The fifth argument, xCallback, is a pointer to the collating function.
4426 ** ^Multiple collating functions can be registered using the same name but
4427 ** with different eTextRep parameters and SQLite will use whichever
4428 ** function requires the least amount of data transformation.
4429 ** ^If the xCallback argument is NULL then the collating function is
4430 ** deleted.  ^When all collating functions having the same name are deleted,
4431 ** that collation is no longer usable.
4432 **
4433 ** ^The collating function callback is invoked with a copy of the pArg 
4434 ** application data pointer and with two strings in the encoding specified
4435 ** by the eTextRep argument.  The collating function must return an
4436 ** integer that is negative, zero, or positive
4437 ** if the first string is less than, equal to, or greater than the second,
4438 ** respectively.  A collating function must alway return the same answer
4439 ** given the same inputs.  If two or more collating functions are registered
4440 ** to the same collation name (using different eTextRep values) then all
4441 ** must give an equivalent answer when invoked with equivalent strings.
4442 ** The collating function must obey the following properties for all
4443 ** strings A, B, and C:
4444 **
4445 ** <ol>
4446 ** <li> If A==B then B==A.
4447 ** <li> If A==B and B==C then A==C.
4448 ** <li> If A&lt;B THEN B&gt;A.
4449 ** <li> If A&lt;B and B&lt;C then A&lt;C.
4450 ** </ol>
4451 **
4452 ** If a collating function fails any of the above constraints and that
4453 ** collating function is  registered and used, then the behavior of SQLite
4454 ** is undefined.
4455 **
4456 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4457 ** with the addition that the xDestroy callback is invoked on pArg when
4458 ** the collating function is deleted.
4459 ** ^Collating functions are deleted when they are overridden by later
4460 ** calls to the collation creation functions or when the
4461 ** [database connection] is closed using [sqlite3_close()].
4462 **
4463 ** ^The xDestroy callback is <u>not</u> called if the 
4464 ** sqlite3_create_collation_v2() function fails.  Applications that invoke
4465 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should 
4466 ** check the return code and dispose of the application data pointer
4467 ** themselves rather than expecting SQLite to deal with it for them.
4468 ** This is different from every other SQLite interface.  The inconsistency 
4469 ** is unfortunate but cannot be changed without breaking backwards 
4470 ** compatibility.
4471 **
4472 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4473 */
4474 SQLITE_API int sqlite3_create_collation(
4475   sqlite3*, 
4476   const char *zName, 
4477   int eTextRep, 
4478   void *pArg,
4479   int(*xCompare)(void*,int,const void*,int,const void*)
4480 );
4481 SQLITE_API int sqlite3_create_collation_v2(
4482   sqlite3*, 
4483   const char *zName, 
4484   int eTextRep, 
4485   void *pArg,
4486   int(*xCompare)(void*,int,const void*,int,const void*),
4487   void(*xDestroy)(void*)
4488 );
4489 SQLITE_API int sqlite3_create_collation16(
4490   sqlite3*, 
4491   const void *zName,
4492   int eTextRep, 
4493   void *pArg,
4494   int(*xCompare)(void*,int,const void*,int,const void*)
4495 );
4496
4497 /*
4498 ** CAPI3REF: Collation Needed Callbacks
4499 **
4500 ** ^To avoid having to register all collation sequences before a database
4501 ** can be used, a single callback function may be registered with the
4502 ** [database connection] to be invoked whenever an undefined collation
4503 ** sequence is required.
4504 **
4505 ** ^If the function is registered using the sqlite3_collation_needed() API,
4506 ** then it is passed the names of undefined collation sequences as strings
4507 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4508 ** the names are passed as UTF-16 in machine native byte order.
4509 ** ^A call to either function replaces the existing collation-needed callback.
4510 **
4511 ** ^(When the callback is invoked, the first argument passed is a copy
4512 ** of the second argument to sqlite3_collation_needed() or
4513 ** sqlite3_collation_needed16().  The second argument is the database
4514 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4515 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4516 ** sequence function required.  The fourth parameter is the name of the
4517 ** required collation sequence.)^
4518 **
4519 ** The callback function should register the desired collation using
4520 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4521 ** [sqlite3_create_collation_v2()].
4522 */
4523 SQLITE_API int sqlite3_collation_needed(
4524   sqlite3*, 
4525   void*, 
4526   void(*)(void*,sqlite3*,int eTextRep,const char*)
4527 );
4528 SQLITE_API int sqlite3_collation_needed16(
4529   sqlite3*, 
4530   void*,
4531   void(*)(void*,sqlite3*,int eTextRep,const void*)
4532 );
4533
4534 #ifdef SQLITE_HAS_CODEC
4535 /*
4536 ** Specify the key for an encrypted database.  This routine should be
4537 ** called right after sqlite3_open().
4538 **
4539 ** The code to implement this API is not available in the public release
4540 ** of SQLite.
4541 */
4542 SQLITE_API int sqlite3_key(
4543   sqlite3 *db,                   /* Database to be rekeyed */
4544   const void *pKey, int nKey     /* The key */
4545 );
4546
4547 /*
4548 ** Change the key on an open database.  If the current database is not
4549 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4550 ** database is decrypted.
4551 **
4552 ** The code to implement this API is not available in the public release
4553 ** of SQLite.
4554 */
4555 SQLITE_API int sqlite3_rekey(
4556   sqlite3 *db,                   /* Database to be rekeyed */
4557   const void *pKey, int nKey     /* The new key */
4558 );
4559
4560 /*
4561 ** Specify the activation key for a SEE database.  Unless 
4562 ** activated, none of the SEE routines will work.
4563 */
4564 SQLITE_API void sqlite3_activate_see(
4565   const char *zPassPhrase        /* Activation phrase */
4566 );
4567 #endif
4568
4569 #ifdef SQLITE_ENABLE_CEROD
4570 /*
4571 ** Specify the activation key for a CEROD database.  Unless 
4572 ** activated, none of the CEROD routines will work.
4573 */
4574 SQLITE_API void sqlite3_activate_cerod(
4575   const char *zPassPhrase        /* Activation phrase */
4576 );
4577 #endif
4578
4579 /*
4580 ** CAPI3REF: Suspend Execution For A Short Time
4581 **
4582 ** The sqlite3_sleep() function causes the current thread to suspend execution
4583 ** for at least a number of milliseconds specified in its parameter.
4584 **
4585 ** If the operating system does not support sleep requests with
4586 ** millisecond time resolution, then the time will be rounded up to
4587 ** the nearest second. The number of milliseconds of sleep actually
4588 ** requested from the operating system is returned.
4589 **
4590 ** ^SQLite implements this interface by calling the xSleep()
4591 ** method of the default [sqlite3_vfs] object.  If the xSleep() method
4592 ** of the default VFS is not implemented correctly, or not implemented at
4593 ** all, then the behavior of sqlite3_sleep() may deviate from the description
4594 ** in the previous paragraphs.
4595 */
4596 SQLITE_API int sqlite3_sleep(int);
4597
4598 /*
4599 ** CAPI3REF: Name Of The Folder Holding Temporary Files
4600 **
4601 ** ^(If this global variable is made to point to a string which is
4602 ** the name of a folder (a.k.a. directory), then all temporary files
4603 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
4604 ** will be placed in that directory.)^  ^If this variable
4605 ** is a NULL pointer, then SQLite performs a search for an appropriate
4606 ** temporary file directory.
4607 **
4608 ** It is not safe to read or modify this variable in more than one
4609 ** thread at a time.  It is not safe to read or modify this variable
4610 ** if a [database connection] is being used at the same time in a separate
4611 ** thread.
4612 ** It is intended that this variable be set once
4613 ** as part of process initialization and before any SQLite interface
4614 ** routines have been called and that this variable remain unchanged
4615 ** thereafter.
4616 **
4617 ** ^The [temp_store_directory pragma] may modify this variable and cause
4618 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
4619 ** the [temp_store_directory pragma] always assumes that any string
4620 ** that this variable points to is held in memory obtained from 
4621 ** [sqlite3_malloc] and the pragma may attempt to free that memory
4622 ** using [sqlite3_free].
4623 ** Hence, if this variable is modified directly, either it should be
4624 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
4625 ** or else the use of the [temp_store_directory pragma] should be avoided.
4626 */
4627 SQLITE_API char *sqlite3_temp_directory;
4628
4629 /*
4630 ** CAPI3REF: Test For Auto-Commit Mode
4631 ** KEYWORDS: {autocommit mode}
4632 **
4633 ** ^The sqlite3_get_autocommit() interface returns non-zero or
4634 ** zero if the given database connection is or is not in autocommit mode,
4635 ** respectively.  ^Autocommit mode is on by default.
4636 ** ^Autocommit mode is disabled by a [BEGIN] statement.
4637 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
4638 **
4639 ** If certain kinds of errors occur on a statement within a multi-statement
4640 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
4641 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
4642 ** transaction might be rolled back automatically.  The only way to
4643 ** find out whether SQLite automatically rolled back the transaction after
4644 ** an error is to use this function.
4645 **
4646 ** If another thread changes the autocommit status of the database
4647 ** connection while this routine is running, then the return value
4648 ** is undefined.
4649 */
4650 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
4651
4652 /*
4653 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
4654 **
4655 ** ^The sqlite3_db_handle interface returns the [database connection] handle
4656 ** to which a [prepared statement] belongs.  ^The [database connection]
4657 ** returned by sqlite3_db_handle is the same [database connection]
4658 ** that was the first argument
4659 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
4660 ** create the statement in the first place.
4661 */
4662 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
4663
4664 /*
4665 ** CAPI3REF: Find the next prepared statement
4666 **
4667 ** ^This interface returns a pointer to the next [prepared statement] after
4668 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
4669 ** then this interface returns a pointer to the first prepared statement
4670 ** associated with the database connection pDb.  ^If no prepared statement
4671 ** satisfies the conditions of this routine, it returns NULL.
4672 **
4673 ** The [database connection] pointer D in a call to
4674 ** [sqlite3_next_stmt(D,S)] must refer to an open database
4675 ** connection and in particular must not be a NULL pointer.
4676 */
4677 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
4678
4679 /*
4680 ** CAPI3REF: Commit And Rollback Notification Callbacks
4681 **
4682 ** ^The sqlite3_commit_hook() interface registers a callback
4683 ** function to be invoked whenever a transaction is [COMMIT | committed].
4684 ** ^Any callback set by a previous call to sqlite3_commit_hook()
4685 ** for the same database connection is overridden.
4686 ** ^The sqlite3_rollback_hook() interface registers a callback
4687 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
4688 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
4689 ** for the same database connection is overridden.
4690 ** ^The pArg argument is passed through to the callback.
4691 ** ^If the callback on a commit hook function returns non-zero,
4692 ** then the commit is converted into a rollback.
4693 **
4694 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
4695 ** return the P argument from the previous call of the same function
4696 ** on the same [database connection] D, or NULL for
4697 ** the first call for each function on D.
4698 **
4699 ** The callback implementation must not do anything that will modify
4700 ** the database connection that invoked the callback.  Any actions
4701 ** to modify the database connection must be deferred until after the
4702 ** completion of the [sqlite3_step()] call that triggered the commit
4703 ** or rollback hook in the first place.
4704 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4705 ** database connections for the meaning of "modify" in this paragraph.
4706 **
4707 ** ^Registering a NULL function disables the callback.
4708 **
4709 ** ^When the commit hook callback routine returns zero, the [COMMIT]
4710 ** operation is allowed to continue normally.  ^If the commit hook
4711 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
4712 ** ^The rollback hook is invoked on a rollback that results from a commit
4713 ** hook returning non-zero, just as it would be with any other rollback.
4714 **
4715 ** ^For the purposes of this API, a transaction is said to have been
4716 ** rolled back if an explicit "ROLLBACK" statement is executed, or
4717 ** an error or constraint causes an implicit rollback to occur.
4718 ** ^The rollback callback is not invoked if a transaction is
4719 ** automatically rolled back because the database connection is closed.
4720 **
4721 ** See also the [sqlite3_update_hook()] interface.
4722 */
4723 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
4724 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
4725
4726 /*
4727 ** CAPI3REF: Data Change Notification Callbacks
4728 **
4729 ** ^The sqlite3_update_hook() interface registers a callback function
4730 ** with the [database connection] identified by the first argument
4731 ** to be invoked whenever a row is updated, inserted or deleted.
4732 ** ^Any callback set by a previous call to this function
4733 ** for the same database connection is overridden.
4734 **
4735 ** ^The second argument is a pointer to the function to invoke when a
4736 ** row is updated, inserted or deleted.
4737 ** ^The first argument to the callback is a copy of the third argument
4738 ** to sqlite3_update_hook().
4739 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
4740 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
4741 ** to be invoked.
4742 ** ^The third and fourth arguments to the callback contain pointers to the
4743 ** database and table name containing the affected row.
4744 ** ^The final callback parameter is the [rowid] of the row.
4745 ** ^In the case of an update, this is the [rowid] after the update takes place.
4746 **
4747 ** ^(The update hook is not invoked when internal system tables are
4748 ** modified (i.e. sqlite_master and sqlite_sequence).)^
4749 **
4750 ** ^In the current implementation, the update hook
4751 ** is not invoked when duplication rows are deleted because of an
4752 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
4753 ** invoked when rows are deleted using the [truncate optimization].
4754 ** The exceptions defined in this paragraph might change in a future
4755 ** release of SQLite.
4756 **
4757 ** The update hook implementation must not do anything that will modify
4758 ** the database connection that invoked the update hook.  Any actions
4759 ** to modify the database connection must be deferred until after the
4760 ** completion of the [sqlite3_step()] call that triggered the update hook.
4761 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4762 ** database connections for the meaning of "modify" in this paragraph.
4763 **
4764 ** ^The sqlite3_update_hook(D,C,P) function
4765 ** returns the P argument from the previous call
4766 ** on the same [database connection] D, or NULL for
4767 ** the first call on D.
4768 **
4769 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
4770 ** interfaces.
4771 */
4772 SQLITE_API void *sqlite3_update_hook(
4773   sqlite3*, 
4774   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
4775   void*
4776 );
4777
4778 /*
4779 ** CAPI3REF: Enable Or Disable Shared Pager Cache
4780 ** KEYWORDS: {shared cache}
4781 **
4782 ** ^(This routine enables or disables the sharing of the database cache
4783 ** and schema data structures between [database connection | connections]
4784 ** to the same database. Sharing is enabled if the argument is true
4785 ** and disabled if the argument is false.)^
4786 **
4787 ** ^Cache sharing is enabled and disabled for an entire process.
4788 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
4789 ** sharing was enabled or disabled for each thread separately.
4790 **
4791 ** ^(The cache sharing mode set by this interface effects all subsequent
4792 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
4793 ** Existing database connections continue use the sharing mode
4794 ** that was in effect at the time they were opened.)^
4795 **
4796 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
4797 ** successfully.  An [error code] is returned otherwise.)^
4798 **
4799 ** ^Shared cache is disabled by default. But this might change in
4800 ** future releases of SQLite.  Applications that care about shared
4801 ** cache setting should set it explicitly.
4802 **
4803 ** See Also:  [SQLite Shared-Cache Mode]
4804 */
4805 SQLITE_API int sqlite3_enable_shared_cache(int);
4806
4807 /*
4808 ** CAPI3REF: Attempt To Free Heap Memory
4809 **
4810 ** ^The sqlite3_release_memory() interface attempts to free N bytes
4811 ** of heap memory by deallocating non-essential memory allocations
4812 ** held by the database library.   Memory used to cache database
4813 ** pages to improve performance is an example of non-essential memory.
4814 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
4815 ** which might be more or less than the amount requested.
4816 ** ^The sqlite3_release_memory() routine is a no-op returning zero
4817 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
4818 */
4819 SQLITE_API int sqlite3_release_memory(int);
4820
4821 /*
4822 ** CAPI3REF: Impose A Limit On Heap Size
4823 **
4824 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
4825 ** soft limit on the amount of heap memory that may be allocated by SQLite.
4826 ** ^SQLite strives to keep heap memory utilization below the soft heap
4827 ** limit by reducing the number of pages held in the page cache
4828 ** as heap memory usages approaches the limit.
4829 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
4830 ** below the limit, it will exceed the limit rather than generate
4831 ** an [SQLITE_NOMEM] error.  In other words, the soft heap limit 
4832 ** is advisory only.
4833 **
4834 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
4835 ** the soft heap limit prior to the call.  ^If the argument N is negative
4836 ** then no change is made to the soft heap limit.  Hence, the current
4837 ** size of the soft heap limit can be determined by invoking
4838 ** sqlite3_soft_heap_limit64() with a negative argument.
4839 **
4840 ** ^If the argument N is zero then the soft heap limit is disabled.
4841 **
4842 ** ^(The soft heap limit is not enforced in the current implementation
4843 ** if one or more of following conditions are true:
4844 **
4845 ** <ul>
4846 ** <li> The soft heap limit is set to zero.
4847 ** <li> Memory accounting is disabled using a combination of the
4848 **      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
4849 **      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
4850 ** <li> An alternative page cache implementation is specifed using
4851 **      [sqlite3_config]([SQLITE_CONFIG_PCACHE],...).
4852 ** <li> The page cache allocates from its own memory pool supplied
4853 **      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
4854 **      from the heap.
4855 ** </ul>)^
4856 **
4857 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
4858 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
4859 ** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
4860 ** the soft heap limit is enforced on every memory allocation.  Without
4861 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
4862 ** when memory is allocated by the page cache.  Testing suggests that because
4863 ** the page cache is the predominate memory user in SQLite, most
4864 ** applications will achieve adequate soft heap limit enforcement without
4865 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
4866 **
4867 ** The circumstances under which SQLite will enforce the soft heap limit may
4868 ** changes in future releases of SQLite.
4869 */
4870 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
4871
4872 /*
4873 ** CAPI3REF: Deprecated Soft Heap Limit Interface
4874 ** DEPRECATED
4875 **
4876 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
4877 ** interface.  This routine is provided for historical compatibility
4878 ** only.  All new applications should use the
4879 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
4880 */
4881 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
4882
4883
4884 /*
4885 ** CAPI3REF: Extract Metadata About A Column Of A Table
4886 **
4887 ** ^This routine returns metadata about a specific column of a specific
4888 ** database table accessible using the [database connection] handle
4889 ** passed as the first function argument.
4890 **
4891 ** ^The column is identified by the second, third and fourth parameters to
4892 ** this function. ^The second parameter is either the name of the database
4893 ** (i.e. "main", "temp", or an attached database) containing the specified
4894 ** table or NULL. ^If it is NULL, then all attached databases are searched
4895 ** for the table using the same algorithm used by the database engine to
4896 ** resolve unqualified table references.
4897 **
4898 ** ^The third and fourth parameters to this function are the table and column
4899 ** name of the desired column, respectively. Neither of these parameters
4900 ** may be NULL.
4901 **
4902 ** ^Metadata is returned by writing to the memory locations passed as the 5th
4903 ** and subsequent parameters to this function. ^Any of these arguments may be
4904 ** NULL, in which case the corresponding element of metadata is omitted.
4905 **
4906 ** ^(<blockquote>
4907 ** <table border="1">
4908 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
4909 **
4910 ** <tr><td> 5th <td> const char* <td> Data type
4911 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
4912 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
4913 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
4914 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
4915 ** </table>
4916 ** </blockquote>)^
4917 **
4918 ** ^The memory pointed to by the character pointers returned for the
4919 ** declaration type and collation sequence is valid only until the next
4920 ** call to any SQLite API function.
4921 **
4922 ** ^If the specified table is actually a view, an [error code] is returned.
4923 **
4924 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
4925 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
4926 ** parameters are set for the explicitly declared column. ^(If there is no
4927 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
4928 ** parameters are set as follows:
4929 **
4930 ** <pre>
4931 **     data type: "INTEGER"
4932 **     collation sequence: "BINARY"
4933 **     not null: 0
4934 **     primary key: 1
4935 **     auto increment: 0
4936 ** </pre>)^
4937 **
4938 ** ^(This function may load one or more schemas from database files. If an
4939 ** error occurs during this process, or if the requested table or column
4940 ** cannot be found, an [error code] is returned and an error message left
4941 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
4942 **
4943 ** ^This API is only available if the library was compiled with the
4944 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
4945 */
4946 SQLITE_API int sqlite3_table_column_metadata(
4947   sqlite3 *db,                /* Connection handle */
4948   const char *zDbName,        /* Database name or NULL */
4949   const char *zTableName,     /* Table name */
4950   const char *zColumnName,    /* Column name */
4951   char const **pzDataType,    /* OUTPUT: Declared data type */
4952   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
4953   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
4954   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
4955   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
4956 );
4957
4958 /*
4959 ** CAPI3REF: Load An Extension
4960 **
4961 ** ^This interface loads an SQLite extension library from the named file.
4962 **
4963 ** ^The sqlite3_load_extension() interface attempts to load an
4964 ** SQLite extension library contained in the file zFile.
4965 **
4966 ** ^The entry point is zProc.
4967 ** ^zProc may be 0, in which case the name of the entry point
4968 ** defaults to "sqlite3_extension_init".
4969 ** ^The sqlite3_load_extension() interface returns
4970 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
4971 ** ^If an error occurs and pzErrMsg is not 0, then the
4972 ** [sqlite3_load_extension()] interface shall attempt to
4973 ** fill *pzErrMsg with error message text stored in memory
4974 ** obtained from [sqlite3_malloc()]. The calling function
4975 ** should free this memory by calling [sqlite3_free()].
4976 **
4977 ** ^Extension loading must be enabled using
4978 ** [sqlite3_enable_load_extension()] prior to calling this API,
4979 ** otherwise an error will be returned.
4980 **
4981 ** See also the [load_extension() SQL function].
4982 */
4983 SQLITE_API int sqlite3_load_extension(
4984   sqlite3 *db,          /* Load the extension into this database connection */
4985   const char *zFile,    /* Name of the shared library containing extension */
4986   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
4987   char **pzErrMsg       /* Put error message here if not 0 */
4988 );
4989
4990 /*
4991 ** CAPI3REF: Enable Or Disable Extension Loading
4992 **
4993 ** ^So as not to open security holes in older applications that are
4994 ** unprepared to deal with extension loading, and as a means of disabling
4995 ** extension loading while evaluating user-entered SQL, the following API
4996 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
4997 **
4998 ** ^Extension loading is off by default. See ticket #1863.
4999 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5000 ** to turn extension loading on and call it with onoff==0 to turn
5001 ** it back off again.
5002 */
5003 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5004
5005 /*
5006 ** CAPI3REF: Automatically Load Statically Linked Extensions
5007 **
5008 ** ^This interface causes the xEntryPoint() function to be invoked for
5009 ** each new [database connection] that is created.  The idea here is that
5010 ** xEntryPoint() is the entry point for a statically linked SQLite extension
5011 ** that is to be automatically loaded into all new database connections.
5012 **
5013 ** ^(Even though the function prototype shows that xEntryPoint() takes
5014 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
5015 ** arguments and expects and integer result as if the signature of the
5016 ** entry point where as follows:
5017 **
5018 ** <blockquote><pre>
5019 ** &nbsp;  int xEntryPoint(
5020 ** &nbsp;    sqlite3 *db,
5021 ** &nbsp;    const char **pzErrMsg,
5022 ** &nbsp;    const struct sqlite3_api_routines *pThunk
5023 ** &nbsp;  );
5024 ** </pre></blockquote>)^
5025 **
5026 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5027 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5028 ** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
5029 ** is NULL before calling the xEntryPoint().  ^SQLite will invoke
5030 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
5031 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5032 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5033 **
5034 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5035 ** on the list of automatic extensions is a harmless no-op. ^No entry point
5036 ** will be called more than once for each database connection that is opened.
5037 **
5038 ** See also: [sqlite3_reset_auto_extension()].
5039 */
5040 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
5041
5042 /*
5043 ** CAPI3REF: Reset Automatic Extension Loading
5044 **
5045 ** ^This interface disables all automatic extensions previously
5046 ** registered using [sqlite3_auto_extension()].
5047 */
5048 SQLITE_API void sqlite3_reset_auto_extension(void);
5049
5050 /*
5051 ** The interface to the virtual-table mechanism is currently considered
5052 ** to be experimental.  The interface might change in incompatible ways.
5053 ** If this is a problem for you, do not use the interface at this time.
5054 **
5055 ** When the virtual-table mechanism stabilizes, we will declare the
5056 ** interface fixed, support it indefinitely, and remove this comment.
5057 */
5058
5059 /*
5060 ** Structures used by the virtual table interface
5061 */
5062 typedef struct sqlite3_vtab sqlite3_vtab;
5063 typedef struct sqlite3_index_info sqlite3_index_info;
5064 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5065 typedef struct sqlite3_module sqlite3_module;
5066
5067 /*
5068 ** CAPI3REF: Virtual Table Object
5069 ** KEYWORDS: sqlite3_module {virtual table module}
5070 **
5071 ** This structure, sometimes called a a "virtual table module", 
5072 ** defines the implementation of a [virtual tables].  
5073 ** This structure consists mostly of methods for the module.
5074 **
5075 ** ^A virtual table module is created by filling in a persistent
5076 ** instance of this structure and passing a pointer to that instance
5077 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5078 ** ^The registration remains valid until it is replaced by a different
5079 ** module or until the [database connection] closes.  The content
5080 ** of this structure must not change while it is registered with
5081 ** any database connection.
5082 */
5083 struct sqlite3_module {
5084   int iVersion;
5085   int (*xCreate)(sqlite3*, void *pAux,
5086                int argc, const char *const*argv,
5087                sqlite3_vtab **ppVTab, char**);
5088   int (*xConnect)(sqlite3*, void *pAux,
5089                int argc, const char *const*argv,
5090                sqlite3_vtab **ppVTab, char**);
5091   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5092   int (*xDisconnect)(sqlite3_vtab *pVTab);
5093   int (*xDestroy)(sqlite3_vtab *pVTab);
5094   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5095   int (*xClose)(sqlite3_vtab_cursor*);
5096   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5097                 int argc, sqlite3_value **argv);
5098   int (*xNext)(sqlite3_vtab_cursor*);
5099   int (*xEof)(sqlite3_vtab_cursor*);
5100   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5101   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5102   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5103   int (*xBegin)(sqlite3_vtab *pVTab);
5104   int (*xSync)(sqlite3_vtab *pVTab);
5105   int (*xCommit)(sqlite3_vtab *pVTab);
5106   int (*xRollback)(sqlite3_vtab *pVTab);
5107   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5108                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5109                        void **ppArg);
5110   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5111 };
5112
5113 /*
5114 ** CAPI3REF: Virtual Table Indexing Information
5115 ** KEYWORDS: sqlite3_index_info
5116 **
5117 ** The sqlite3_index_info structure and its substructures is used as part
5118 ** of the [virtual table] interface to
5119 ** pass information into and receive the reply from the [xBestIndex]
5120 ** method of a [virtual table module].  The fields under **Inputs** are the
5121 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5122 ** results into the **Outputs** fields.
5123 **
5124 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
5125 **
5126 ** <blockquote>column OP expr</blockquote>
5127 **
5128 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
5129 ** stored in aConstraint[].op using one of the
5130 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5131 ** ^(The index of the column is stored in
5132 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
5133 ** expr on the right-hand side can be evaluated (and thus the constraint
5134 ** is usable) and false if it cannot.)^
5135 **
5136 ** ^The optimizer automatically inverts terms of the form "expr OP column"
5137 ** and makes other simplifications to the WHERE clause in an attempt to
5138 ** get as many WHERE clause terms into the form shown above as possible.
5139 ** ^The aConstraint[] array only reports WHERE clause terms that are
5140 ** relevant to the particular virtual table being queried.
5141 **
5142 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
5143 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
5144 **
5145 ** The [xBestIndex] method must fill aConstraintUsage[] with information
5146 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
5147 ** the right-hand side of the corresponding aConstraint[] is evaluated
5148 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
5149 ** is true, then the constraint is assumed to be fully handled by the
5150 ** virtual table and is not checked again by SQLite.)^
5151 **
5152 ** ^The idxNum and idxPtr values are recorded and passed into the
5153 ** [xFilter] method.
5154 ** ^[sqlite3_free()] is used to free idxPtr if and only if
5155 ** needToFreeIdxPtr is true.
5156 **
5157 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5158 ** the correct order to satisfy the ORDER BY clause so that no separate
5159 ** sorting step is required.
5160 **
5161 ** ^The estimatedCost value is an estimate of the cost of doing the
5162 ** particular lookup.  A full scan of a table with N entries should have
5163 ** a cost of N.  A binary search of a table of N entries should have a
5164 ** cost of approximately log(N).
5165 */
5166 struct sqlite3_index_info {
5167   /* Inputs */
5168   int nConstraint;           /* Number of entries in aConstraint */
5169   struct sqlite3_index_constraint {
5170      int iColumn;              /* Column on left-hand side of constraint */
5171      unsigned char op;         /* Constraint operator */
5172      unsigned char usable;     /* True if this constraint is usable */
5173      int iTermOffset;          /* Used internally - xBestIndex should ignore */
5174   } *aConstraint;            /* Table of WHERE clause constraints */
5175   int nOrderBy;              /* Number of terms in the ORDER BY clause */
5176   struct sqlite3_index_orderby {
5177      int iColumn;              /* Column number */
5178      unsigned char desc;       /* True for DESC.  False for ASC. */
5179   } *aOrderBy;               /* The ORDER BY clause */
5180   /* Outputs */
5181   struct sqlite3_index_constraint_usage {
5182     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5183     unsigned char omit;      /* Do not code a test for this constraint */
5184   } *aConstraintUsage;
5185   int idxNum;                /* Number used to identify the index */
5186   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
5187   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
5188   int orderByConsumed;       /* True if output is already ordered */
5189   double estimatedCost;      /* Estimated cost of using this index */
5190 };
5191
5192 /*
5193 ** CAPI3REF: Virtual Table Constraint Operator Codes
5194 **
5195 ** These macros defined the allowed values for the
5196 ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
5197 ** an operator that is part of a constraint term in the wHERE clause of
5198 ** a query that uses a [virtual table].
5199 */
5200 #define SQLITE_INDEX_CONSTRAINT_EQ    2
5201 #define SQLITE_INDEX_CONSTRAINT_GT    4
5202 #define SQLITE_INDEX_CONSTRAINT_LE    8
5203 #define SQLITE_INDEX_CONSTRAINT_LT    16
5204 #define SQLITE_INDEX_CONSTRAINT_GE    32
5205 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
5206
5207 /*
5208 ** CAPI3REF: Register A Virtual Table Implementation
5209 **
5210 ** ^These routines are used to register a new [virtual table module] name.
5211 ** ^Module names must be registered before
5212 ** creating a new [virtual table] using the module and before using a
5213 ** preexisting [virtual table] for the module.
5214 **
5215 ** ^The module name is registered on the [database connection] specified
5216 ** by the first parameter.  ^The name of the module is given by the 
5217 ** second parameter.  ^The third parameter is a pointer to
5218 ** the implementation of the [virtual table module].   ^The fourth
5219 ** parameter is an arbitrary client data pointer that is passed through
5220 ** into the [xCreate] and [xConnect] methods of the virtual table module
5221 ** when a new virtual table is be being created or reinitialized.
5222 **
5223 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5224 ** is a pointer to a destructor for the pClientData.  ^SQLite will
5225 ** invoke the destructor function (if it is not NULL) when SQLite
5226 ** no longer needs the pClientData pointer.  ^The destructor will also
5227 ** be invoked if the call to sqlite3_create_module_v2() fails.
5228 ** ^The sqlite3_create_module()
5229 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
5230 ** destructor.
5231 */
5232 SQLITE_API int sqlite3_create_module(
5233   sqlite3 *db,               /* SQLite connection to register module with */
5234   const char *zName,         /* Name of the module */
5235   const sqlite3_module *p,   /* Methods for the module */
5236   void *pClientData          /* Client data for xCreate/xConnect */
5237 );
5238 SQLITE_API int sqlite3_create_module_v2(
5239   sqlite3 *db,               /* SQLite connection to register module with */
5240   const char *zName,         /* Name of the module */
5241   const sqlite3_module *p,   /* Methods for the module */
5242   void *pClientData,         /* Client data for xCreate/xConnect */
5243   void(*xDestroy)(void*)     /* Module destructor function */
5244 );
5245
5246 /*
5247 ** CAPI3REF: Virtual Table Instance Object
5248 ** KEYWORDS: sqlite3_vtab
5249 **
5250 ** Every [virtual table module] implementation uses a subclass
5251 ** of this object to describe a particular instance
5252 ** of the [virtual table].  Each subclass will
5253 ** be tailored to the specific needs of the module implementation.
5254 ** The purpose of this superclass is to define certain fields that are
5255 ** common to all module implementations.
5256 **
5257 ** ^Virtual tables methods can set an error message by assigning a
5258 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
5259 ** take care that any prior string is freed by a call to [sqlite3_free()]
5260 ** prior to assigning a new string to zErrMsg.  ^After the error message
5261 ** is delivered up to the client application, the string will be automatically
5262 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5263 */
5264 struct sqlite3_vtab {
5265   const sqlite3_module *pModule;  /* The module for this virtual table */
5266   int nRef;                       /* NO LONGER USED */
5267   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5268   /* Virtual table implementations will typically add additional fields */
5269 };
5270
5271 /*
5272 ** CAPI3REF: Virtual Table Cursor Object
5273 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5274 **
5275 ** Every [virtual table module] implementation uses a subclass of the
5276 ** following structure to describe cursors that point into the
5277 ** [virtual table] and are used
5278 ** to loop through the virtual table.  Cursors are created using the
5279 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5280 ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
5281 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5282 ** of the module.  Each module implementation will define
5283 ** the content of a cursor structure to suit its own needs.
5284 **
5285 ** This superclass exists in order to define fields of the cursor that
5286 ** are common to all implementations.
5287 */
5288 struct sqlite3_vtab_cursor {
5289   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5290   /* Virtual table implementations will typically add additional fields */
5291 };
5292
5293 /*
5294 ** CAPI3REF: Declare The Schema Of A Virtual Table
5295 **
5296 ** ^The [xCreate] and [xConnect] methods of a
5297 ** [virtual table module] call this interface
5298 ** to declare the format (the names and datatypes of the columns) of
5299 ** the virtual tables they implement.
5300 */
5301 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5302
5303 /*
5304 ** CAPI3REF: Overload A Function For A Virtual Table
5305 **
5306 ** ^(Virtual tables can provide alternative implementations of functions
5307 ** using the [xFindFunction] method of the [virtual table module].  
5308 ** But global versions of those functions
5309 ** must exist in order to be overloaded.)^
5310 **
5311 ** ^(This API makes sure a global version of a function with a particular
5312 ** name and number of parameters exists.  If no such function exists
5313 ** before this API is called, a new function is created.)^  ^The implementation
5314 ** of the new function always causes an exception to be thrown.  So
5315 ** the new function is not good for anything by itself.  Its only
5316 ** purpose is to be a placeholder function that can be overloaded
5317 ** by a [virtual table].
5318 */
5319 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5320
5321 /*
5322 ** The interface to the virtual-table mechanism defined above (back up
5323 ** to a comment remarkably similar to this one) is currently considered
5324 ** to be experimental.  The interface might change in incompatible ways.
5325 ** If this is a problem for you, do not use the interface at this time.
5326 **
5327 ** When the virtual-table mechanism stabilizes, we will declare the
5328 ** interface fixed, support it indefinitely, and remove this comment.
5329 */
5330
5331 /*
5332 ** CAPI3REF: A Handle To An Open BLOB
5333 ** KEYWORDS: {BLOB handle} {BLOB handles}
5334 **
5335 ** An instance of this object represents an open BLOB on which
5336 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5337 ** ^Objects of this type are created by [sqlite3_blob_open()]
5338 ** and destroyed by [sqlite3_blob_close()].
5339 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5340 ** can be used to read or write small subsections of the BLOB.
5341 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5342 */
5343 typedef struct sqlite3_blob sqlite3_blob;
5344
5345 /*
5346 ** CAPI3REF: Open A BLOB For Incremental I/O
5347 **
5348 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5349 ** in row iRow, column zColumn, table zTable in database zDb;
5350 ** in other words, the same BLOB that would be selected by:
5351 **
5352 ** <pre>
5353 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5354 ** </pre>)^
5355 **
5356 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
5357 ** and write access. ^If it is zero, the BLOB is opened for read access.
5358 ** ^It is not possible to open a column that is part of an index or primary 
5359 ** key for writing. ^If [foreign key constraints] are enabled, it is 
5360 ** not possible to open a column that is part of a [child key] for writing.
5361 **
5362 ** ^Note that the database name is not the filename that contains
5363 ** the database but rather the symbolic name of the database that
5364 ** appears after the AS keyword when the database is connected using [ATTACH].
5365 ** ^For the main database file, the database name is "main".
5366 ** ^For TEMP tables, the database name is "temp".
5367 **
5368 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
5369 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
5370 ** to be a null pointer.)^
5371 ** ^This function sets the [database connection] error code and message
5372 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
5373 ** functions. ^Note that the *ppBlob variable is always initialized in a
5374 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
5375 ** regardless of the success or failure of this routine.
5376 **
5377 ** ^(If the row that a BLOB handle points to is modified by an
5378 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5379 ** then the BLOB handle is marked as "expired".
5380 ** This is true if any column of the row is changed, even a column
5381 ** other than the one the BLOB handle is open on.)^
5382 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5383 ** a expired BLOB handle fail with an return code of [SQLITE_ABORT].
5384 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
5385 ** rolled back by the expiration of the BLOB.  Such changes will eventually
5386 ** commit if the transaction continues to completion.)^
5387 **
5388 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
5389 ** the opened blob.  ^The size of a blob may not be changed by this
5390 ** interface.  Use the [UPDATE] SQL command to change the size of a
5391 ** blob.
5392 **
5393 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
5394 ** and the built-in [zeroblob] SQL function can be used, if desired,
5395 ** to create an empty, zero-filled blob in which to read or write using
5396 ** this interface.
5397 **
5398 ** To avoid a resource leak, every open [BLOB handle] should eventually
5399 ** be released by a call to [sqlite3_blob_close()].
5400 */
5401 SQLITE_API int sqlite3_blob_open(
5402   sqlite3*,
5403   const char *zDb,
5404   const char *zTable,
5405   const char *zColumn,
5406   sqlite3_int64 iRow,
5407   int flags,
5408   sqlite3_blob **ppBlob
5409 );
5410
5411 /*
5412 ** CAPI3REF: Move a BLOB Handle to a New Row
5413 **
5414 ** ^This function is used to move an existing blob handle so that it points
5415 ** to a different row of the same database table. ^The new row is identified
5416 ** by the rowid value passed as the second argument. Only the row can be
5417 ** changed. ^The database, table and column on which the blob handle is open
5418 ** remain the same. Moving an existing blob handle to a new row can be
5419 ** faster than closing the existing handle and opening a new one.
5420 **
5421 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
5422 ** it must exist and there must be either a blob or text value stored in
5423 ** the nominated column.)^ ^If the new row is not present in the table, or if
5424 ** it does not contain a blob or text value, or if another error occurs, an
5425 ** SQLite error code is returned and the blob handle is considered aborted.
5426 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
5427 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
5428 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
5429 ** always returns zero.
5430 **
5431 ** ^This function sets the database handle error code and message.
5432 */
5433 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
5434
5435 /*
5436 ** CAPI3REF: Close A BLOB Handle
5437 **
5438 ** ^Closes an open [BLOB handle].
5439 **
5440 ** ^Closing a BLOB shall cause the current transaction to commit
5441 ** if there are no other BLOBs, no pending prepared statements, and the
5442 ** database connection is in [autocommit mode].
5443 ** ^If any writes were made to the BLOB, they might be held in cache
5444 ** until the close operation if they will fit.
5445 **
5446 ** ^(Closing the BLOB often forces the changes
5447 ** out to disk and so if any I/O errors occur, they will likely occur
5448 ** at the time when the BLOB is closed.  Any errors that occur during
5449 ** closing are reported as a non-zero return value.)^
5450 **
5451 ** ^(The BLOB is closed unconditionally.  Even if this routine returns
5452 ** an error code, the BLOB is still closed.)^
5453 **
5454 ** ^Calling this routine with a null pointer (such as would be returned
5455 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
5456 */
5457 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5458
5459 /*
5460 ** CAPI3REF: Return The Size Of An Open BLOB
5461 **
5462 ** ^Returns the size in bytes of the BLOB accessible via the 
5463 ** successfully opened [BLOB handle] in its only argument.  ^The
5464 ** incremental blob I/O routines can only read or overwriting existing
5465 ** blob content; they cannot change the size of a blob.
5466 **
5467 ** This routine only works on a [BLOB handle] which has been created
5468 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5469 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5470 ** to this routine results in undefined and probably undesirable behavior.
5471 */
5472 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5473
5474 /*
5475 ** CAPI3REF: Read Data From A BLOB Incrementally
5476 **
5477 ** ^(This function is used to read data from an open [BLOB handle] into a
5478 ** caller-supplied buffer. N bytes of data are copied into buffer Z
5479 ** from the open BLOB, starting at offset iOffset.)^
5480 **
5481 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5482 ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
5483 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
5484 ** ^The size of the blob (and hence the maximum value of N+iOffset)
5485 ** can be determined using the [sqlite3_blob_bytes()] interface.
5486 **
5487 ** ^An attempt to read from an expired [BLOB handle] fails with an
5488 ** error code of [SQLITE_ABORT].
5489 **
5490 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
5491 ** Otherwise, an [error code] or an [extended error code] is returned.)^
5492 **
5493 ** This routine only works on a [BLOB handle] which has been created
5494 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5495 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5496 ** to this routine results in undefined and probably undesirable behavior.
5497 **
5498 ** See also: [sqlite3_blob_write()].
5499 */
5500 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5501
5502 /*
5503 ** CAPI3REF: Write Data Into A BLOB Incrementally
5504 **
5505 ** ^This function is used to write data into an open [BLOB handle] from a
5506 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5507 ** into the open BLOB, starting at offset iOffset.
5508 **
5509 ** ^If the [BLOB handle] passed as the first argument was not opened for
5510 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
5511 ** this function returns [SQLITE_READONLY].
5512 **
5513 ** ^This function may only modify the contents of the BLOB; it is
5514 ** not possible to increase the size of a BLOB using this API.
5515 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5516 ** [SQLITE_ERROR] is returned and no data is written.  ^If N is
5517 ** less than zero [SQLITE_ERROR] is returned and no data is written.
5518 ** The size of the BLOB (and hence the maximum value of N+iOffset)
5519 ** can be determined using the [sqlite3_blob_bytes()] interface.
5520 **
5521 ** ^An attempt to write to an expired [BLOB handle] fails with an
5522 ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
5523 ** before the [BLOB handle] expired are not rolled back by the
5524 ** expiration of the handle, though of course those changes might
5525 ** have been overwritten by the statement that expired the BLOB handle
5526 ** or by other independent statements.
5527 **
5528 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
5529 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
5530 **
5531 ** This routine only works on a [BLOB handle] which has been created
5532 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5533 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5534 ** to this routine results in undefined and probably undesirable behavior.
5535 **
5536 ** See also: [sqlite3_blob_read()].
5537 */
5538 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
5539
5540 /*
5541 ** CAPI3REF: Virtual File System Objects
5542 **
5543 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
5544 ** that SQLite uses to interact
5545 ** with the underlying operating system.  Most SQLite builds come with a
5546 ** single default VFS that is appropriate for the host computer.
5547 ** New VFSes can be registered and existing VFSes can be unregistered.
5548 ** The following interfaces are provided.
5549 **
5550 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
5551 ** ^Names are case sensitive.
5552 ** ^Names are zero-terminated UTF-8 strings.
5553 ** ^If there is no match, a NULL pointer is returned.
5554 ** ^If zVfsName is NULL then the default VFS is returned.
5555 **
5556 ** ^New VFSes are registered with sqlite3_vfs_register().
5557 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
5558 ** ^The same VFS can be registered multiple times without injury.
5559 ** ^To make an existing VFS into the default VFS, register it again
5560 ** with the makeDflt flag set.  If two different VFSes with the
5561 ** same name are registered, the behavior is undefined.  If a
5562 ** VFS is registered with a name that is NULL or an empty string,
5563 ** then the behavior is undefined.
5564 **
5565 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
5566 ** ^(If the default VFS is unregistered, another VFS is chosen as
5567 ** the default.  The choice for the new VFS is arbitrary.)^
5568 */
5569 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
5570 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
5571 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
5572
5573 /*
5574 ** CAPI3REF: Mutexes
5575 **
5576 ** The SQLite core uses these routines for thread
5577 ** synchronization. Though they are intended for internal
5578 ** use by SQLite, code that links against SQLite is
5579 ** permitted to use any of these routines.
5580 **
5581 ** The SQLite source code contains multiple implementations
5582 ** of these mutex routines.  An appropriate implementation
5583 ** is selected automatically at compile-time.  ^(The following
5584 ** implementations are available in the SQLite core:
5585 **
5586 ** <ul>
5587 ** <li>   SQLITE_MUTEX_OS2
5588 ** <li>   SQLITE_MUTEX_PTHREAD
5589 ** <li>   SQLITE_MUTEX_W32
5590 ** <li>   SQLITE_MUTEX_NOOP
5591 ** </ul>)^
5592 **
5593 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
5594 ** that does no real locking and is appropriate for use in
5595 ** a single-threaded application.  ^The SQLITE_MUTEX_OS2,
5596 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
5597 ** are appropriate for use on OS/2, Unix, and Windows.
5598 **
5599 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
5600 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
5601 ** implementation is included with the library. In this case the
5602 ** application must supply a custom mutex implementation using the
5603 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
5604 ** before calling sqlite3_initialize() or any other public sqlite3_
5605 ** function that calls sqlite3_initialize().)^
5606 **
5607 ** ^The sqlite3_mutex_alloc() routine allocates a new
5608 ** mutex and returns a pointer to it. ^If it returns NULL
5609 ** that means that a mutex could not be allocated.  ^SQLite
5610 ** will unwind its stack and return an error.  ^(The argument
5611 ** to sqlite3_mutex_alloc() is one of these integer constants:
5612 **
5613 ** <ul>
5614 ** <li>  SQLITE_MUTEX_FAST
5615 ** <li>  SQLITE_MUTEX_RECURSIVE
5616 ** <li>  SQLITE_MUTEX_STATIC_MASTER
5617 ** <li>  SQLITE_MUTEX_STATIC_MEM
5618 ** <li>  SQLITE_MUTEX_STATIC_MEM2
5619 ** <li>  SQLITE_MUTEX_STATIC_PRNG
5620 ** <li>  SQLITE_MUTEX_STATIC_LRU
5621 ** <li>  SQLITE_MUTEX_STATIC_LRU2
5622 ** </ul>)^
5623 **
5624 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
5625 ** cause sqlite3_mutex_alloc() to create
5626 ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
5627 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
5628 ** The mutex implementation does not need to make a distinction
5629 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
5630 ** not want to.  ^SQLite will only request a recursive mutex in
5631 ** cases where it really needs one.  ^If a faster non-recursive mutex
5632 ** implementation is available on the host platform, the mutex subsystem
5633 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
5634 **
5635 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
5636 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
5637 ** a pointer to a static preexisting mutex.  ^Six static mutexes are
5638 ** used by the current version of SQLite.  Future versions of SQLite
5639 ** may add additional static mutexes.  Static mutexes are for internal
5640 ** use by SQLite only.  Applications that use SQLite mutexes should
5641 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
5642 ** SQLITE_MUTEX_RECURSIVE.
5643 **
5644 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
5645 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
5646 ** returns a different mutex on every call.  ^But for the static
5647 ** mutex types, the same mutex is returned on every call that has
5648 ** the same type number.
5649 **
5650 ** ^The sqlite3_mutex_free() routine deallocates a previously
5651 ** allocated dynamic mutex.  ^SQLite is careful to deallocate every
5652 ** dynamic mutex that it allocates.  The dynamic mutexes must not be in
5653 ** use when they are deallocated.  Attempting to deallocate a static
5654 ** mutex results in undefined behavior.  ^SQLite never deallocates
5655 ** a static mutex.
5656 **
5657 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
5658 ** to enter a mutex.  ^If another thread is already within the mutex,
5659 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
5660 ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
5661 ** upon successful entry.  ^(Mutexes created using
5662 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
5663 ** In such cases the,
5664 ** mutex must be exited an equal number of times before another thread
5665 ** can enter.)^  ^(If the same thread tries to enter any other
5666 ** kind of mutex more than once, the behavior is undefined.
5667 ** SQLite will never exhibit
5668 ** such behavior in its own use of mutexes.)^
5669 **
5670 ** ^(Some systems (for example, Windows 95) do not support the operation
5671 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
5672 ** will always return SQLITE_BUSY.  The SQLite core only ever uses
5673 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
5674 **
5675 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
5676 ** previously entered by the same thread.   ^(The behavior
5677 ** is undefined if the mutex is not currently entered by the
5678 ** calling thread or is not currently allocated.  SQLite will
5679 ** never do either.)^
5680 **
5681 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
5682 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
5683 ** behave as no-ops.
5684 **
5685 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
5686 */
5687 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
5688 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
5689 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
5690 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
5691 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
5692
5693 /*
5694 ** CAPI3REF: Mutex Methods Object
5695 **
5696 ** An instance of this structure defines the low-level routines
5697 ** used to allocate and use mutexes.
5698 **
5699 ** Usually, the default mutex implementations provided by SQLite are
5700 ** sufficient, however the user has the option of substituting a custom
5701 ** implementation for specialized deployments or systems for which SQLite
5702 ** does not provide a suitable implementation. In this case, the user
5703 ** creates and populates an instance of this structure to pass
5704 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
5705 ** Additionally, an instance of this structure can be used as an
5706 ** output variable when querying the system for the current mutex
5707 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
5708 **
5709 ** ^The xMutexInit method defined by this structure is invoked as
5710 ** part of system initialization by the sqlite3_initialize() function.
5711 ** ^The xMutexInit routine is called by SQLite exactly once for each
5712 ** effective call to [sqlite3_initialize()].
5713 **
5714 ** ^The xMutexEnd method defined by this structure is invoked as
5715 ** part of system shutdown by the sqlite3_shutdown() function. The
5716 ** implementation of this method is expected to release all outstanding
5717 ** resources obtained by the mutex methods implementation, especially
5718 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
5719 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
5720 **
5721 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
5722 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
5723 ** xMutexNotheld) implement the following interfaces (respectively):
5724 **
5725 ** <ul>
5726 **   <li>  [sqlite3_mutex_alloc()] </li>
5727 **   <li>  [sqlite3_mutex_free()] </li>
5728 **   <li>  [sqlite3_mutex_enter()] </li>
5729 **   <li>  [sqlite3_mutex_try()] </li>
5730 **   <li>  [sqlite3_mutex_leave()] </li>
5731 **   <li>  [sqlite3_mutex_held()] </li>
5732 **   <li>  [sqlite3_mutex_notheld()] </li>
5733 ** </ul>)^
5734 **
5735 ** The only difference is that the public sqlite3_XXX functions enumerated
5736 ** above silently ignore any invocations that pass a NULL pointer instead
5737 ** of a valid mutex handle. The implementations of the methods defined
5738 ** by this structure are not required to handle this case, the results
5739 ** of passing a NULL pointer instead of a valid mutex handle are undefined
5740 ** (i.e. it is acceptable to provide an implementation that segfaults if
5741 ** it is passed a NULL pointer).
5742 **
5743 ** The xMutexInit() method must be threadsafe.  ^It must be harmless to
5744 ** invoke xMutexInit() multiple times within the same process and without
5745 ** intervening calls to xMutexEnd().  Second and subsequent calls to
5746 ** xMutexInit() must be no-ops.
5747 **
5748 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
5749 ** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
5750 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
5751 ** memory allocation for a fast or recursive mutex.
5752 **
5753 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
5754 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
5755 ** If xMutexInit fails in any way, it is expected to clean up after itself
5756 ** prior to returning.
5757 */
5758 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
5759 struct sqlite3_mutex_methods {
5760   int (*xMutexInit)(void);
5761   int (*xMutexEnd)(void);
5762   sqlite3_mutex *(*xMutexAlloc)(int);
5763   void (*xMutexFree)(sqlite3_mutex *);
5764   void (*xMutexEnter)(sqlite3_mutex *);
5765   int (*xMutexTry)(sqlite3_mutex *);
5766   void (*xMutexLeave)(sqlite3_mutex *);
5767   int (*xMutexHeld)(sqlite3_mutex *);
5768   int (*xMutexNotheld)(sqlite3_mutex *);
5769 };
5770
5771 /*
5772 ** CAPI3REF: Mutex Verification Routines
5773 **
5774 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
5775 ** are intended for use inside assert() statements.  ^The SQLite core
5776 ** never uses these routines except inside an assert() and applications
5777 ** are advised to follow the lead of the core.  ^The SQLite core only
5778 ** provides implementations for these routines when it is compiled
5779 ** with the SQLITE_DEBUG flag.  ^External mutex implementations
5780 ** are only required to provide these routines if SQLITE_DEBUG is
5781 ** defined and if NDEBUG is not defined.
5782 **
5783 ** ^These routines should return true if the mutex in their argument
5784 ** is held or not held, respectively, by the calling thread.
5785 **
5786 ** ^The implementation is not required to provided versions of these
5787 ** routines that actually work. If the implementation does not provide working
5788 ** versions of these routines, it should at least provide stubs that always
5789 ** return true so that one does not get spurious assertion failures.
5790 **
5791 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
5792 ** the routine should return 1.   This seems counter-intuitive since
5793 ** clearly the mutex cannot be held if it does not exist.  But the
5794 ** the reason the mutex does not exist is because the build is not
5795 ** using mutexes.  And we do not want the assert() containing the
5796 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
5797 ** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
5798 ** interface should also return 1 when given a NULL pointer.
5799 */
5800 #ifndef NDEBUG
5801 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
5802 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
5803 #endif
5804
5805 /*
5806 ** CAPI3REF: Mutex Types
5807 **
5808 ** The [sqlite3_mutex_alloc()] interface takes a single argument
5809 ** which is one of these integer constants.
5810 **
5811 ** The set of static mutexes may change from one SQLite release to the
5812 ** next.  Applications that override the built-in mutex logic must be
5813 ** prepared to accommodate additional static mutexes.
5814 */
5815 #define SQLITE_MUTEX_FAST             0
5816 #define SQLITE_MUTEX_RECURSIVE        1
5817 #define SQLITE_MUTEX_STATIC_MASTER    2
5818 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
5819 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
5820 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
5821 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
5822 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
5823 #define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
5824 #define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
5825
5826 /*
5827 ** CAPI3REF: Retrieve the mutex for a database connection
5828 **
5829 ** ^This interface returns a pointer the [sqlite3_mutex] object that 
5830 ** serializes access to the [database connection] given in the argument
5831 ** when the [threading mode] is Serialized.
5832 ** ^If the [threading mode] is Single-thread or Multi-thread then this
5833 ** routine returns a NULL pointer.
5834 */
5835 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
5836
5837 /*
5838 ** CAPI3REF: Low-Level Control Of Database Files
5839 **
5840 ** ^The [sqlite3_file_control()] interface makes a direct call to the
5841 ** xFileControl method for the [sqlite3_io_methods] object associated
5842 ** with a particular database identified by the second argument. ^The
5843 ** name of the database is "main" for the main database or "temp" for the
5844 ** TEMP database, or the name that appears after the AS keyword for
5845 ** databases that are added using the [ATTACH] SQL command.
5846 ** ^A NULL pointer can be used in place of "main" to refer to the
5847 ** main database file.
5848 ** ^The third and fourth parameters to this routine
5849 ** are passed directly through to the second and third parameters of
5850 ** the xFileControl method.  ^The return value of the xFileControl
5851 ** method becomes the return value of this routine.
5852 **
5853 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
5854 ** a pointer to the underlying [sqlite3_file] object to be written into
5855 ** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
5856 ** case is a short-circuit path which does not actually invoke the
5857 ** underlying sqlite3_io_methods.xFileControl method.
5858 **
5859 ** ^If the second parameter (zDbName) does not match the name of any
5860 ** open database file, then SQLITE_ERROR is returned.  ^This error
5861 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
5862 ** or [sqlite3_errmsg()].  The underlying xFileControl method might
5863 ** also return SQLITE_ERROR.  There is no way to distinguish between
5864 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
5865 ** xFileControl method.
5866 **
5867 ** See also: [SQLITE_FCNTL_LOCKSTATE]
5868 */
5869 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
5870
5871 /*
5872 ** CAPI3REF: Testing Interface
5873 **
5874 ** ^The sqlite3_test_control() interface is used to read out internal
5875 ** state of SQLite and to inject faults into SQLite for testing
5876 ** purposes.  ^The first parameter is an operation code that determines
5877 ** the number, meaning, and operation of all subsequent parameters.
5878 **
5879 ** This interface is not for use by applications.  It exists solely
5880 ** for verifying the correct operation of the SQLite library.  Depending
5881 ** on how the SQLite library is compiled, this interface might not exist.
5882 **
5883 ** The details of the operation codes, their meanings, the parameters
5884 ** they take, and what they do are all subject to change without notice.
5885 ** Unlike most of the SQLite API, this function is not guaranteed to
5886 ** operate consistently from one release to the next.
5887 */
5888 SQLITE_API int sqlite3_test_control(int op, ...);
5889
5890 /*
5891 ** CAPI3REF: Testing Interface Operation Codes
5892 **
5893 ** These constants are the valid operation code parameters used
5894 ** as the first argument to [sqlite3_test_control()].
5895 **
5896 ** These parameters and their meanings are subject to change
5897 ** without notice.  These values are for testing purposes only.
5898 ** Applications should not use any of these parameters or the
5899 ** [sqlite3_test_control()] interface.
5900 */
5901 #define SQLITE_TESTCTRL_FIRST                    5
5902 #define SQLITE_TESTCTRL_PRNG_SAVE                5
5903 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
5904 #define SQLITE_TESTCTRL_PRNG_RESET               7
5905 #define SQLITE_TESTCTRL_BITVEC_TEST              8
5906 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
5907 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
5908 #define SQLITE_TESTCTRL_PENDING_BYTE            11
5909 #define SQLITE_TESTCTRL_ASSERT                  12
5910 #define SQLITE_TESTCTRL_ALWAYS                  13
5911 #define SQLITE_TESTCTRL_RESERVE                 14
5912 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
5913 #define SQLITE_TESTCTRL_ISKEYWORD               16
5914 #define SQLITE_TESTCTRL_PGHDRSZ                 17
5915 #define SQLITE_TESTCTRL_SCRATCHMALLOC           18
5916 #define SQLITE_TESTCTRL_LAST                    18
5917
5918 /*
5919 ** CAPI3REF: SQLite Runtime Status
5920 **
5921 ** ^This interface is used to retrieve runtime status information
5922 ** about the performance of SQLite, and optionally to reset various
5923 ** highwater marks.  ^The first argument is an integer code for
5924 ** the specific parameter to measure.  ^(Recognized integer codes
5925 ** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].)^
5926 ** ^The current value of the parameter is returned into *pCurrent.
5927 ** ^The highest recorded value is returned in *pHighwater.  ^If the
5928 ** resetFlag is true, then the highest record value is reset after
5929 ** *pHighwater is written.  ^(Some parameters do not record the highest
5930 ** value.  For those parameters
5931 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
5932 ** ^(Other parameters record only the highwater mark and not the current
5933 ** value.  For these latter parameters nothing is written into *pCurrent.)^
5934 **
5935 ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
5936 ** non-zero [error code] on failure.
5937 **
5938 ** This routine is threadsafe but is not atomic.  This routine can be
5939 ** called while other threads are running the same or different SQLite
5940 ** interfaces.  However the values returned in *pCurrent and
5941 ** *pHighwater reflect the status of SQLite at different points in time
5942 ** and it is possible that another thread might change the parameter
5943 ** in between the times when *pCurrent and *pHighwater are written.
5944 **
5945 ** See also: [sqlite3_db_status()]
5946 */
5947 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
5948
5949
5950 /*
5951 ** CAPI3REF: Status Parameters
5952 **
5953 ** These integer constants designate various run-time status parameters
5954 ** that can be returned by [sqlite3_status()].
5955 **
5956 ** <dl>
5957 ** ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
5958 ** <dd>This parameter is the current amount of memory checked out
5959 ** using [sqlite3_malloc()], either directly or indirectly.  The
5960 ** figure includes calls made to [sqlite3_malloc()] by the application
5961 ** and internal memory usage by the SQLite library.  Scratch memory
5962 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
5963 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
5964 ** this parameter.  The amount returned is the sum of the allocation
5965 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
5966 **
5967 ** ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
5968 ** <dd>This parameter records the largest memory allocation request
5969 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
5970 ** internal equivalents).  Only the value returned in the
5971 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
5972 ** The value written into the *pCurrent parameter is undefined.</dd>)^
5973 **
5974 ** ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
5975 ** <dd>This parameter records the number of separate memory allocations
5976 ** currently checked out.</dd>)^
5977 **
5978 ** ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
5979 ** <dd>This parameter returns the number of pages used out of the
5980 ** [pagecache memory allocator] that was configured using 
5981 ** [SQLITE_CONFIG_PAGECACHE].  The
5982 ** value returned is in pages, not in bytes.</dd>)^
5983 **
5984 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
5985 ** <dd>This parameter returns the number of bytes of page cache
5986 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
5987 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
5988 ** returned value includes allocations that overflowed because they
5989 ** where too large (they were larger than the "sz" parameter to
5990 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
5991 ** no space was left in the page cache.</dd>)^
5992 **
5993 ** ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
5994 ** <dd>This parameter records the largest memory allocation request
5995 ** handed to [pagecache memory allocator].  Only the value returned in the
5996 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
5997 ** The value written into the *pCurrent parameter is undefined.</dd>)^
5998 **
5999 ** ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
6000 ** <dd>This parameter returns the number of allocations used out of the
6001 ** [scratch memory allocator] configured using
6002 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
6003 ** in bytes.  Since a single thread may only have one scratch allocation
6004 ** outstanding at time, this parameter also reports the number of threads
6005 ** using scratch memory at the same time.</dd>)^
6006 **
6007 ** ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6008 ** <dd>This parameter returns the number of bytes of scratch memory
6009 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
6010 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
6011 ** returned include overflows because the requested allocation was too
6012 ** larger (that is, because the requested allocation was larger than the
6013 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6014 ** slots were available.
6015 ** </dd>)^
6016 **
6017 ** ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6018 ** <dd>This parameter records the largest memory allocation request
6019 ** handed to [scratch memory allocator].  Only the value returned in the
6020 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6021 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6022 **
6023 ** ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
6024 ** <dd>This parameter records the deepest parser stack.  It is only
6025 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6026 ** </dl>
6027 **
6028 ** New status parameters may be added from time to time.
6029 */
6030 #define SQLITE_STATUS_MEMORY_USED          0
6031 #define SQLITE_STATUS_PAGECACHE_USED       1
6032 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
6033 #define SQLITE_STATUS_SCRATCH_USED         3
6034 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
6035 #define SQLITE_STATUS_MALLOC_SIZE          5
6036 #define SQLITE_STATUS_PARSER_STACK         6
6037 #define SQLITE_STATUS_PAGECACHE_SIZE       7
6038 #define SQLITE_STATUS_SCRATCH_SIZE         8
6039 #define SQLITE_STATUS_MALLOC_COUNT         9
6040
6041 /*
6042 ** CAPI3REF: Database Connection Status
6043 **
6044 ** ^This interface is used to retrieve runtime status information 
6045 ** about a single [database connection].  ^The first argument is the
6046 ** database connection object to be interrogated.  ^The second argument
6047 ** is an integer constant, taken from the set of
6048 ** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros, that
6049 ** determines the parameter to interrogate.  The set of 
6050 ** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros is likely
6051 ** to grow in future releases of SQLite.
6052 **
6053 ** ^The current value of the requested parameter is written into *pCur
6054 ** and the highest instantaneous value is written into *pHiwtr.  ^If
6055 ** the resetFlg is true, then the highest instantaneous value is
6056 ** reset back down to the current value.
6057 **
6058 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6059 ** non-zero [error code] on failure.
6060 **
6061 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6062 */
6063 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6064
6065 /*
6066 ** CAPI3REF: Status Parameters for database connections
6067 **
6068 ** These constants are the available integer "verbs" that can be passed as
6069 ** the second argument to the [sqlite3_db_status()] interface.
6070 **
6071 ** New verbs may be added in future releases of SQLite. Existing verbs
6072 ** might be discontinued. Applications should check the return code from
6073 ** [sqlite3_db_status()] to make sure that the call worked.
6074 ** The [sqlite3_db_status()] interface will return a non-zero error code
6075 ** if a discontinued or unsupported verb is invoked.
6076 **
6077 ** <dl>
6078 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6079 ** <dd>This parameter returns the number of lookaside memory slots currently
6080 ** checked out.</dd>)^
6081 **
6082 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
6083 ** <dd>This parameter returns the number malloc attempts that were 
6084 ** satisfied using lookaside memory. Only the high-water value is meaningful;
6085 ** the current value is always zero.
6086 ** checked out.</dd>)^
6087 **
6088 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6089 ** <dd>This parameter returns the number malloc attempts that might have
6090 ** been satisfied using lookaside memory but failed due to the amount of
6091 ** memory requested being larger than the lookaside slot size.
6092 ** Only the high-water value is meaningful;
6093 ** the current value is always zero.
6094 ** checked out.</dd>)^
6095 **
6096 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6097 ** <dd>This parameter returns the number malloc attempts that might have
6098 ** been satisfied using lookaside memory but failed due to all lookaside
6099 ** memory already being in use.
6100 ** Only the high-water value is meaningful;
6101 ** the current value is always zero.
6102 ** checked out.</dd>)^
6103 **
6104 ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
6105 ** <dd>This parameter returns the approximate number of of bytes of heap
6106 ** memory used by all pager caches associated with the database connection.)^
6107 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
6108 **
6109 ** ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
6110 ** <dd>This parameter returns the approximate number of of bytes of heap
6111 ** memory used to store the schema for all databases associated
6112 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^ 
6113 ** ^The full amount of memory used by the schemas is reported, even if the
6114 ** schema memory is shared with other database connections due to
6115 ** [shared cache mode] being enabled.
6116 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
6117 **
6118 ** ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
6119 ** <dd>This parameter returns the approximate number of of bytes of heap
6120 ** and lookaside memory used by all prepared statements associated with
6121 ** the database connection.)^
6122 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
6123 ** </dd>
6124 ** </dl>
6125 */
6126 #define SQLITE_DBSTATUS_LOOKASIDE_USED       0
6127 #define SQLITE_DBSTATUS_CACHE_USED           1
6128 #define SQLITE_DBSTATUS_SCHEMA_USED          2
6129 #define SQLITE_DBSTATUS_STMT_USED            3
6130 #define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
6131 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
6132 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
6133 #define SQLITE_DBSTATUS_MAX                  6   /* Largest defined DBSTATUS */
6134
6135
6136 /*
6137 ** CAPI3REF: Prepared Statement Status
6138 **
6139 ** ^(Each prepared statement maintains various
6140 ** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
6141 ** of times it has performed specific operations.)^  These counters can
6142 ** be used to monitor the performance characteristics of the prepared
6143 ** statements.  For example, if the number of table steps greatly exceeds
6144 ** the number of table searches or result rows, that would tend to indicate
6145 ** that the prepared statement is using a full table scan rather than
6146 ** an index.  
6147 **
6148 ** ^(This interface is used to retrieve and reset counter values from
6149 ** a [prepared statement].  The first argument is the prepared statement
6150 ** object to be interrogated.  The second argument
6151 ** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter]
6152 ** to be interrogated.)^
6153 ** ^The current value of the requested counter is returned.
6154 ** ^If the resetFlg is true, then the counter is reset to zero after this
6155 ** interface call returns.
6156 **
6157 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
6158 */
6159 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6160
6161 /*
6162 ** CAPI3REF: Status Parameters for prepared statements
6163 **
6164 ** These preprocessor macros define integer codes that name counter
6165 ** values associated with the [sqlite3_stmt_status()] interface.
6166 ** The meanings of the various counters are as follows:
6167 **
6168 ** <dl>
6169 ** <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6170 ** <dd>^This is the number of times that SQLite has stepped forward in
6171 ** a table as part of a full table scan.  Large numbers for this counter
6172 ** may indicate opportunities for performance improvement through 
6173 ** careful use of indices.</dd>
6174 **
6175 ** <dt>SQLITE_STMTSTATUS_SORT</dt>
6176 ** <dd>^This is the number of sort operations that have occurred.
6177 ** A non-zero value in this counter may indicate an opportunity to
6178 ** improvement performance through careful use of indices.</dd>
6179 **
6180 ** <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
6181 ** <dd>^This is the number of rows inserted into transient indices that
6182 ** were created automatically in order to help joins run faster.
6183 ** A non-zero value in this counter may indicate an opportunity to
6184 ** improvement performance by adding permanent indices that do not
6185 ** need to be reinitialized each time the statement is run.</dd>
6186 **
6187 ** </dl>
6188 */
6189 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
6190 #define SQLITE_STMTSTATUS_SORT              2
6191 #define SQLITE_STMTSTATUS_AUTOINDEX         3
6192
6193 /*
6194 ** CAPI3REF: Custom Page Cache Object
6195 **
6196 ** The sqlite3_pcache type is opaque.  It is implemented by
6197 ** the pluggable module.  The SQLite core has no knowledge of
6198 ** its size or internal structure and never deals with the
6199 ** sqlite3_pcache object except by holding and passing pointers
6200 ** to the object.
6201 **
6202 ** See [sqlite3_pcache_methods] for additional information.
6203 */
6204 typedef struct sqlite3_pcache sqlite3_pcache;
6205
6206 /*
6207 ** CAPI3REF: Application Defined Page Cache.
6208 ** KEYWORDS: {page cache}
6209 **
6210 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
6211 ** register an alternative page cache implementation by passing in an 
6212 ** instance of the sqlite3_pcache_methods structure.)^
6213 ** In many applications, most of the heap memory allocated by 
6214 ** SQLite is used for the page cache.
6215 ** By implementing a 
6216 ** custom page cache using this API, an application can better control
6217 ** the amount of memory consumed by SQLite, the way in which 
6218 ** that memory is allocated and released, and the policies used to 
6219 ** determine exactly which parts of a database file are cached and for 
6220 ** how long.
6221 **
6222 ** The alternative page cache mechanism is an
6223 ** extreme measure that is only needed by the most demanding applications.
6224 ** The built-in page cache is recommended for most uses.
6225 **
6226 ** ^(The contents of the sqlite3_pcache_methods structure are copied to an
6227 ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
6228 ** the application may discard the parameter after the call to
6229 ** [sqlite3_config()] returns.)^
6230 **
6231 ** ^(The xInit() method is called once for each effective 
6232 ** call to [sqlite3_initialize()])^
6233 ** (usually only once during the lifetime of the process). ^(The xInit()
6234 ** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
6235 ** The intent of the xInit() method is to set up global data structures 
6236 ** required by the custom page cache implementation. 
6237 ** ^(If the xInit() method is NULL, then the 
6238 ** built-in default page cache is used instead of the application defined
6239 ** page cache.)^
6240 **
6241 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
6242 ** It can be used to clean up 
6243 ** any outstanding resources before process shutdown, if required.
6244 ** ^The xShutdown() method may be NULL.
6245 **
6246 ** ^SQLite automatically serializes calls to the xInit method,
6247 ** so the xInit method need not be threadsafe.  ^The
6248 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
6249 ** not need to be threadsafe either.  All other methods must be threadsafe
6250 ** in multithreaded applications.
6251 **
6252 ** ^SQLite will never invoke xInit() more than once without an intervening
6253 ** call to xShutdown().
6254 **
6255 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
6256 ** SQLite will typically create one cache instance for each open database file,
6257 ** though this is not guaranteed. ^The
6258 ** first parameter, szPage, is the size in bytes of the pages that must
6259 ** be allocated by the cache.  ^szPage will not be a power of two.  ^szPage
6260 ** will the page size of the database file that is to be cached plus an
6261 ** increment (here called "R") of less than 250.  SQLite will use the
6262 ** extra R bytes on each page to store metadata about the underlying
6263 ** database page on disk.  The value of R depends
6264 ** on the SQLite version, the target platform, and how SQLite was compiled.
6265 ** ^(R is constant for a particular build of SQLite. Except, there are two
6266 ** distinct values of R when SQLite is compiled with the proprietary
6267 ** ZIPVFS extension.)^  ^The second argument to
6268 ** xCreate(), bPurgeable, is true if the cache being created will
6269 ** be used to cache database pages of a file stored on disk, or
6270 ** false if it is used for an in-memory database. The cache implementation
6271 ** does not have to do anything special based with the value of bPurgeable;
6272 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
6273 ** never invoke xUnpin() except to deliberately delete a page.
6274 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6275 ** false will always have the "discard" flag set to true.  
6276 ** ^Hence, a cache created with bPurgeable false will
6277 ** never contain any unpinned pages.
6278 **
6279 ** ^(The xCachesize() method may be called at any time by SQLite to set the
6280 ** suggested maximum cache-size (number of pages stored by) the cache
6281 ** instance passed as the first argument. This is the value configured using
6282 ** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
6283 ** parameter, the implementation is not required to do anything with this
6284 ** value; it is advisory only.
6285 **
6286 ** The xPagecount() method must return the number of pages currently
6287 ** stored in the cache, both pinned and unpinned.
6288 ** 
6289 ** The xFetch() method locates a page in the cache and returns a pointer to 
6290 ** the page, or a NULL pointer.
6291 ** A "page", in this context, means a buffer of szPage bytes aligned at an
6292 ** 8-byte boundary. The page to be fetched is determined by the key. ^The
6293 ** mimimum key value is 1.  After it has been retrieved using xFetch, the page 
6294 ** is considered to be "pinned".
6295 **
6296 ** If the requested page is already in the page cache, then the page cache
6297 ** implementation must return a pointer to the page buffer with its content
6298 ** intact.  If the requested page is not already in the cache, then the
6299 ** cache implementation should use the value of the createFlag
6300 ** parameter to help it determined what action to take:
6301 **
6302 ** <table border=1 width=85% align=center>
6303 ** <tr><th> createFlag <th> Behaviour when page is not already in cache
6304 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
6305 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
6306 **                 Otherwise return NULL.
6307 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
6308 **                 NULL if allocating a new page is effectively impossible.
6309 ** </table>
6310 **
6311 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
6312 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
6313 ** failed.)^  In between the to xFetch() calls, SQLite may
6314 ** attempt to unpin one or more cache pages by spilling the content of
6315 ** pinned pages to disk and synching the operating system disk cache.
6316 **
6317 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6318 ** as its second argument.  If the third parameter, discard, is non-zero,
6319 ** then the page must be evicted from the cache.
6320 ** ^If the discard parameter is
6321 ** zero, then the page may be discarded or retained at the discretion of
6322 ** page cache implementation. ^The page cache implementation
6323 ** may choose to evict unpinned pages at any time.
6324 **
6325 ** The cache must not perform any reference counting. A single 
6326 ** call to xUnpin() unpins the page regardless of the number of prior calls 
6327 ** to xFetch().
6328 **
6329 ** The xRekey() method is used to change the key value associated with the
6330 ** page passed as the second argument. If the cache
6331 ** previously contains an entry associated with newKey, it must be
6332 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
6333 ** to be pinned.
6334 **
6335 ** When SQLite calls the xTruncate() method, the cache must discard all
6336 ** existing cache entries with page numbers (keys) greater than or equal
6337 ** to the value of the iLimit parameter passed to xTruncate(). If any
6338 ** of these pages are pinned, they are implicitly unpinned, meaning that
6339 ** they can be safely discarded.
6340 **
6341 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
6342 ** All resources associated with the specified cache should be freed. ^After
6343 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
6344 ** handle invalid, and will not use it with any other sqlite3_pcache_methods
6345 ** functions.
6346 */
6347 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
6348 struct sqlite3_pcache_methods {
6349   void *pArg;
6350   int (*xInit)(void*);
6351   void (*xShutdown)(void*);
6352   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
6353   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6354   int (*xPagecount)(sqlite3_pcache*);
6355   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
6356   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
6357   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
6358   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
6359   void (*xDestroy)(sqlite3_pcache*);
6360 };
6361
6362 /*
6363 ** CAPI3REF: Online Backup Object
6364 **
6365 ** The sqlite3_backup object records state information about an ongoing
6366 ** online backup operation.  ^The sqlite3_backup object is created by
6367 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
6368 ** [sqlite3_backup_finish()].
6369 **
6370 ** See Also: [Using the SQLite Online Backup API]
6371 */
6372 typedef struct sqlite3_backup sqlite3_backup;
6373
6374 /*
6375 ** CAPI3REF: Online Backup API.
6376 **
6377 ** The backup API copies the content of one database into another.
6378 ** It is useful either for creating backups of databases or
6379 ** for copying in-memory databases to or from persistent files. 
6380 **
6381 ** See Also: [Using the SQLite Online Backup API]
6382 **
6383 ** ^SQLite holds a write transaction open on the destination database file
6384 ** for the duration of the backup operation.
6385 ** ^The source database is read-locked only while it is being read;
6386 ** it is not locked continuously for the entire backup operation.
6387 ** ^Thus, the backup may be performed on a live source database without
6388 ** preventing other database connections from
6389 ** reading or writing to the source database while the backup is underway.
6390 ** 
6391 ** ^(To perform a backup operation: 
6392 **   <ol>
6393 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
6394 **         backup, 
6395 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer 
6396 **         the data between the two databases, and finally
6397 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources 
6398 **         associated with the backup operation. 
6399 **   </ol>)^
6400 ** There should be exactly one call to sqlite3_backup_finish() for each
6401 ** successful call to sqlite3_backup_init().
6402 **
6403 ** <b>sqlite3_backup_init()</b>
6404 **
6405 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the 
6406 ** [database connection] associated with the destination database 
6407 ** and the database name, respectively.
6408 ** ^The database name is "main" for the main database, "temp" for the
6409 ** temporary database, or the name specified after the AS keyword in
6410 ** an [ATTACH] statement for an attached database.
6411 ** ^The S and M arguments passed to 
6412 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
6413 ** and database name of the source database, respectively.
6414 ** ^The source and destination [database connections] (parameters S and D)
6415 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
6416 ** an error.
6417 **
6418 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
6419 ** returned and an error code and error message are stored in the
6420 ** destination [database connection] D.
6421 ** ^The error code and message for the failed call to sqlite3_backup_init()
6422 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
6423 ** [sqlite3_errmsg16()] functions.
6424 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
6425 ** [sqlite3_backup] object.
6426 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
6427 ** sqlite3_backup_finish() functions to perform the specified backup 
6428 ** operation.
6429 **
6430 ** <b>sqlite3_backup_step()</b>
6431 **
6432 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between 
6433 ** the source and destination databases specified by [sqlite3_backup] object B.
6434 ** ^If N is negative, all remaining source pages are copied. 
6435 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
6436 ** are still more pages to be copied, then the function returns [SQLITE_OK].
6437 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
6438 ** from source to destination, then it returns [SQLITE_DONE].
6439 ** ^If an error occurs while running sqlite3_backup_step(B,N),
6440 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
6441 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
6442 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
6443 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
6444 **
6445 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
6446 ** <ol>
6447 ** <li> the destination database was opened read-only, or
6448 ** <li> the destination database is using write-ahead-log journaling
6449 ** and the destination and source page sizes differ, or
6450 ** <li> the destination database is an in-memory database and the
6451 ** destination and source page sizes differ.
6452 ** </ol>)^
6453 **
6454 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
6455 ** the [sqlite3_busy_handler | busy-handler function]
6456 ** is invoked (if one is specified). ^If the 
6457 ** busy-handler returns non-zero before the lock is available, then 
6458 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
6459 ** sqlite3_backup_step() can be retried later. ^If the source
6460 ** [database connection]
6461 ** is being used to write to the source database when sqlite3_backup_step()
6462 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
6463 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
6464 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
6465 ** [SQLITE_READONLY] is returned, then 
6466 ** there is no point in retrying the call to sqlite3_backup_step(). These 
6467 ** errors are considered fatal.)^  The application must accept 
6468 ** that the backup operation has failed and pass the backup operation handle 
6469 ** to the sqlite3_backup_finish() to release associated resources.
6470 **
6471 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
6472 ** on the destination file. ^The exclusive lock is not released until either 
6473 ** sqlite3_backup_finish() is called or the backup operation is complete 
6474 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
6475 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
6476 ** lasts for the duration of the sqlite3_backup_step() call.
6477 ** ^Because the source database is not locked between calls to
6478 ** sqlite3_backup_step(), the source database may be modified mid-way
6479 ** through the backup process.  ^If the source database is modified by an
6480 ** external process or via a database connection other than the one being
6481 ** used by the backup operation, then the backup will be automatically
6482 ** restarted by the next call to sqlite3_backup_step(). ^If the source 
6483 ** database is modified by the using the same database connection as is used
6484 ** by the backup operation, then the backup database is automatically
6485 ** updated at the same time.
6486 **
6487 ** <b>sqlite3_backup_finish()</b>
6488 **
6489 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the 
6490 ** application wishes to abandon the backup operation, the application
6491 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
6492 ** ^The sqlite3_backup_finish() interfaces releases all
6493 ** resources associated with the [sqlite3_backup] object. 
6494 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
6495 ** active write-transaction on the destination database is rolled back.
6496 ** The [sqlite3_backup] object is invalid
6497 ** and may not be used following a call to sqlite3_backup_finish().
6498 **
6499 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
6500 ** sqlite3_backup_step() errors occurred, regardless or whether or not
6501 ** sqlite3_backup_step() completed.
6502 ** ^If an out-of-memory condition or IO error occurred during any prior
6503 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
6504 ** sqlite3_backup_finish() returns the corresponding [error code].
6505 **
6506 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
6507 ** is not a permanent error and does not affect the return value of
6508 ** sqlite3_backup_finish().
6509 **
6510 ** <b>sqlite3_backup_remaining(), sqlite3_backup_pagecount()</b>
6511 **
6512 ** ^Each call to sqlite3_backup_step() sets two values inside
6513 ** the [sqlite3_backup] object: the number of pages still to be backed
6514 ** up and the total number of pages in the source database file.
6515 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
6516 ** retrieve these two values, respectively.
6517 **
6518 ** ^The values returned by these functions are only updated by
6519 ** sqlite3_backup_step(). ^If the source database is modified during a backup
6520 ** operation, then the values are not updated to account for any extra
6521 ** pages that need to be updated or the size of the source database file
6522 ** changing.
6523 **
6524 ** <b>Concurrent Usage of Database Handles</b>
6525 **
6526 ** ^The source [database connection] may be used by the application for other
6527 ** purposes while a backup operation is underway or being initialized.
6528 ** ^If SQLite is compiled and configured to support threadsafe database
6529 ** connections, then the source database connection may be used concurrently
6530 ** from within other threads.
6531 **
6532 ** However, the application must guarantee that the destination 
6533 ** [database connection] is not passed to any other API (by any thread) after 
6534 ** sqlite3_backup_init() is called and before the corresponding call to
6535 ** sqlite3_backup_finish().  SQLite does not currently check to see
6536 ** if the application incorrectly accesses the destination [database connection]
6537 ** and so no error code is reported, but the operations may malfunction
6538 ** nevertheless.  Use of the destination database connection while a
6539 ** backup is in progress might also also cause a mutex deadlock.
6540 **
6541 ** If running in [shared cache mode], the application must
6542 ** guarantee that the shared cache used by the destination database
6543 ** is not accessed while the backup is running. In practice this means
6544 ** that the application must guarantee that the disk file being 
6545 ** backed up to is not accessed by any connection within the process,
6546 ** not just the specific connection that was passed to sqlite3_backup_init().
6547 **
6548 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple 
6549 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
6550 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
6551 ** APIs are not strictly speaking threadsafe. If they are invoked at the
6552 ** same time as another thread is invoking sqlite3_backup_step() it is
6553 ** possible that they return invalid values.
6554 */
6555 SQLITE_API sqlite3_backup *sqlite3_backup_init(
6556   sqlite3 *pDest,                        /* Destination database handle */
6557   const char *zDestName,                 /* Destination database name */
6558   sqlite3 *pSource,                      /* Source database handle */
6559   const char *zSourceName                /* Source database name */
6560 );
6561 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
6562 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
6563 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
6564 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
6565
6566 /*
6567 ** CAPI3REF: Unlock Notification
6568 **
6569 ** ^When running in shared-cache mode, a database operation may fail with
6570 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
6571 ** individual tables within the shared-cache cannot be obtained. See
6572 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. 
6573 ** ^This API may be used to register a callback that SQLite will invoke 
6574 ** when the connection currently holding the required lock relinquishes it.
6575 ** ^This API is only available if the library was compiled with the
6576 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
6577 **
6578 ** See Also: [Using the SQLite Unlock Notification Feature].
6579 **
6580 ** ^Shared-cache locks are released when a database connection concludes
6581 ** its current transaction, either by committing it or rolling it back. 
6582 **
6583 ** ^When a connection (known as the blocked connection) fails to obtain a
6584 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
6585 ** identity of the database connection (the blocking connection) that
6586 ** has locked the required resource is stored internally. ^After an 
6587 ** application receives an SQLITE_LOCKED error, it may call the
6588 ** sqlite3_unlock_notify() method with the blocked connection handle as 
6589 ** the first argument to register for a callback that will be invoked
6590 ** when the blocking connections current transaction is concluded. ^The
6591 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
6592 ** call that concludes the blocking connections transaction.
6593 **
6594 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
6595 ** there is a chance that the blocking connection will have already
6596 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
6597 ** If this happens, then the specified callback is invoked immediately,
6598 ** from within the call to sqlite3_unlock_notify().)^
6599 **
6600 ** ^If the blocked connection is attempting to obtain a write-lock on a
6601 ** shared-cache table, and more than one other connection currently holds
6602 ** a read-lock on the same table, then SQLite arbitrarily selects one of 
6603 ** the other connections to use as the blocking connection.
6604 **
6605 ** ^(There may be at most one unlock-notify callback registered by a 
6606 ** blocked connection. If sqlite3_unlock_notify() is called when the
6607 ** blocked connection already has a registered unlock-notify callback,
6608 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
6609 ** called with a NULL pointer as its second argument, then any existing
6610 ** unlock-notify callback is canceled. ^The blocked connections 
6611 ** unlock-notify callback may also be canceled by closing the blocked
6612 ** connection using [sqlite3_close()].
6613 **
6614 ** The unlock-notify callback is not reentrant. If an application invokes
6615 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
6616 ** crash or deadlock may be the result.
6617 **
6618 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
6619 ** returns SQLITE_OK.
6620 **
6621 ** <b>Callback Invocation Details</b>
6622 **
6623 ** When an unlock-notify callback is registered, the application provides a 
6624 ** single void* pointer that is passed to the callback when it is invoked.
6625 ** However, the signature of the callback function allows SQLite to pass
6626 ** it an array of void* context pointers. The first argument passed to
6627 ** an unlock-notify callback is a pointer to an array of void* pointers,
6628 ** and the second is the number of entries in the array.
6629 **
6630 ** When a blocking connections transaction is concluded, there may be
6631 ** more than one blocked connection that has registered for an unlock-notify
6632 ** callback. ^If two or more such blocked connections have specified the
6633 ** same callback function, then instead of invoking the callback function
6634 ** multiple times, it is invoked once with the set of void* context pointers
6635 ** specified by the blocked connections bundled together into an array.
6636 ** This gives the application an opportunity to prioritize any actions 
6637 ** related to the set of unblocked database connections.
6638 **
6639 ** <b>Deadlock Detection</b>
6640 **
6641 ** Assuming that after registering for an unlock-notify callback a 
6642 ** database waits for the callback to be issued before taking any further
6643 ** action (a reasonable assumption), then using this API may cause the
6644 ** application to deadlock. For example, if connection X is waiting for
6645 ** connection Y's transaction to be concluded, and similarly connection
6646 ** Y is waiting on connection X's transaction, then neither connection
6647 ** will proceed and the system may remain deadlocked indefinitely.
6648 **
6649 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
6650 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
6651 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
6652 ** unlock-notify callback is registered. The system is said to be in
6653 ** a deadlocked state if connection A has registered for an unlock-notify
6654 ** callback on the conclusion of connection B's transaction, and connection
6655 ** B has itself registered for an unlock-notify callback when connection
6656 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
6657 ** the system is also considered to be deadlocked if connection B has
6658 ** registered for an unlock-notify callback on the conclusion of connection
6659 ** C's transaction, where connection C is waiting on connection A. ^Any
6660 ** number of levels of indirection are allowed.
6661 **
6662 ** <b>The "DROP TABLE" Exception</b>
6663 **
6664 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost 
6665 ** always appropriate to call sqlite3_unlock_notify(). There is however,
6666 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
6667 ** SQLite checks if there are any currently executing SELECT statements
6668 ** that belong to the same connection. If there are, SQLITE_LOCKED is
6669 ** returned. In this case there is no "blocking connection", so invoking
6670 ** sqlite3_unlock_notify() results in the unlock-notify callback being
6671 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
6672 ** or "DROP INDEX" query, an infinite loop might be the result.
6673 **
6674 ** One way around this problem is to check the extended error code returned
6675 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
6676 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
6677 ** the special "DROP TABLE/INDEX" case, the extended error code is just 
6678 ** SQLITE_LOCKED.)^
6679 */
6680 SQLITE_API int sqlite3_unlock_notify(
6681   sqlite3 *pBlocked,                          /* Waiting connection */
6682   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
6683   void *pNotifyArg                            /* Argument to pass to xNotify */
6684 );
6685
6686
6687 /*
6688 ** CAPI3REF: String Comparison
6689 **
6690 ** ^The [sqlite3_strnicmp()] API allows applications and extensions to
6691 ** compare the contents of two buffers containing UTF-8 strings in a
6692 ** case-independent fashion, using the same definition of case independence 
6693 ** that SQLite uses internally when comparing identifiers.
6694 */
6695 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
6696
6697 /*
6698 ** CAPI3REF: Error Logging Interface
6699 **
6700 ** ^The [sqlite3_log()] interface writes a message into the error log
6701 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
6702 ** ^If logging is enabled, the zFormat string and subsequent arguments are
6703 ** used with [sqlite3_snprintf()] to generate the final output string.
6704 **
6705 ** The sqlite3_log() interface is intended for use by extensions such as
6706 ** virtual tables, collating functions, and SQL functions.  While there is
6707 ** nothing to prevent an application from calling sqlite3_log(), doing so
6708 ** is considered bad form.
6709 **
6710 ** The zFormat string must not be NULL.
6711 **
6712 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
6713 ** will not use dynamically allocated memory.  The log message is stored in
6714 ** a fixed-length buffer on the stack.  If the log message is longer than
6715 ** a few hundred characters, it will be truncated to the length of the
6716 ** buffer.
6717 */
6718 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
6719
6720 /*
6721 ** CAPI3REF: Write-Ahead Log Commit Hook
6722 **
6723 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
6724 ** will be invoked each time a database connection commits data to a
6725 ** [write-ahead log] (i.e. whenever a transaction is committed in
6726 ** [journal_mode | journal_mode=WAL mode]). 
6727 **
6728 ** ^The callback is invoked by SQLite after the commit has taken place and 
6729 ** the associated write-lock on the database released, so the implementation 
6730 ** may read, write or [checkpoint] the database as required.
6731 **
6732 ** ^The first parameter passed to the callback function when it is invoked
6733 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
6734 ** registering the callback. ^The second is a copy of the database handle.
6735 ** ^The third parameter is the name of the database that was written to -
6736 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
6737 ** is the number of pages currently in the write-ahead log file,
6738 ** including those that were just committed.
6739 **
6740 ** The callback function should normally return [SQLITE_OK].  ^If an error
6741 ** code is returned, that error will propagate back up through the
6742 ** SQLite code base to cause the statement that provoked the callback
6743 ** to report an error, though the commit will have still occurred. If the
6744 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
6745 ** that does not correspond to any valid SQLite error code, the results
6746 ** are undefined.
6747 **
6748 ** A single database handle may have at most a single write-ahead log callback 
6749 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
6750 ** previously registered write-ahead log callback. ^Note that the
6751 ** [sqlite3_wal_autocheckpoint()] interface and the
6752 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
6753 ** those overwrite any prior [sqlite3_wal_hook()] settings.
6754 */
6755 SQLITE_API void *sqlite3_wal_hook(
6756   sqlite3*, 
6757   int(*)(void *,sqlite3*,const char*,int),
6758   void*
6759 );
6760
6761 /*
6762 ** CAPI3REF: Configure an auto-checkpoint
6763 **
6764 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
6765 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
6766 ** to automatically [checkpoint]
6767 ** after committing a transaction if there are N or
6768 ** more frames in the [write-ahead log] file.  ^Passing zero or 
6769 ** a negative value as the nFrame parameter disables automatic
6770 ** checkpoints entirely.
6771 **
6772 ** ^The callback registered by this function replaces any existing callback
6773 ** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
6774 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
6775 ** configured by this function.
6776 **
6777 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
6778 ** from SQL.
6779 **
6780 ** ^Every new [database connection] defaults to having the auto-checkpoint
6781 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
6782 ** pages.  The use of this interface
6783 ** is only necessary if the default setting is found to be suboptimal
6784 ** for a particular application.
6785 */
6786 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
6787
6788 /*
6789 ** CAPI3REF: Checkpoint a database
6790 **
6791 ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
6792 ** on [database connection] D to be [checkpointed].  ^If X is NULL or an
6793 ** empty string, then a checkpoint is run on all databases of
6794 ** connection D.  ^If the database connection D is not in
6795 ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
6796 **
6797 ** ^The [wal_checkpoint pragma] can be used to invoke this interface
6798 ** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
6799 ** [wal_autocheckpoint pragma] can be used to cause this interface to be
6800 ** run whenever the WAL reaches a certain size threshold.
6801 */
6802 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
6803
6804 /*
6805 ** Undo the hack that converts floating point types to integer for
6806 ** builds on processors without floating point support.
6807 */
6808 #ifdef SQLITE_OMIT_FLOATING_POINT
6809 # undef double
6810 #endif
6811
6812 #if 0
6813 }  /* End of the 'extern "C"' block */
6814 #endif
6815 #endif
6816
6817 /*
6818 ** 2010 August 30
6819 **
6820 ** The author disclaims copyright to this source code.  In place of
6821 ** a legal notice, here is a blessing:
6822 **
6823 **    May you do good and not evil.
6824 **    May you find forgiveness for yourself and forgive others.
6825 **    May you share freely, never taking more than you give.
6826 **
6827 *************************************************************************
6828 */
6829
6830 #ifndef _SQLITE3RTREE_H_
6831 #define _SQLITE3RTREE_H_
6832
6833
6834 #if 0
6835 extern "C" {
6836 #endif
6837
6838 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
6839
6840 /*
6841 ** Register a geometry callback named zGeom that can be used as part of an
6842 ** R-Tree geometry query as follows:
6843 **
6844 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
6845 */
6846 SQLITE_API int sqlite3_rtree_geometry_callback(
6847   sqlite3 *db,
6848   const char *zGeom,
6849   int (*xGeom)(sqlite3_rtree_geometry *, int nCoord, double *aCoord, int *pRes),
6850   void *pContext
6851 );
6852
6853
6854 /*
6855 ** A pointer to a structure of the following type is passed as the first
6856 ** argument to callbacks registered using rtree_geometry_callback().
6857 */
6858 struct sqlite3_rtree_geometry {
6859   void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
6860   int nParam;                     /* Size of array aParam[] */
6861   double *aParam;                 /* Parameters passed to SQL geom function */
6862   void *pUser;                    /* Callback implementation user data */
6863   void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
6864 };
6865
6866
6867 #if 0
6868 }  /* end of the 'extern "C"' block */
6869 #endif
6870
6871 #endif  /* ifndef _SQLITE3RTREE_H_ */
6872
6873
6874 /************** End of sqlite3.h *********************************************/
6875 /************** Continuing where we left off in sqliteInt.h ******************/
6876 /************** Include hash.h in the middle of sqliteInt.h ******************/
6877 /************** Begin file hash.h ********************************************/
6878 /*
6879 ** 2001 September 22
6880 **
6881 ** The author disclaims copyright to this source code.  In place of
6882 ** a legal notice, here is a blessing:
6883 **
6884 **    May you do good and not evil.
6885 **    May you find forgiveness for yourself and forgive others.
6886 **    May you share freely, never taking more than you give.
6887 **
6888 *************************************************************************
6889 ** This is the header file for the generic hash-table implemenation
6890 ** used in SQLite.
6891 */
6892 #ifndef _SQLITE_HASH_H_
6893 #define _SQLITE_HASH_H_
6894
6895 /* Forward declarations of structures. */
6896 typedef struct Hash Hash;
6897 typedef struct HashElem HashElem;
6898
6899 /* A complete hash table is an instance of the following structure.
6900 ** The internals of this structure are intended to be opaque -- client
6901 ** code should not attempt to access or modify the fields of this structure
6902 ** directly.  Change this structure only by using the routines below.
6903 ** However, some of the "procedures" and "functions" for modifying and
6904 ** accessing this structure are really macros, so we can't really make
6905 ** this structure opaque.
6906 **
6907 ** All elements of the hash table are on a single doubly-linked list.
6908 ** Hash.first points to the head of this list.
6909 **
6910 ** There are Hash.htsize buckets.  Each bucket points to a spot in
6911 ** the global doubly-linked list.  The contents of the bucket are the
6912 ** element pointed to plus the next _ht.count-1 elements in the list.
6913 **
6914 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
6915 ** by a linear search of the global list.  For small tables, the 
6916 ** Hash.ht table is never allocated because if there are few elements
6917 ** in the table, it is faster to do a linear search than to manage
6918 ** the hash table.
6919 */
6920 struct Hash {
6921   unsigned int htsize;      /* Number of buckets in the hash table */
6922   unsigned int count;       /* Number of entries in this table */
6923   HashElem *first;          /* The first element of the array */
6924   struct _ht {              /* the hash table */
6925     int count;                 /* Number of entries with this hash */
6926     HashElem *chain;           /* Pointer to first entry with this hash */
6927   } *ht;
6928 };
6929
6930 /* Each element in the hash table is an instance of the following 
6931 ** structure.  All elements are stored on a single doubly-linked list.
6932 **
6933 ** Again, this structure is intended to be opaque, but it can't really
6934 ** be opaque because it is used by macros.
6935 */
6936 struct HashElem {
6937   HashElem *next, *prev;       /* Next and previous elements in the table */
6938   void *data;                  /* Data associated with this element */
6939   const char *pKey; int nKey;  /* Key associated with this element */
6940 };
6941
6942 /*
6943 ** Access routines.  To delete, insert a NULL pointer.
6944 */
6945 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
6946 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
6947 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
6948 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
6949
6950 /*
6951 ** Macros for looping over all elements of a hash table.  The idiom is
6952 ** like this:
6953 **
6954 **   Hash h;
6955 **   HashElem *p;
6956 **   ...
6957 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
6958 **     SomeStructure *pData = sqliteHashData(p);
6959 **     // do something with pData
6960 **   }
6961 */
6962 #define sqliteHashFirst(H)  ((H)->first)
6963 #define sqliteHashNext(E)   ((E)->next)
6964 #define sqliteHashData(E)   ((E)->data)
6965 /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
6966 /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
6967
6968 /*
6969 ** Number of entries in a hash table
6970 */
6971 /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
6972
6973 #endif /* _SQLITE_HASH_H_ */
6974
6975 /************** End of hash.h ************************************************/
6976 /************** Continuing where we left off in sqliteInt.h ******************/
6977 /************** Include parse.h in the middle of sqliteInt.h *****************/
6978 /************** Begin file parse.h *******************************************/
6979 #define TK_SEMI                            1
6980 #define TK_EXPLAIN                         2
6981 #define TK_QUERY                           3
6982 #define TK_PLAN                            4
6983 #define TK_BEGIN                           5
6984 #define TK_TRANSACTION                     6
6985 #define TK_DEFERRED                        7
6986 #define TK_IMMEDIATE                       8
6987 #define TK_EXCLUSIVE                       9
6988 #define TK_COMMIT                         10
6989 #define TK_END                            11
6990 #define TK_ROLLBACK                       12
6991 #define TK_SAVEPOINT                      13
6992 #define TK_RELEASE                        14
6993 #define TK_TO                             15
6994 #define TK_TABLE                          16
6995 #define TK_CREATE                         17
6996 #define TK_IF                             18
6997 #define TK_NOT                            19
6998 #define TK_EXISTS                         20
6999 #define TK_TEMP                           21
7000 #define TK_LP                             22
7001 #define TK_RP                             23
7002 #define TK_AS                             24
7003 #define TK_COMMA                          25
7004 #define TK_ID                             26
7005 #define TK_INDEXED                        27
7006 #define TK_ABORT                          28
7007 #define TK_ACTION                         29
7008 #define TK_AFTER                          30
7009 #define TK_ANALYZE                        31
7010 #define TK_ASC                            32
7011 #define TK_ATTACH                         33
7012 #define TK_BEFORE                         34
7013 #define TK_BY                             35
7014 #define TK_CASCADE                        36
7015 #define TK_CAST                           37
7016 #define TK_COLUMNKW                       38
7017 #define TK_CONFLICT                       39
7018 #define TK_DATABASE                       40
7019 #define TK_DESC                           41
7020 #define TK_DETACH                         42
7021 #define TK_EACH                           43
7022 #define TK_FAIL                           44
7023 #define TK_FOR                            45
7024 #define TK_IGNORE                         46
7025 #define TK_INITIALLY                      47
7026 #define TK_INSTEAD                        48
7027 #define TK_LIKE_KW                        49
7028 #define TK_MATCH                          50
7029 #define TK_NO                             51
7030 #define TK_KEY                            52
7031 #define TK_OF                             53
7032 #define TK_OFFSET                         54
7033 #define TK_PRAGMA                         55
7034 #define TK_RAISE                          56
7035 #define TK_REPLACE                        57
7036 #define TK_RESTRICT                       58
7037 #define TK_ROW                            59
7038 #define TK_TRIGGER                        60
7039 #define TK_VACUUM                         61
7040 #define TK_VIEW                           62
7041 #define TK_VIRTUAL                        63
7042 #define TK_REINDEX                        64
7043 #define TK_RENAME                         65
7044 #define TK_CTIME_KW                       66
7045 #define TK_ANY                            67
7046 #define TK_OR                             68
7047 #define TK_AND                            69
7048 #define TK_IS                             70
7049 #define TK_BETWEEN                        71
7050 #define TK_IN                             72
7051 #define TK_ISNULL                         73
7052 #define TK_NOTNULL                        74
7053 #define TK_NE                             75
7054 #define TK_EQ                             76
7055 #define TK_GT                             77
7056 #define TK_LE                             78
7057 #define TK_LT                             79
7058 #define TK_GE                             80
7059 #define TK_ESCAPE                         81
7060 #define TK_BITAND                         82
7061 #define TK_BITOR                          83
7062 #define TK_LSHIFT                         84
7063 #define TK_RSHIFT                         85
7064 #define TK_PLUS                           86
7065 #define TK_MINUS                          87
7066 #define TK_STAR                           88
7067 #define TK_SLASH                          89
7068 #define TK_REM                            90
7069 #define TK_CONCAT                         91
7070 #define TK_COLLATE                        92
7071 #define TK_BITNOT                         93
7072 #define TK_STRING                         94
7073 #define TK_JOIN_KW                        95
7074 #define TK_CONSTRAINT                     96
7075 #define TK_DEFAULT                        97
7076 #define TK_NULL                           98
7077 #define TK_PRIMARY                        99
7078 #define TK_UNIQUE                         100
7079 #define TK_CHECK                          101
7080 #define TK_REFERENCES                     102
7081 #define TK_AUTOINCR                       103
7082 #define TK_ON                             104
7083 #define TK_INSERT                         105
7084 #define TK_DELETE                         106
7085 #define TK_UPDATE                         107
7086 #define TK_SET                            108
7087 #define TK_DEFERRABLE                     109
7088 #define TK_FOREIGN                        110
7089 #define TK_DROP                           111
7090 #define TK_UNION                          112
7091 #define TK_ALL                            113
7092 #define TK_EXCEPT                         114
7093 #define TK_INTERSECT                      115
7094 #define TK_SELECT                         116
7095 #define TK_DISTINCT                       117
7096 #define TK_DOT                            118
7097 #define TK_FROM                           119
7098 #define TK_JOIN                           120
7099 #define TK_USING                          121
7100 #define TK_ORDER                          122
7101 #define TK_GROUP                          123
7102 #define TK_HAVING                         124
7103 #define TK_LIMIT                          125
7104 #define TK_WHERE                          126
7105 #define TK_INTO                           127
7106 #define TK_VALUES                         128
7107 #define TK_INTEGER                        129
7108 #define TK_FLOAT                          130
7109 #define TK_BLOB                           131
7110 #define TK_REGISTER                       132
7111 #define TK_VARIABLE                       133
7112 #define TK_CASE                           134
7113 #define TK_WHEN                           135
7114 #define TK_THEN                           136
7115 #define TK_ELSE                           137
7116 #define TK_INDEX                          138
7117 #define TK_ALTER                          139
7118 #define TK_ADD                            140
7119 #define TK_TO_TEXT                        141
7120 #define TK_TO_BLOB                        142
7121 #define TK_TO_NUMERIC                     143
7122 #define TK_TO_INT                         144
7123 #define TK_TO_REAL                        145
7124 #define TK_ISNOT                          146
7125 #define TK_END_OF_FILE                    147
7126 #define TK_ILLEGAL                        148
7127 #define TK_SPACE                          149
7128 #define TK_UNCLOSED_STRING                150
7129 #define TK_FUNCTION                       151
7130 #define TK_COLUMN                         152
7131 #define TK_AGG_FUNCTION                   153
7132 #define TK_AGG_COLUMN                     154
7133 #define TK_CONST_FUNC                     155
7134 #define TK_UMINUS                         156
7135 #define TK_UPLUS                          157
7136
7137 /************** End of parse.h ***********************************************/
7138 /************** Continuing where we left off in sqliteInt.h ******************/
7139 #include <stdio.h>
7140 #include <stdlib.h>
7141 #include <string.h>
7142 #include <assert.h>
7143 #include <stddef.h>
7144
7145 /*
7146 ** If compiling for a processor that lacks floating point support,
7147 ** substitute integer for floating-point
7148 */
7149 #ifdef SQLITE_OMIT_FLOATING_POINT
7150 # define double sqlite_int64
7151 # define float sqlite_int64
7152 # define LONGDOUBLE_TYPE sqlite_int64
7153 # ifndef SQLITE_BIG_DBL
7154 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
7155 # endif
7156 # define SQLITE_OMIT_DATETIME_FUNCS 1
7157 # define SQLITE_OMIT_TRACE 1
7158 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
7159 # undef SQLITE_HAVE_ISNAN
7160 #endif
7161 #ifndef SQLITE_BIG_DBL
7162 # define SQLITE_BIG_DBL (1e99)
7163 #endif
7164
7165 /*
7166 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
7167 ** afterward. Having this macro allows us to cause the C compiler 
7168 ** to omit code used by TEMP tables without messy #ifndef statements.
7169 */
7170 #ifdef SQLITE_OMIT_TEMPDB
7171 #define OMIT_TEMPDB 1
7172 #else
7173 #define OMIT_TEMPDB 0
7174 #endif
7175
7176 /*
7177 ** The "file format" number is an integer that is incremented whenever
7178 ** the VDBE-level file format changes.  The following macros define the
7179 ** the default file format for new databases and the maximum file format
7180 ** that the library can read.
7181 */
7182 #define SQLITE_MAX_FILE_FORMAT 4
7183 #ifndef SQLITE_DEFAULT_FILE_FORMAT
7184 # define SQLITE_DEFAULT_FILE_FORMAT 1
7185 #endif
7186
7187 /*
7188 ** Determine whether triggers are recursive by default.  This can be
7189 ** changed at run-time using a pragma.
7190 */
7191 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
7192 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
7193 #endif
7194
7195 /*
7196 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
7197 ** on the command-line
7198 */
7199 #ifndef SQLITE_TEMP_STORE
7200 # define SQLITE_TEMP_STORE 1
7201 #endif
7202
7203 /*
7204 ** GCC does not define the offsetof() macro so we'll have to do it
7205 ** ourselves.
7206 */
7207 #ifndef offsetof
7208 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
7209 #endif
7210
7211 /*
7212 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
7213 ** not, there are still machines out there that use EBCDIC.)
7214 */
7215 #if 'A' == '\301'
7216 # define SQLITE_EBCDIC 1
7217 #else
7218 # define SQLITE_ASCII 1
7219 #endif
7220
7221 /*
7222 ** Integers of known sizes.  These typedefs might change for architectures
7223 ** where the sizes very.  Preprocessor macros are available so that the
7224 ** types can be conveniently redefined at compile-type.  Like this:
7225 **
7226 **         cc '-DUINTPTR_TYPE=long long int' ...
7227 */
7228 #ifndef UINT32_TYPE
7229 # ifdef HAVE_UINT32_T
7230 #  define UINT32_TYPE uint32_t
7231 # else
7232 #  define UINT32_TYPE unsigned int
7233 # endif
7234 #endif
7235 #ifndef UINT16_TYPE
7236 # ifdef HAVE_UINT16_T
7237 #  define UINT16_TYPE uint16_t
7238 # else
7239 #  define UINT16_TYPE unsigned short int
7240 # endif
7241 #endif
7242 #ifndef INT16_TYPE
7243 # ifdef HAVE_INT16_T
7244 #  define INT16_TYPE int16_t
7245 # else
7246 #  define INT16_TYPE short int
7247 # endif
7248 #endif
7249 #ifndef UINT8_TYPE
7250 # ifdef HAVE_UINT8_T
7251 #  define UINT8_TYPE uint8_t
7252 # else
7253 #  define UINT8_TYPE unsigned char
7254 # endif
7255 #endif
7256 #ifndef INT8_TYPE
7257 # ifdef HAVE_INT8_T
7258 #  define INT8_TYPE int8_t
7259 # else
7260 #  define INT8_TYPE signed char
7261 # endif
7262 #endif
7263 #ifndef LONGDOUBLE_TYPE
7264 # define LONGDOUBLE_TYPE long double
7265 #endif
7266 typedef sqlite_int64 i64;          /* 8-byte signed integer */
7267 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
7268 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
7269 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
7270 typedef INT16_TYPE i16;            /* 2-byte signed integer */
7271 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
7272 typedef INT8_TYPE i8;              /* 1-byte signed integer */
7273
7274 /*
7275 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
7276 ** that can be stored in a u32 without loss of data.  The value
7277 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
7278 ** have to specify the value in the less intuitive manner shown:
7279 */
7280 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
7281
7282 /*
7283 ** Macros to determine whether the machine is big or little endian,
7284 ** evaluated at runtime.
7285 */
7286 #ifdef SQLITE_AMALGAMATION
7287 SQLITE_PRIVATE const int sqlite3one = 1;
7288 #else
7289 SQLITE_PRIVATE const int sqlite3one;
7290 #endif
7291 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
7292                              || defined(__x86_64) || defined(__x86_64__)
7293 # define SQLITE_BIGENDIAN    0
7294 # define SQLITE_LITTLEENDIAN 1
7295 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
7296 #else
7297 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
7298 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
7299 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
7300 #endif
7301
7302 /*
7303 ** Constants for the largest and smallest possible 64-bit signed integers.
7304 ** These macros are designed to work correctly on both 32-bit and 64-bit
7305 ** compilers.
7306 */
7307 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
7308 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
7309
7310 /* 
7311 ** Round up a number to the next larger multiple of 8.  This is used
7312 ** to force 8-byte alignment on 64-bit architectures.
7313 */
7314 #define ROUND8(x)     (((x)+7)&~7)
7315
7316 /*
7317 ** Round down to the nearest multiple of 8
7318 */
7319 #define ROUNDDOWN8(x) ((x)&~7)
7320
7321 /*
7322 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
7323 ** macro is used only within assert() to verify that the code gets
7324 ** all alignment restrictions correct.
7325 **
7326 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
7327 ** underlying malloc() implemention might return us 4-byte aligned
7328 ** pointers.  In that case, only verify 4-byte alignment.
7329 */
7330 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
7331 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
7332 #else
7333 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
7334 #endif
7335
7336
7337 /*
7338 ** An instance of the following structure is used to store the busy-handler
7339 ** callback for a given sqlite handle. 
7340 **
7341 ** The sqlite.busyHandler member of the sqlite struct contains the busy
7342 ** callback for the database handle. Each pager opened via the sqlite
7343 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
7344 ** callback is currently invoked only from within pager.c.
7345 */
7346 typedef struct BusyHandler BusyHandler;
7347 struct BusyHandler {
7348   int (*xFunc)(void *,int);  /* The busy callback */
7349   void *pArg;                /* First arg to busy callback */
7350   int nBusy;                 /* Incremented with each busy call */
7351 };
7352
7353 /*
7354 ** Name of the master database table.  The master database table
7355 ** is a special table that holds the names and attributes of all
7356 ** user tables and indices.
7357 */
7358 #define MASTER_NAME       "sqlite_master"
7359 #define TEMP_MASTER_NAME  "sqlite_temp_master"
7360
7361 /*
7362 ** The root-page of the master database table.
7363 */
7364 #define MASTER_ROOT       1
7365
7366 /*
7367 ** The name of the schema table.
7368 */
7369 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
7370
7371 /*
7372 ** A convenience macro that returns the number of elements in
7373 ** an array.
7374 */
7375 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
7376
7377 /*
7378 ** The following value as a destructor means to use sqlite3DbFree().
7379 ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
7380 */
7381 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
7382
7383 /*
7384 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
7385 ** not support Writable Static Data (WSD) such as global and static variables.
7386 ** All variables must either be on the stack or dynamically allocated from
7387 ** the heap.  When WSD is unsupported, the variable declarations scattered
7388 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
7389 ** macro is used for this purpose.  And instead of referencing the variable
7390 ** directly, we use its constant as a key to lookup the run-time allocated
7391 ** buffer that holds real variable.  The constant is also the initializer
7392 ** for the run-time allocated buffer.
7393 **
7394 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
7395 ** macros become no-ops and have zero performance impact.
7396 */
7397 #ifdef SQLITE_OMIT_WSD
7398   #define SQLITE_WSD const
7399   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
7400   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
7401 SQLITE_API   int sqlite3_wsd_init(int N, int J);
7402 SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
7403 #else
7404   #define SQLITE_WSD 
7405   #define GLOBAL(t,v) v
7406   #define sqlite3GlobalConfig sqlite3Config
7407 #endif
7408
7409 /*
7410 ** The following macros are used to suppress compiler warnings and to
7411 ** make it clear to human readers when a function parameter is deliberately 
7412 ** left unused within the body of a function. This usually happens when
7413 ** a function is called via a function pointer. For example the 
7414 ** implementation of an SQL aggregate step callback may not use the
7415 ** parameter indicating the number of arguments passed to the aggregate,
7416 ** if it knows that this is enforced elsewhere.
7417 **
7418 ** When a function parameter is not used at all within the body of a function,
7419 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
7420 ** However, these macros may also be used to suppress warnings related to
7421 ** parameters that may or may not be used depending on compilation options.
7422 ** For example those parameters only used in assert() statements. In these
7423 ** cases the parameters are named as per the usual conventions.
7424 */
7425 #define UNUSED_PARAMETER(x) (void)(x)
7426 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
7427
7428 /*
7429 ** Forward references to structures
7430 */
7431 typedef struct AggInfo AggInfo;
7432 typedef struct AuthContext AuthContext;
7433 typedef struct AutoincInfo AutoincInfo;
7434 typedef struct Bitvec Bitvec;
7435 typedef struct CollSeq CollSeq;
7436 typedef struct Column Column;
7437 typedef struct Db Db;
7438 typedef struct Schema Schema;
7439 typedef struct Expr Expr;
7440 typedef struct ExprList ExprList;
7441 typedef struct ExprSpan ExprSpan;
7442 typedef struct FKey FKey;
7443 typedef struct FuncDestructor FuncDestructor;
7444 typedef struct FuncDef FuncDef;
7445 typedef struct FuncDefHash FuncDefHash;
7446 typedef struct IdList IdList;
7447 typedef struct Index Index;
7448 typedef struct IndexSample IndexSample;
7449 typedef struct KeyClass KeyClass;
7450 typedef struct KeyInfo KeyInfo;
7451 typedef struct Lookaside Lookaside;
7452 typedef struct LookasideSlot LookasideSlot;
7453 typedef struct Module Module;
7454 typedef struct NameContext NameContext;
7455 typedef struct Parse Parse;
7456 typedef struct RowSet RowSet;
7457 typedef struct Savepoint Savepoint;
7458 typedef struct Select Select;
7459 typedef struct SrcList SrcList;
7460 typedef struct StrAccum StrAccum;
7461 typedef struct Table Table;
7462 typedef struct TableLock TableLock;
7463 typedef struct Token Token;
7464 typedef struct Trigger Trigger;
7465 typedef struct TriggerPrg TriggerPrg;
7466 typedef struct TriggerStep TriggerStep;
7467 typedef struct UnpackedRecord UnpackedRecord;
7468 typedef struct VTable VTable;
7469 typedef struct Walker Walker;
7470 typedef struct WherePlan WherePlan;
7471 typedef struct WhereInfo WhereInfo;
7472 typedef struct WhereLevel WhereLevel;
7473
7474 /*
7475 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
7476 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
7477 ** pointer types (i.e. FuncDef) defined above.
7478 */
7479 /************** Include btree.h in the middle of sqliteInt.h *****************/
7480 /************** Begin file btree.h *******************************************/
7481 /*
7482 ** 2001 September 15
7483 **
7484 ** The author disclaims copyright to this source code.  In place of
7485 ** a legal notice, here is a blessing:
7486 **
7487 **    May you do good and not evil.
7488 **    May you find forgiveness for yourself and forgive others.
7489 **    May you share freely, never taking more than you give.
7490 **
7491 *************************************************************************
7492 ** This header file defines the interface that the sqlite B-Tree file
7493 ** subsystem.  See comments in the source code for a detailed description
7494 ** of what each interface routine does.
7495 */
7496 #ifndef _BTREE_H_
7497 #define _BTREE_H_
7498
7499 /* TODO: This definition is just included so other modules compile. It
7500 ** needs to be revisited.
7501 */
7502 #define SQLITE_N_BTREE_META 10
7503
7504 /*
7505 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
7506 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
7507 */
7508 #ifndef SQLITE_DEFAULT_AUTOVACUUM
7509   #define SQLITE_DEFAULT_AUTOVACUUM 0
7510 #endif
7511
7512 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
7513 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
7514 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
7515
7516 /*
7517 ** Forward declarations of structure
7518 */
7519 typedef struct Btree Btree;
7520 typedef struct BtCursor BtCursor;
7521 typedef struct BtShared BtShared;
7522 typedef struct BtreeMutexArray BtreeMutexArray;
7523
7524 /*
7525 ** This structure records all of the Btrees that need to hold
7526 ** a mutex before we enter sqlite3VdbeExec().  The Btrees are
7527 ** are placed in aBtree[] in order of aBtree[]->pBt.  That way,
7528 ** we can always lock and unlock them all quickly.
7529 */
7530 struct BtreeMutexArray {
7531   int nMutex;
7532   Btree *aBtree[SQLITE_MAX_ATTACHED+1];
7533 };
7534
7535
7536 SQLITE_PRIVATE int sqlite3BtreeOpen(
7537   const char *zFilename,   /* Name of database file to open */
7538   sqlite3 *db,             /* Associated database connection */
7539   Btree **ppBtree,         /* Return open Btree* here */
7540   int flags,               /* Flags */
7541   int vfsFlags             /* Flags passed through to VFS open */
7542 );
7543
7544 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
7545 ** following values.
7546 **
7547 ** NOTE:  These values must match the corresponding PAGER_ values in
7548 ** pager.h.
7549 */
7550 #define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
7551 #define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
7552 #define BTREE_MEMORY        4  /* This is an in-memory DB */
7553 #define BTREE_SINGLE        8  /* The file contains at most 1 b-tree */
7554 #define BTREE_UNORDERED    16  /* Use of a hash implementation is OK */
7555
7556 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
7557 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
7558 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);
7559 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
7560 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
7561 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
7562 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
7563 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
7564 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
7565 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
7566 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
7567 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
7568 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
7569 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
7570 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
7571 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
7572 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
7573 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
7574 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
7575 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
7576 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
7577 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
7578 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
7579 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
7580 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
7581 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
7582
7583 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
7584 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
7585 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
7586
7587 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
7588
7589 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
7590 ** of the flags shown below.
7591 **
7592 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
7593 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
7594 ** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
7595 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
7596 ** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
7597 ** indices.)
7598 */
7599 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
7600 #define BTREE_BLOBKEY    2    /* Table has keys only - no data */
7601
7602 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
7603 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
7604 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
7605
7606 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
7607 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
7608
7609 /*
7610 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
7611 ** should be one of the following values. The integer values are assigned 
7612 ** to constants so that the offset of the corresponding field in an
7613 ** SQLite database header may be found using the following formula:
7614 **
7615 **   offset = 36 + (idx * 4)
7616 **
7617 ** For example, the free-page-count field is located at byte offset 36 of
7618 ** the database file header. The incr-vacuum-flag field is located at
7619 ** byte offset 64 (== 36+4*7).
7620 */
7621 #define BTREE_FREE_PAGE_COUNT     0
7622 #define BTREE_SCHEMA_VERSION      1
7623 #define BTREE_FILE_FORMAT         2
7624 #define BTREE_DEFAULT_CACHE_SIZE  3
7625 #define BTREE_LARGEST_ROOT_PAGE   4
7626 #define BTREE_TEXT_ENCODING       5
7627 #define BTREE_USER_VERSION        6
7628 #define BTREE_INCR_VACUUM         7
7629
7630 SQLITE_PRIVATE int sqlite3BtreeCursor(
7631   Btree*,                              /* BTree containing table to open */
7632   int iTable,                          /* Index of root page */
7633   int wrFlag,                          /* 1 for writing.  0 for read-only */
7634   struct KeyInfo*,                     /* First argument to compare function */
7635   BtCursor *pCursor                    /* Space to write cursor structure */
7636 );
7637 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
7638 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
7639
7640 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
7641 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
7642   BtCursor*,
7643   UnpackedRecord *pUnKey,
7644   i64 intKey,
7645   int bias,
7646   int *pRes
7647 );
7648 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
7649 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
7650 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
7651                                   const void *pData, int nData,
7652                                   int nZero, int bias, int seekResult);
7653 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
7654 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
7655 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
7656 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
7657 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
7658 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
7659 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
7660 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
7661 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
7662 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
7663 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
7664 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
7665 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
7666
7667 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
7668 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
7669
7670 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
7671 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
7672 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
7673
7674 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
7675
7676 #ifndef NDEBUG
7677 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
7678 #endif
7679
7680 #ifndef SQLITE_OMIT_BTREECOUNT
7681 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
7682 #endif
7683
7684 #ifdef SQLITE_TEST
7685 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
7686 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
7687 #endif
7688
7689 #ifndef SQLITE_OMIT_WAL
7690 SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*);
7691 #endif
7692
7693 /*
7694 ** If we are not using shared cache, then there is no need to
7695 ** use mutexes to access the BtShared structures.  So make the
7696 ** Enter and Leave procedures no-ops.
7697 */
7698 #ifndef SQLITE_OMIT_SHARED_CACHE
7699 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
7700 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
7701 #else
7702 # define sqlite3BtreeEnter(X) 
7703 # define sqlite3BtreeEnterAll(X)
7704 #endif
7705
7706 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
7707 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
7708 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
7709 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
7710 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
7711 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
7712 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
7713 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
7714 #ifndef NDEBUG
7715   /* These routines are used inside assert() statements only. */
7716 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
7717 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
7718 #endif
7719 #else
7720
7721 # define sqlite3BtreeLeave(X)
7722 # define sqlite3BtreeEnterCursor(X)
7723 # define sqlite3BtreeLeaveCursor(X)
7724 # define sqlite3BtreeLeaveAll(X)
7725 # define sqlite3BtreeMutexArrayEnter(X)
7726 # define sqlite3BtreeMutexArrayLeave(X)
7727 # define sqlite3BtreeMutexArrayInsert(X,Y)
7728
7729 # define sqlite3BtreeHoldsMutex(X) 1
7730 # define sqlite3BtreeHoldsAllMutexes(X) 1
7731 #endif
7732
7733
7734 #endif /* _BTREE_H_ */
7735
7736 /************** End of btree.h ***********************************************/
7737 /************** Continuing where we left off in sqliteInt.h ******************/
7738 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
7739 /************** Begin file vdbe.h ********************************************/
7740 /*
7741 ** 2001 September 15
7742 **
7743 ** The author disclaims copyright to this source code.  In place of
7744 ** a legal notice, here is a blessing:
7745 **
7746 **    May you do good and not evil.
7747 **    May you find forgiveness for yourself and forgive others.
7748 **    May you share freely, never taking more than you give.
7749 **
7750 *************************************************************************
7751 ** Header file for the Virtual DataBase Engine (VDBE)
7752 **
7753 ** This header defines the interface to the virtual database engine
7754 ** or VDBE.  The VDBE implements an abstract machine that runs a
7755 ** simple program to access and modify the underlying database.
7756 */
7757 #ifndef _SQLITE_VDBE_H_
7758 #define _SQLITE_VDBE_H_
7759
7760 /*
7761 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
7762 ** in the source file sqliteVdbe.c are allowed to see the insides
7763 ** of this structure.
7764 */
7765 typedef struct Vdbe Vdbe;
7766
7767 /*
7768 ** The names of the following types declared in vdbeInt.h are required
7769 ** for the VdbeOp definition.
7770 */
7771 typedef struct VdbeFunc VdbeFunc;
7772 typedef struct Mem Mem;
7773 typedef struct SubProgram SubProgram;
7774
7775 /*
7776 ** A single instruction of the virtual machine has an opcode
7777 ** and as many as three operands.  The instruction is recorded
7778 ** as an instance of the following structure:
7779 */
7780 struct VdbeOp {
7781   u8 opcode;          /* What operation to perform */
7782   signed char p4type; /* One of the P4_xxx constants for p4 */
7783   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
7784   u8 p5;              /* Fifth parameter is an unsigned character */
7785   int p1;             /* First operand */
7786   int p2;             /* Second parameter (often the jump destination) */
7787   int p3;             /* The third parameter */
7788   union {             /* fourth parameter */
7789     int i;                 /* Integer value if p4type==P4_INT32 */
7790     void *p;               /* Generic pointer */
7791     char *z;               /* Pointer to data for string (char array) types */
7792     i64 *pI64;             /* Used when p4type is P4_INT64 */
7793     double *pReal;         /* Used when p4type is P4_REAL */
7794     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
7795     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
7796     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
7797     Mem *pMem;             /* Used when p4type is P4_MEM */
7798     VTable *pVtab;         /* Used when p4type is P4_VTAB */
7799     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
7800     int *ai;               /* Used when p4type is P4_INTARRAY */
7801     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
7802   } p4;
7803 #ifdef SQLITE_DEBUG
7804   char *zComment;          /* Comment to improve readability */
7805 #endif
7806 #ifdef VDBE_PROFILE
7807   int cnt;                 /* Number of times this instruction was executed */
7808   u64 cycles;              /* Total time spent executing this instruction */
7809 #endif
7810 };
7811 typedef struct VdbeOp VdbeOp;
7812
7813
7814 /*
7815 ** A sub-routine used to implement a trigger program.
7816 */
7817 struct SubProgram {
7818   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
7819   int nOp;                      /* Elements in aOp[] */
7820   int nMem;                     /* Number of memory cells required */
7821   int nCsr;                     /* Number of cursors required */
7822   void *token;                  /* id that may be used to recursive triggers */
7823   SubProgram *pNext;            /* Next sub-program already visited */
7824 };
7825
7826 /*
7827 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
7828 ** it takes up less space.
7829 */
7830 struct VdbeOpList {
7831   u8 opcode;          /* What operation to perform */
7832   signed char p1;     /* First operand */
7833   signed char p2;     /* Second parameter (often the jump destination) */
7834   signed char p3;     /* Third parameter */
7835 };
7836 typedef struct VdbeOpList VdbeOpList;
7837
7838 /*
7839 ** Allowed values of VdbeOp.p4type
7840 */
7841 #define P4_NOTUSED    0   /* The P4 parameter is not used */
7842 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
7843 #define P4_STATIC   (-2)  /* Pointer to a static string */
7844 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
7845 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
7846 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
7847 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
7848 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
7849 #define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
7850 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
7851 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
7852 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
7853 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
7854 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
7855 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
7856 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
7857
7858 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
7859 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
7860 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
7861 ** gets freed when the Vdbe is finalized so it still should be obtained
7862 ** from a single sqliteMalloc().  But no copy is made and the calling
7863 ** function should *not* try to free the KeyInfo.
7864 */
7865 #define P4_KEYINFO_HANDOFF (-16)
7866 #define P4_KEYINFO_STATIC  (-17)
7867
7868 /*
7869 ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
7870 ** number of columns of data returned by the statement.
7871 */
7872 #define COLNAME_NAME     0
7873 #define COLNAME_DECLTYPE 1
7874 #define COLNAME_DATABASE 2
7875 #define COLNAME_TABLE    3
7876 #define COLNAME_COLUMN   4
7877 #ifdef SQLITE_ENABLE_COLUMN_METADATA
7878 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
7879 #else
7880 # ifdef SQLITE_OMIT_DECLTYPE
7881 #   define COLNAME_N      1      /* Store only the name */
7882 # else
7883 #   define COLNAME_N      2      /* Store the name and decltype */
7884 # endif
7885 #endif
7886
7887 /*
7888 ** The following macro converts a relative address in the p2 field
7889 ** of a VdbeOp structure into a negative number so that 
7890 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
7891 ** the macro again restores the address.
7892 */
7893 #define ADDR(X)  (-1-(X))
7894
7895 /*
7896 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
7897 ** header file that defines a number for each opcode used by the VDBE.
7898 */
7899 /************** Include opcodes.h in the middle of vdbe.h ********************/
7900 /************** Begin file opcodes.h *****************************************/
7901 /* Automatically generated.  Do not edit */
7902 /* See the mkopcodeh.awk script for details */
7903 #define OP_Goto                                 1
7904 #define OP_Gosub                                2
7905 #define OP_Return                               3
7906 #define OP_Yield                                4
7907 #define OP_HaltIfNull                           5
7908 #define OP_Halt                                 6
7909 #define OP_Integer                              7
7910 #define OP_Int64                                8
7911 #define OP_Real                               130   /* same as TK_FLOAT    */
7912 #define OP_String8                             94   /* same as TK_STRING   */
7913 #define OP_String                               9
7914 #define OP_Null                                10
7915 #define OP_Blob                                11
7916 #define OP_Variable                            12
7917 #define OP_Move                                13
7918 #define OP_Copy                                14
7919 #define OP_SCopy                               15
7920 #define OP_ResultRow                           16
7921 #define OP_Concat                              91   /* same as TK_CONCAT   */
7922 #define OP_Add                                 86   /* same as TK_PLUS     */
7923 #define OP_Subtract                            87   /* same as TK_MINUS    */
7924 #define OP_Multiply                            88   /* same as TK_STAR     */
7925 #define OP_Divide                              89   /* same as TK_SLASH    */
7926 #define OP_Remainder                           90   /* same as TK_REM      */
7927 #define OP_CollSeq                             17
7928 #define OP_Function                            18
7929 #define OP_BitAnd                              82   /* same as TK_BITAND   */
7930 #define OP_BitOr                               83   /* same as TK_BITOR    */
7931 #define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
7932 #define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
7933 #define OP_AddImm                              20
7934 #define OP_MustBeInt                           21
7935 #define OP_RealAffinity                        22
7936 #define OP_ToText                             141   /* same as TK_TO_TEXT  */
7937 #define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
7938 #define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
7939 #define OP_ToInt                              144   /* same as TK_TO_INT   */
7940 #define OP_ToReal                             145   /* same as TK_TO_REAL  */
7941 #define OP_Eq                                  76   /* same as TK_EQ       */
7942 #define OP_Ne                                  75   /* same as TK_NE       */
7943 #define OP_Lt                                  79   /* same as TK_LT       */
7944 #define OP_Le                                  78   /* same as TK_LE       */
7945 #define OP_Gt                                  77   /* same as TK_GT       */
7946 #define OP_Ge                                  80   /* same as TK_GE       */
7947 #define OP_Permutation                         23
7948 #define OP_Compare                             24
7949 #define OP_Jump                                25
7950 #define OP_And                                 69   /* same as TK_AND      */
7951 #define OP_Or                                  68   /* same as TK_OR       */
7952 #define OP_Not                                 19   /* same as TK_NOT      */
7953 #define OP_BitNot                              93   /* same as TK_BITNOT   */
7954 #define OP_If                                  26
7955 #define OP_IfNot                               27
7956 #define OP_IsNull                              73   /* same as TK_ISNULL   */
7957 #define OP_NotNull                             74   /* same as TK_NOTNULL  */
7958 #define OP_Column                              28
7959 #define OP_Affinity                            29
7960 #define OP_MakeRecord                          30
7961 #define OP_Count                               31
7962 #define OP_Savepoint                           32
7963 #define OP_AutoCommit                          33
7964 #define OP_Transaction                         34
7965 #define OP_ReadCookie                          35
7966 #define OP_SetCookie                           36
7967 #define OP_VerifyCookie                        37
7968 #define OP_OpenRead                            38
7969 #define OP_OpenWrite                           39
7970 #define OP_OpenAutoindex                       40
7971 #define OP_OpenEphemeral                       41
7972 #define OP_OpenPseudo                          42
7973 #define OP_Close                               43
7974 #define OP_SeekLt                              44
7975 #define OP_SeekLe                              45
7976 #define OP_SeekGe                              46
7977 #define OP_SeekGt                              47
7978 #define OP_Seek                                48
7979 #define OP_NotFound                            49
7980 #define OP_Found                               50
7981 #define OP_IsUnique                            51
7982 #define OP_NotExists                           52
7983 #define OP_Sequence                            53
7984 #define OP_NewRowid                            54
7985 #define OP_Insert                              55
7986 #define OP_InsertInt                           56
7987 #define OP_Delete                              57
7988 #define OP_ResetCount                          58
7989 #define OP_RowKey                              59
7990 #define OP_RowData                             60
7991 #define OP_Rowid                               61
7992 #define OP_NullRow                             62
7993 #define OP_Last                                63
7994 #define OP_Sort                                64
7995 #define OP_Rewind                              65
7996 #define OP_Prev                                66
7997 #define OP_Next                                67
7998 #define OP_IdxInsert                           70
7999 #define OP_IdxDelete                           71
8000 #define OP_IdxRowid                            72
8001 #define OP_IdxLT                               81
8002 #define OP_IdxGE                               92
8003 #define OP_Destroy                             95
8004 #define OP_Clear                               96
8005 #define OP_CreateIndex                         97
8006 #define OP_CreateTable                         98
8007 #define OP_ParseSchema                         99
8008 #define OP_LoadAnalysis                       100
8009 #define OP_DropTable                          101
8010 #define OP_DropIndex                          102
8011 #define OP_DropTrigger                        103
8012 #define OP_IntegrityCk                        104
8013 #define OP_RowSetAdd                          105
8014 #define OP_RowSetRead                         106
8015 #define OP_RowSetTest                         107
8016 #define OP_Program                            108
8017 #define OP_Param                              109
8018 #define OP_FkCounter                          110
8019 #define OP_FkIfZero                           111
8020 #define OP_MemMax                             112
8021 #define OP_IfPos                              113
8022 #define OP_IfNeg                              114
8023 #define OP_IfZero                             115
8024 #define OP_AggStep                            116
8025 #define OP_AggFinal                           117
8026 #define OP_Checkpoint                         118
8027 #define OP_JournalMode                        119
8028 #define OP_Vacuum                             120
8029 #define OP_IncrVacuum                         121
8030 #define OP_Expire                             122
8031 #define OP_TableLock                          123
8032 #define OP_VBegin                             124
8033 #define OP_VCreate                            125
8034 #define OP_VDestroy                           126
8035 #define OP_VOpen                              127
8036 #define OP_VFilter                            128
8037 #define OP_VColumn                            129
8038 #define OP_VNext                              131
8039 #define OP_VRename                            132
8040 #define OP_VUpdate                            133
8041 #define OP_Pagecount                          134
8042 #define OP_MaxPgcnt                           135
8043 #define OP_Trace                              136
8044 #define OP_Noop                               137
8045 #define OP_Explain                            138
8046
8047 /* The following opcode values are never used */
8048 #define OP_NotUsed_139                        139
8049 #define OP_NotUsed_140                        140
8050
8051
8052 /* Properties such as "out2" or "jump" that are specified in
8053 ** comments following the "case" for each opcode in the vdbe.c
8054 ** are encoded into bitvectors as follows:
8055 */
8056 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
8057 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
8058 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
8059 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
8060 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
8061 #define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
8062 #define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
8063 #define OPFLG_INITIALIZER {\
8064 /*   0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
8065 /*   8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\
8066 /*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
8067 /*  24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
8068 /*  32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\
8069 /*  40 */ 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11,\
8070 /*  48 */ 0x08, 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00,\
8071 /*  56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01,\
8072 /*  64 */ 0x01, 0x01, 0x01, 0x01, 0x4c, 0x4c, 0x08, 0x00,\
8073 /*  72 */ 0x02, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
8074 /*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
8075 /*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x02,\
8076 /*  96 */ 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
8077 /* 104 */ 0x00, 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01,\
8078 /* 112 */ 0x08, 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
8079 /* 120 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8080 /* 128 */ 0x01, 0x00, 0x02, 0x01, 0x00, 0x00, 0x02, 0x02,\
8081 /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
8082 /* 144 */ 0x04, 0x04,}
8083
8084 /************** End of opcodes.h *********************************************/
8085 /************** Continuing where we left off in vdbe.h ***********************/
8086
8087 /*
8088 ** Prototypes for the VDBE interface.  See comments on the implementation
8089 ** for a description of what each of these routines does.
8090 */
8091 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
8092 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
8093 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
8094 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
8095 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
8096 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
8097 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
8098 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
8099 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
8100 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
8101 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
8102 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
8103 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
8104 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
8105 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
8106 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
8107 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
8108 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
8109 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
8110 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
8111 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3*,Vdbe*);
8112 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int);
8113 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
8114 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
8115 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
8116 #ifdef SQLITE_DEBUG
8117 SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
8118 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
8119 #endif
8120 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
8121 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
8122 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
8123 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
8124 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
8125 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
8126 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
8127 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
8128 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
8129 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
8130 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
8131 #ifndef SQLITE_OMIT_TRACE
8132 SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
8133 #endif
8134
8135 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
8136 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
8137 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
8138
8139 #ifndef SQLITE_OMIT_TRIGGER
8140 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
8141 #endif
8142
8143
8144 #ifndef NDEBUG
8145 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
8146 # define VdbeComment(X)  sqlite3VdbeComment X
8147 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
8148 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
8149 #else
8150 # define VdbeComment(X)
8151 # define VdbeNoopComment(X)
8152 #endif
8153
8154 #endif
8155
8156 /************** End of vdbe.h ************************************************/
8157 /************** Continuing where we left off in sqliteInt.h ******************/
8158 /************** Include pager.h in the middle of sqliteInt.h *****************/
8159 /************** Begin file pager.h *******************************************/
8160 /*
8161 ** 2001 September 15
8162 **
8163 ** The author disclaims copyright to this source code.  In place of
8164 ** a legal notice, here is a blessing:
8165 **
8166 **    May you do good and not evil.
8167 **    May you find forgiveness for yourself and forgive others.
8168 **    May you share freely, never taking more than you give.
8169 **
8170 *************************************************************************
8171 ** This header file defines the interface that the sqlite page cache
8172 ** subsystem.  The page cache subsystem reads and writes a file a page
8173 ** at a time and provides a journal for rollback.
8174 */
8175
8176 #ifndef _PAGER_H_
8177 #define _PAGER_H_
8178
8179 /*
8180 ** Default maximum size for persistent journal files. A negative 
8181 ** value means no limit. This value may be overridden using the 
8182 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
8183 */
8184 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
8185   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
8186 #endif
8187
8188 /*
8189 ** The type used to represent a page number.  The first page in a file
8190 ** is called page 1.  0 is used to represent "not a page".
8191 */
8192 typedef u32 Pgno;
8193
8194 /*
8195 ** Each open file is managed by a separate instance of the "Pager" structure.
8196 */
8197 typedef struct Pager Pager;
8198
8199 /*
8200 ** Handle type for pages.
8201 */
8202 typedef struct PgHdr DbPage;
8203
8204 /*
8205 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
8206 ** reserved for working around a windows/posix incompatibility). It is
8207 ** used in the journal to signify that the remainder of the journal file 
8208 ** is devoted to storing a master journal name - there are no more pages to
8209 ** roll back. See comments for function writeMasterJournal() in pager.c 
8210 ** for details.
8211 */
8212 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
8213
8214 /*
8215 ** Allowed values for the flags parameter to sqlite3PagerOpen().
8216 **
8217 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
8218 */
8219 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
8220 #define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
8221 #define PAGER_MEMORY        0x0004    /* In-memory database */
8222
8223 /*
8224 ** Valid values for the second argument to sqlite3PagerLockingMode().
8225 */
8226 #define PAGER_LOCKINGMODE_QUERY      -1
8227 #define PAGER_LOCKINGMODE_NORMAL      0
8228 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
8229
8230 /*
8231 ** Numeric constants that encode the journalmode.  
8232 */
8233 #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
8234 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
8235 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
8236 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
8237 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
8238 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
8239 #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
8240
8241 /*
8242 ** The remainder of this file contains the declarations of the functions
8243 ** that make up the Pager sub-system API. See source code comments for 
8244 ** a detailed description of each routine.
8245 */
8246
8247 /* Open and close a Pager connection. */ 
8248 SQLITE_PRIVATE int sqlite3PagerOpen(
8249   sqlite3_vfs*,
8250   Pager **ppPager,
8251   const char*,
8252   int,
8253   int,
8254   int,
8255   void(*)(DbPage*)
8256 );
8257 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
8258 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
8259
8260 /* Functions used to configure a Pager object. */
8261 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
8262 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
8263 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
8264 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
8265 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int);
8266 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
8267 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
8268 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
8269 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
8270 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
8271 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
8272
8273 /* Functions used to obtain and release page references. */ 
8274 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
8275 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
8276 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
8277 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
8278 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
8279
8280 /* Operations on page references. */
8281 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
8282 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
8283 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
8284 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
8285 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
8286 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
8287
8288 /* Functions used to manage pager transactions and savepoints. */
8289 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
8290 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
8291 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
8292 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
8293 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
8294 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
8295 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
8296 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
8297 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
8298 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
8299
8300 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager);
8301 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
8302 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
8303 SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
8304 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
8305
8306 /* Functions used to query pager state and configuration. */
8307 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
8308 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
8309 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
8310 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
8311 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
8312 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
8313 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
8314 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
8315 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
8316 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
8317
8318 /* Functions used to truncate the database file. */
8319 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
8320
8321 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
8322 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
8323 #endif
8324
8325 /* Functions to support testing and debugging. */
8326 #if !defined(NDEBUG) || defined(SQLITE_TEST)
8327 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
8328 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
8329 #endif
8330 #ifdef SQLITE_TEST
8331 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
8332 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
8333   void disable_simulated_io_errors(void);
8334   void enable_simulated_io_errors(void);
8335 #else
8336 # define disable_simulated_io_errors()
8337 # define enable_simulated_io_errors()
8338 #endif
8339
8340 #endif /* _PAGER_H_ */
8341
8342 /************** End of pager.h ***********************************************/
8343 /************** Continuing where we left off in sqliteInt.h ******************/
8344 /************** Include pcache.h in the middle of sqliteInt.h ****************/
8345 /************** Begin file pcache.h ******************************************/
8346 /*
8347 ** 2008 August 05
8348 **
8349 ** The author disclaims copyright to this source code.  In place of
8350 ** a legal notice, here is a blessing:
8351 **
8352 **    May you do good and not evil.
8353 **    May you find forgiveness for yourself and forgive others.
8354 **    May you share freely, never taking more than you give.
8355 **
8356 *************************************************************************
8357 ** This header file defines the interface that the sqlite page cache
8358 ** subsystem. 
8359 */
8360
8361 #ifndef _PCACHE_H_
8362
8363 typedef struct PgHdr PgHdr;
8364 typedef struct PCache PCache;
8365
8366 /*
8367 ** Every page in the cache is controlled by an instance of the following
8368 ** structure.
8369 */
8370 struct PgHdr {
8371   void *pData;                   /* Content of this page */
8372   void *pExtra;                  /* Extra content */
8373   PgHdr *pDirty;                 /* Transient list of dirty pages */
8374   Pgno pgno;                     /* Page number for this page */
8375   Pager *pPager;                 /* The pager this page is part of */
8376 #ifdef SQLITE_CHECK_PAGES
8377   u32 pageHash;                  /* Hash of page content */
8378 #endif
8379   u16 flags;                     /* PGHDR flags defined below */
8380
8381   /**********************************************************************
8382   ** Elements above are public.  All that follows is private to pcache.c
8383   ** and should not be accessed by other modules.
8384   */
8385   i16 nRef;                      /* Number of users of this page */
8386   PCache *pCache;                /* Cache that owns this page */
8387
8388   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
8389   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
8390 };
8391
8392 /* Bit values for PgHdr.flags */
8393 #define PGHDR_DIRTY             0x002  /* Page has changed */
8394 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
8395                                        ** writing this page to the database */
8396 #define PGHDR_NEED_READ         0x008  /* Content is unread */
8397 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
8398 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
8399
8400 /* Initialize and shutdown the page cache subsystem */
8401 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
8402 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
8403
8404 /* Page cache buffer management:
8405 ** These routines implement SQLITE_CONFIG_PAGECACHE.
8406 */
8407 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
8408
8409 /* Create a new pager cache.
8410 ** Under memory stress, invoke xStress to try to make pages clean.
8411 ** Only clean and unpinned pages can be reclaimed.
8412 */
8413 SQLITE_PRIVATE void sqlite3PcacheOpen(
8414   int szPage,                    /* Size of every page */
8415   int szExtra,                   /* Extra space associated with each page */
8416   int bPurgeable,                /* True if pages are on backing store */
8417   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
8418   void *pStress,                 /* Argument to xStress */
8419   PCache *pToInit                /* Preallocated space for the PCache */
8420 );
8421
8422 /* Modify the page-size after the cache has been created. */
8423 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
8424
8425 /* Return the size in bytes of a PCache object.  Used to preallocate
8426 ** storage space.
8427 */
8428 SQLITE_PRIVATE int sqlite3PcacheSize(void);
8429
8430 /* One release per successful fetch.  Page is pinned until released.
8431 ** Reference counted. 
8432 */
8433 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
8434 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
8435
8436 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
8437 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
8438 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
8439 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
8440
8441 /* Change a page number.  Used by incr-vacuum. */
8442 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
8443
8444 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
8445 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
8446
8447 /* Get a list of all dirty pages in the cache, sorted by page number */
8448 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
8449
8450 /* Reset and close the cache object */
8451 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
8452
8453 /* Clear flags from pages of the page cache */
8454 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
8455
8456 /* Discard the contents of the cache */
8457 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
8458
8459 /* Return the total number of outstanding page references */
8460 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
8461
8462 /* Increment the reference count of an existing page */
8463 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
8464
8465 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
8466
8467 /* Return the total number of pages stored in the cache */
8468 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
8469
8470 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
8471 /* Iterate through all dirty pages currently stored in the cache. This
8472 ** interface is only available if SQLITE_CHECK_PAGES is defined when the 
8473 ** library is built.
8474 */
8475 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
8476 #endif
8477
8478 /* Set and get the suggested cache-size for the specified pager-cache.
8479 **
8480 ** If no global maximum is configured, then the system attempts to limit
8481 ** the total number of pages cached by purgeable pager-caches to the sum
8482 ** of the suggested cache-sizes.
8483 */
8484 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
8485 #ifdef SQLITE_TEST
8486 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
8487 #endif
8488
8489 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
8490 /* Try to return memory used by the pcache module to the main memory heap */
8491 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
8492 #endif
8493
8494 #ifdef SQLITE_TEST
8495 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
8496 #endif
8497
8498 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
8499
8500 #endif /* _PCACHE_H_ */
8501
8502 /************** End of pcache.h **********************************************/
8503 /************** Continuing where we left off in sqliteInt.h ******************/
8504
8505 /************** Include os.h in the middle of sqliteInt.h ********************/
8506 /************** Begin file os.h **********************************************/
8507 /*
8508 ** 2001 September 16
8509 **
8510 ** The author disclaims copyright to this source code.  In place of
8511 ** a legal notice, here is a blessing:
8512 **
8513 **    May you do good and not evil.
8514 **    May you find forgiveness for yourself and forgive others.
8515 **    May you share freely, never taking more than you give.
8516 **
8517 ******************************************************************************
8518 **
8519 ** This header file (together with is companion C source-code file
8520 ** "os.c") attempt to abstract the underlying operating system so that
8521 ** the SQLite library will work on both POSIX and windows systems.
8522 **
8523 ** This header file is #include-ed by sqliteInt.h and thus ends up
8524 ** being included by every source file.
8525 */
8526 #ifndef _SQLITE_OS_H_
8527 #define _SQLITE_OS_H_
8528
8529 /*
8530 ** Figure out if we are dealing with Unix, Windows, or some other
8531 ** operating system.  After the following block of preprocess macros,
8532 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER 
8533 ** will defined to either 1 or 0.  One of the four will be 1.  The other 
8534 ** three will be 0.
8535 */
8536 #if defined(SQLITE_OS_OTHER)
8537 # if SQLITE_OS_OTHER==1
8538 #   undef SQLITE_OS_UNIX
8539 #   define SQLITE_OS_UNIX 0
8540 #   undef SQLITE_OS_WIN
8541 #   define SQLITE_OS_WIN 0
8542 #   undef SQLITE_OS_OS2
8543 #   define SQLITE_OS_OS2 0
8544 # else
8545 #   undef SQLITE_OS_OTHER
8546 # endif
8547 #endif
8548 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
8549 # define SQLITE_OS_OTHER 0
8550 # ifndef SQLITE_OS_WIN
8551 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
8552 #     define SQLITE_OS_WIN 1
8553 #     define SQLITE_OS_UNIX 0
8554 #     define SQLITE_OS_OS2 0
8555 #   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
8556 #     define SQLITE_OS_WIN 0
8557 #     define SQLITE_OS_UNIX 0
8558 #     define SQLITE_OS_OS2 1
8559 #   else
8560 #     define SQLITE_OS_WIN 0
8561 #     define SQLITE_OS_UNIX 1
8562 #     define SQLITE_OS_OS2 0
8563 #  endif
8564 # else
8565 #  define SQLITE_OS_UNIX 0
8566 #  define SQLITE_OS_OS2 0
8567 # endif
8568 #else
8569 # ifndef SQLITE_OS_WIN
8570 #  define SQLITE_OS_WIN 0
8571 # endif
8572 #endif
8573
8574 /*
8575 ** Determine if we are dealing with WindowsCE - which has a much
8576 ** reduced API.
8577 */
8578 #if defined(_WIN32_WCE)
8579 # define SQLITE_OS_WINCE 1
8580 #else
8581 # define SQLITE_OS_WINCE 0
8582 #endif
8583
8584
8585 /*
8586 ** Define the maximum size of a temporary filename
8587 */
8588 #if SQLITE_OS_WIN
8589 # include <windows.h>
8590 # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
8591 #elif SQLITE_OS_OS2
8592 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
8593 #  include <os2safe.h> /* has to be included before os2.h for linking to work */
8594 # endif
8595 # define INCL_DOSDATETIME
8596 # define INCL_DOSFILEMGR
8597 # define INCL_DOSERRORS
8598 # define INCL_DOSMISC
8599 # define INCL_DOSPROCESS
8600 # define INCL_DOSMODULEMGR
8601 # define INCL_DOSSEMAPHORES
8602 # include <os2.h>
8603 # include <uconv.h>
8604 # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
8605 #else
8606 # define SQLITE_TEMPNAME_SIZE 200
8607 #endif
8608
8609 /* If the SET_FULLSYNC macro is not defined above, then make it
8610 ** a no-op
8611 */
8612 #ifndef SET_FULLSYNC
8613 # define SET_FULLSYNC(x,y)
8614 #endif
8615
8616 /*
8617 ** The default size of a disk sector
8618 */
8619 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
8620 # define SQLITE_DEFAULT_SECTOR_SIZE 512
8621 #endif
8622
8623 /*
8624 ** Temporary files are named starting with this prefix followed by 16 random
8625 ** alphanumeric characters, and no file extension. They are stored in the
8626 ** OS's standard temporary file directory, and are deleted prior to exit.
8627 ** If sqlite is being embedded in another program, you may wish to change the
8628 ** prefix to reflect your program's name, so that if your program exits
8629 ** prematurely, old temporary files can be easily identified. This can be done
8630 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
8631 **
8632 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
8633 ** Mcafee started using SQLite in their anti-virus product and it
8634 ** started putting files with the "sqlite" name in the c:/temp folder.
8635 ** This annoyed many windows users.  Those users would then do a 
8636 ** Google search for "sqlite", find the telephone numbers of the
8637 ** developers and call to wake them up at night and complain.
8638 ** For this reason, the default name prefix is changed to be "sqlite" 
8639 ** spelled backwards.  So the temp files are still identified, but
8640 ** anybody smart enough to figure out the code is also likely smart
8641 ** enough to know that calling the developer will not help get rid
8642 ** of the file.
8643 */
8644 #ifndef SQLITE_TEMP_FILE_PREFIX
8645 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
8646 #endif
8647
8648 /*
8649 ** The following values may be passed as the second argument to
8650 ** sqlite3OsLock(). The various locks exhibit the following semantics:
8651 **
8652 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
8653 ** RESERVED:  A single process may hold a RESERVED lock on a file at
8654 **            any time. Other processes may hold and obtain new SHARED locks.
8655 ** PENDING:   A single process may hold a PENDING lock on a file at
8656 **            any one time. Existing SHARED locks may persist, but no new
8657 **            SHARED locks may be obtained by other processes.
8658 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
8659 **
8660 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
8661 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
8662 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
8663 ** sqlite3OsLock().
8664 */
8665 #define NO_LOCK         0
8666 #define SHARED_LOCK     1
8667 #define RESERVED_LOCK   2
8668 #define PENDING_LOCK    3
8669 #define EXCLUSIVE_LOCK  4
8670
8671 /*
8672 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
8673 **
8674 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
8675 ** those functions are not available.  So we use only LockFile() and
8676 ** UnlockFile().
8677 **
8678 ** LockFile() prevents not just writing but also reading by other processes.
8679 ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
8680 ** byte out of a specific range of bytes. The lock byte is obtained at 
8681 ** random so two separate readers can probably access the file at the 
8682 ** same time, unless they are unlucky and choose the same lock byte.
8683 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
8684 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
8685 ** a single byte of the file that is designated as the reserved lock byte.
8686 ** A PENDING_LOCK is obtained by locking a designated byte different from
8687 ** the RESERVED_LOCK byte.
8688 **
8689 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
8690 ** which means we can use reader/writer locks.  When reader/writer locks
8691 ** are used, the lock is placed on the same range of bytes that is used
8692 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
8693 ** will support two or more Win95 readers or two or more WinNT readers.
8694 ** But a single Win95 reader will lock out all WinNT readers and a single
8695 ** WinNT reader will lock out all other Win95 readers.
8696 **
8697 ** The following #defines specify the range of bytes used for locking.
8698 ** SHARED_SIZE is the number of bytes available in the pool from which
8699 ** a random byte is selected for a shared lock.  The pool of bytes for
8700 ** shared locks begins at SHARED_FIRST. 
8701 **
8702 ** The same locking strategy and
8703 ** byte ranges are used for Unix.  This leaves open the possiblity of having
8704 ** clients on win95, winNT, and unix all talking to the same shared file
8705 ** and all locking correctly.  To do so would require that samba (or whatever
8706 ** tool is being used for file sharing) implements locks correctly between
8707 ** windows and unix.  I'm guessing that isn't likely to happen, but by
8708 ** using the same locking range we are at least open to the possibility.
8709 **
8710 ** Locking in windows is manditory.  For this reason, we cannot store
8711 ** actual data in the bytes used for locking.  The pager never allocates
8712 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
8713 ** that all locks will fit on a single page even at the minimum page size.
8714 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
8715 ** is set high so that we don't have to allocate an unused page except
8716 ** for very large databases.  But one should test the page skipping logic 
8717 ** by setting PENDING_BYTE low and running the entire regression suite.
8718 **
8719 ** Changing the value of PENDING_BYTE results in a subtly incompatible
8720 ** file format.  Depending on how it is changed, you might not notice
8721 ** the incompatibility right away, even running a full regression test.
8722 ** The default location of PENDING_BYTE is the first byte past the
8723 ** 1GB boundary.
8724 **
8725 */
8726 #ifdef SQLITE_OMIT_WSD
8727 # define PENDING_BYTE     (0x40000000)
8728 #else
8729 # define PENDING_BYTE      sqlite3PendingByte
8730 #endif
8731 #define RESERVED_BYTE     (PENDING_BYTE+1)
8732 #define SHARED_FIRST      (PENDING_BYTE+2)
8733 #define SHARED_SIZE       510
8734
8735 /*
8736 ** Wrapper around OS specific sqlite3_os_init() function.
8737 */
8738 SQLITE_PRIVATE int sqlite3OsInit(void);
8739
8740 /* 
8741 ** Functions for accessing sqlite3_file methods 
8742 */
8743 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
8744 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
8745 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
8746 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
8747 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
8748 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
8749 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
8750 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
8751 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
8752 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
8753 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
8754 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
8755 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
8756 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
8757 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
8758 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
8759 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
8760
8761 /* 
8762 ** Functions for accessing sqlite3_vfs methods 
8763 */
8764 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
8765 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
8766 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
8767 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
8768 #ifndef SQLITE_OMIT_LOAD_EXTENSION
8769 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
8770 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
8771 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
8772 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
8773 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
8774 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
8775 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
8776 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
8777
8778 /*
8779 ** Convenience functions for opening and closing files using 
8780 ** sqlite3_malloc() to obtain space for the file-handle structure.
8781 */
8782 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
8783 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
8784
8785 #endif /* _SQLITE_OS_H_ */
8786
8787 /************** End of os.h **************************************************/
8788 /************** Continuing where we left off in sqliteInt.h ******************/
8789 /************** Include mutex.h in the middle of sqliteInt.h *****************/
8790 /************** Begin file mutex.h *******************************************/
8791 /*
8792 ** 2007 August 28
8793 **
8794 ** The author disclaims copyright to this source code.  In place of
8795 ** a legal notice, here is a blessing:
8796 **
8797 **    May you do good and not evil.
8798 **    May you find forgiveness for yourself and forgive others.
8799 **    May you share freely, never taking more than you give.
8800 **
8801 *************************************************************************
8802 **
8803 ** This file contains the common header for all mutex implementations.
8804 ** The sqliteInt.h header #includes this file so that it is available
8805 ** to all source files.  We break it out in an effort to keep the code
8806 ** better organized.
8807 **
8808 ** NOTE:  source files should *not* #include this header file directly.
8809 ** Source files should #include the sqliteInt.h file and let that file
8810 ** include this one indirectly.
8811 */
8812
8813
8814 /*
8815 ** Figure out what version of the code to use.  The choices are
8816 **
8817 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
8818 **                             mutexes implemention cannot be overridden
8819 **                             at start-time.
8820 **
8821 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
8822 **                             mutual exclusion is provided.  But this
8823 **                             implementation can be overridden at
8824 **                             start-time.
8825 **
8826 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
8827 **
8828 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
8829 **
8830 **   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
8831 */
8832 #if !SQLITE_THREADSAFE
8833 # define SQLITE_MUTEX_OMIT
8834 #endif
8835 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
8836 #  if SQLITE_OS_UNIX
8837 #    define SQLITE_MUTEX_PTHREADS
8838 #  elif SQLITE_OS_WIN
8839 #    define SQLITE_MUTEX_W32
8840 #  elif SQLITE_OS_OS2
8841 #    define SQLITE_MUTEX_OS2
8842 #  else
8843 #    define SQLITE_MUTEX_NOOP
8844 #  endif
8845 #endif
8846
8847 #ifdef SQLITE_MUTEX_OMIT
8848 /*
8849 ** If this is a no-op implementation, implement everything as macros.
8850 */
8851 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
8852 #define sqlite3_mutex_free(X)
8853 #define sqlite3_mutex_enter(X)
8854 #define sqlite3_mutex_try(X)      SQLITE_OK
8855 #define sqlite3_mutex_leave(X)
8856 #define sqlite3_mutex_held(X)     ((void)(X),1)
8857 #define sqlite3_mutex_notheld(X)  ((void)(X),1)
8858 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
8859 #define sqlite3MutexInit()        SQLITE_OK
8860 #define sqlite3MutexEnd()
8861 #endif /* defined(SQLITE_MUTEX_OMIT) */
8862
8863 /************** End of mutex.h ***********************************************/
8864 /************** Continuing where we left off in sqliteInt.h ******************/
8865
8866
8867 /*
8868 ** Each database file to be accessed by the system is an instance
8869 ** of the following structure.  There are normally two of these structures
8870 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
8871 ** aDb[1] is the database file used to hold temporary tables.  Additional
8872 ** databases may be attached.
8873 */
8874 struct Db {
8875   char *zName;         /* Name of this database */
8876   Btree *pBt;          /* The B*Tree structure for this database file */
8877   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
8878   u8 safety_level;     /* How aggressive at syncing data to disk */
8879   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
8880 };
8881
8882 /*
8883 ** An instance of the following structure stores a database schema.
8884 */
8885 struct Schema {
8886   int schema_cookie;   /* Database schema version number for this file */
8887   Hash tblHash;        /* All tables indexed by name */
8888   Hash idxHash;        /* All (named) indices indexed by name */
8889   Hash trigHash;       /* All triggers indexed by name */
8890   Hash fkeyHash;       /* All foreign keys by referenced table name */
8891   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
8892   u8 file_format;      /* Schema format version for this file */
8893   u8 enc;              /* Text encoding used by this database */
8894   u16 flags;           /* Flags associated with this schema */
8895   int cache_size;      /* Number of pages to use in the cache */
8896 };
8897
8898 /*
8899 ** These macros can be used to test, set, or clear bits in the 
8900 ** Db.pSchema->flags field.
8901 */
8902 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
8903 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
8904 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
8905 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
8906
8907 /*
8908 ** Allowed values for the DB.pSchema->flags field.
8909 **
8910 ** The DB_SchemaLoaded flag is set after the database schema has been
8911 ** read into internal hash tables.
8912 **
8913 ** DB_UnresetViews means that one or more views have column names that
8914 ** have been filled out.  If the schema changes, these column names might
8915 ** changes and so the view will need to be reset.
8916 */
8917 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
8918 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
8919 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
8920
8921 /*
8922 ** The number of different kinds of things that can be limited
8923 ** using the sqlite3_limit() interface.
8924 */
8925 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
8926
8927 /*
8928 ** Lookaside malloc is a set of fixed-size buffers that can be used
8929 ** to satisfy small transient memory allocation requests for objects
8930 ** associated with a particular database connection.  The use of
8931 ** lookaside malloc provides a significant performance enhancement
8932 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
8933 ** SQL statements.
8934 **
8935 ** The Lookaside structure holds configuration information about the
8936 ** lookaside malloc subsystem.  Each available memory allocation in
8937 ** the lookaside subsystem is stored on a linked list of LookasideSlot
8938 ** objects.
8939 **
8940 ** Lookaside allocations are only allowed for objects that are associated
8941 ** with a particular database connection.  Hence, schema information cannot
8942 ** be stored in lookaside because in shared cache mode the schema information
8943 ** is shared by multiple database connections.  Therefore, while parsing
8944 ** schema information, the Lookaside.bEnabled flag is cleared so that
8945 ** lookaside allocations are not used to construct the schema objects.
8946 */
8947 struct Lookaside {
8948   u16 sz;                 /* Size of each buffer in bytes */
8949   u8 bEnabled;            /* False to disable new lookaside allocations */
8950   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
8951   int nOut;               /* Number of buffers currently checked out */
8952   int mxOut;              /* Highwater mark for nOut */
8953   int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
8954   LookasideSlot *pFree;   /* List of available buffers */
8955   void *pStart;           /* First byte of available memory space */
8956   void *pEnd;             /* First byte past end of available space */
8957 };
8958 struct LookasideSlot {
8959   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
8960 };
8961
8962 /*
8963 ** A hash table for function definitions.
8964 **
8965 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
8966 ** Collisions are on the FuncDef.pHash chain.
8967 */
8968 struct FuncDefHash {
8969   FuncDef *a[23];       /* Hash table for functions */
8970 };
8971
8972 /*
8973 ** Each database connection is an instance of the following structure.
8974 **
8975 ** The sqlite.lastRowid records the last insert rowid generated by an
8976 ** insert statement.  Inserts on views do not affect its value.  Each
8977 ** trigger has its own context, so that lastRowid can be updated inside
8978 ** triggers as usual.  The previous value will be restored once the trigger
8979 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
8980 ** longer (since after version 2.8.12) reset to -1.
8981 **
8982 ** The sqlite.nChange does not count changes within triggers and keeps no
8983 ** context.  It is reset at start of sqlite3_exec.
8984 ** The sqlite.lsChange represents the number of changes made by the last
8985 ** insert, update, or delete statement.  It remains constant throughout the
8986 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
8987 ** context stack just like lastRowid so that the count of changes
8988 ** within a trigger is not seen outside the trigger.  Changes to views do not
8989 ** affect the value of lsChange.
8990 ** The sqlite.csChange keeps track of the number of current changes (since
8991 ** the last statement) and is used to update sqlite_lsChange.
8992 **
8993 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
8994 ** store the most recent error code and, if applicable, string. The
8995 ** internal function sqlite3Error() is used to set these variables
8996 ** consistently.
8997 */
8998 struct sqlite3 {
8999   sqlite3_vfs *pVfs;            /* OS Interface */
9000   int nDb;                      /* Number of backends currently in use */
9001   Db *aDb;                      /* All backends */
9002   int flags;                    /* Miscellaneous flags. See below */
9003   int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
9004   int errCode;                  /* Most recent error code (SQLITE_*) */
9005   int errMask;                  /* & result codes with this before returning */
9006   u8 autoCommit;                /* The auto-commit flag. */
9007   u8 temp_store;                /* 1: file 2: memory 0: default */
9008   u8 mallocFailed;              /* True if we have seen a malloc failure */
9009   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
9010   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
9011   u8 suppressErr;               /* Do not issue error messages if true */
9012   int nextPagesize;             /* Pagesize after VACUUM if >0 */
9013   int nTable;                   /* Number of tables in the database */
9014   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
9015   i64 lastRowid;                /* ROWID of most recent insert (see above) */
9016   u32 magic;                    /* Magic number for detect library misuse */
9017   int nChange;                  /* Value returned by sqlite3_changes() */
9018   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
9019   sqlite3_mutex *mutex;         /* Connection mutex */
9020   int aLimit[SQLITE_N_LIMIT];   /* Limits */
9021   struct sqlite3InitInfo {      /* Information used during initialization */
9022     int iDb;                    /* When back is being initialized */
9023     int newTnum;                /* Rootpage of table being initialized */
9024     u8 busy;                    /* TRUE if currently initializing */
9025     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
9026   } init;
9027   int nExtension;               /* Number of loaded extensions */
9028   void **aExtension;            /* Array of shared library handles */
9029   struct Vdbe *pVdbe;           /* List of active virtual machines */
9030   int activeVdbeCnt;            /* Number of VDBEs currently executing */
9031   int writeVdbeCnt;             /* Number of active VDBEs that are writing */
9032   int vdbeExecCnt;              /* Number of nested calls to VdbeExec() */
9033   void (*xTrace)(void*,const char*);        /* Trace function */
9034   void *pTraceArg;                          /* Argument to the trace function */
9035   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
9036   void *pProfileArg;                        /* Argument to profile function */
9037   void *pCommitArg;                 /* Argument to xCommitCallback() */   
9038   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
9039   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
9040   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
9041   void *pUpdateArg;
9042   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
9043 #ifndef SQLITE_OMIT_WAL
9044   int (*xWalCallback)(void *, sqlite3 *, const char *, int);
9045   void *pWalArg;
9046 #endif
9047   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
9048   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
9049   void *pCollNeededArg;
9050   sqlite3_value *pErr;          /* Most recent error message */
9051   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
9052   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
9053   union {
9054     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
9055     double notUsed1;            /* Spacer */
9056   } u1;
9057   Lookaside lookaside;          /* Lookaside malloc configuration */
9058 #ifndef SQLITE_OMIT_AUTHORIZATION
9059   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
9060                                 /* Access authorization function */
9061   void *pAuthArg;               /* 1st argument to the access auth function */
9062 #endif
9063 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9064   int (*xProgress)(void *);     /* The progress callback */
9065   void *pProgressArg;           /* Argument to the progress callback */
9066   int nProgressOps;             /* Number of opcodes for progress callback */
9067 #endif
9068 #ifndef SQLITE_OMIT_VIRTUALTABLE
9069   Hash aModule;                 /* populated by sqlite3_create_module() */
9070   Table *pVTab;                 /* vtab with active Connect/Create method */
9071   VTable **aVTrans;             /* Virtual tables with open transactions */
9072   int nVTrans;                  /* Allocated size of aVTrans */
9073   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
9074 #endif
9075   FuncDefHash aFunc;            /* Hash table of connection functions */
9076   Hash aCollSeq;                /* All collating sequences */
9077   BusyHandler busyHandler;      /* Busy callback */
9078   int busyTimeout;              /* Busy handler timeout, in msec */
9079   Db aDbStatic[2];              /* Static space for the 2 default backends */
9080   Savepoint *pSavepoint;        /* List of active savepoints */
9081   int nSavepoint;               /* Number of non-transaction savepoints */
9082   int nStatement;               /* Number of nested statement-transactions  */
9083   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
9084   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
9085   int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
9086
9087 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
9088   /* The following variables are all protected by the STATIC_MASTER 
9089   ** mutex, not by sqlite3.mutex. They are used by code in notify.c. 
9090   **
9091   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
9092   ** unlock so that it can proceed.
9093   **
9094   ** When X.pBlockingConnection==Y, that means that something that X tried
9095   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
9096   ** held by Y.
9097   */
9098   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
9099   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
9100   void *pUnlockArg;                     /* Argument to xUnlockNotify */
9101   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
9102   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
9103 #endif
9104 };
9105
9106 /*
9107 ** A macro to discover the encoding of a database.
9108 */
9109 #define ENC(db) ((db)->aDb[0].pSchema->enc)
9110
9111 /*
9112 ** Possible values for the sqlite3.flags.
9113 */
9114 #define SQLITE_VdbeTrace      0x00000100  /* True to trace VDBE execution */
9115 #define SQLITE_InternChanges  0x00000200  /* Uncommitted Hash table changes */
9116 #define SQLITE_FullColNames   0x00000400  /* Show full column names on SELECT */
9117 #define SQLITE_ShortColNames  0x00000800  /* Show short columns names */
9118 #define SQLITE_CountRows      0x00001000  /* Count rows changed by INSERT, */
9119                                           /*   DELETE, or UPDATE and return */
9120                                           /*   the count using a callback. */
9121 #define SQLITE_NullCallback   0x00002000  /* Invoke the callback once if the */
9122                                           /*   result set is empty */
9123 #define SQLITE_SqlTrace       0x00004000  /* Debug print SQL as it executes */
9124 #define SQLITE_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
9125 #define SQLITE_WriteSchema    0x00010000  /* OK to update SQLITE_MASTER */
9126 #define SQLITE_NoReadlock     0x00020000  /* Readlocks are omitted when 
9127                                           ** accessing read-only databases */
9128 #define SQLITE_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
9129 #define SQLITE_ReadUncommitted 0x0080000  /* For shared-cache mode */
9130 #define SQLITE_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
9131 #define SQLITE_FullFSync      0x00200000  /* Use full fsync on the backend */
9132 #define SQLITE_CkptFullFSync  0x00400000  /* Use full fsync for checkpoint */
9133 #define SQLITE_RecoveryMode   0x00800000  /* Ignore schema errors */
9134 #define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
9135 #define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
9136 #define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
9137 #define SQLITE_AutoIndex      0x08000000  /* Enable automatic indexes */
9138 #define SQLITE_PreferBuiltin  0x10000000  /* Preference to built-in funcs */
9139 #define SQLITE_LoadExtension  0x20000000  /* Enable load_extension */
9140
9141 /*
9142 ** Bits of the sqlite3.flags field that are used by the
9143 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
9144 ** These must be the low-order bits of the flags field.
9145 */
9146 #define SQLITE_QueryFlattener 0x01        /* Disable query flattening */
9147 #define SQLITE_ColumnCache    0x02        /* Disable the column cache */
9148 #define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
9149 #define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
9150 #define SQLITE_IndexCover     0x10        /* Disable index covering table */
9151 #define SQLITE_GroupByOrder   0x20        /* Disable GROUPBY cover of ORDERBY */
9152 #define SQLITE_FactorOutConst 0x40        /* Disable factoring out constants */
9153 #define SQLITE_OptMask        0xff        /* Mask of all disablable opts */
9154
9155 /*
9156 ** Possible values for the sqlite.magic field.
9157 ** The numbers are obtained at random and have no special meaning, other
9158 ** than being distinct from one another.
9159 */
9160 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
9161 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
9162 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
9163 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
9164 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
9165
9166 /*
9167 ** Each SQL function is defined by an instance of the following
9168 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
9169 ** hash table.  When multiple functions have the same name, the hash table
9170 ** points to a linked list of these structures.
9171 */
9172 struct FuncDef {
9173   i16 nArg;            /* Number of arguments.  -1 means unlimited */
9174   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
9175   u8 flags;            /* Some combination of SQLITE_FUNC_* */
9176   void *pUserData;     /* User data parameter */
9177   FuncDef *pNext;      /* Next function with same name */
9178   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
9179   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
9180   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
9181   char *zName;         /* SQL name of the function. */
9182   FuncDef *pHash;      /* Next with a different name but the same hash */
9183   FuncDestructor *pDestructor;   /* Reference counted destructor function */
9184 };
9185
9186 /*
9187 ** This structure encapsulates a user-function destructor callback (as
9188 ** configured using create_function_v2()) and a reference counter. When
9189 ** create_function_v2() is called to create a function with a destructor,
9190 ** a single object of this type is allocated. FuncDestructor.nRef is set to 
9191 ** the number of FuncDef objects created (either 1 or 3, depending on whether
9192 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
9193 ** member of each of the new FuncDef objects is set to point to the allocated
9194 ** FuncDestructor.
9195 **
9196 ** Thereafter, when one of the FuncDef objects is deleted, the reference
9197 ** count on this object is decremented. When it reaches 0, the destructor
9198 ** is invoked and the FuncDestructor structure freed.
9199 */
9200 struct FuncDestructor {
9201   int nRef;
9202   void (*xDestroy)(void *);
9203   void *pUserData;
9204 };
9205
9206 /*
9207 ** Possible values for FuncDef.flags
9208 */
9209 #define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
9210 #define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
9211 #define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
9212 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
9213 #define SQLITE_FUNC_PRIVATE  0x10 /* Allowed for internal use only */
9214 #define SQLITE_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */
9215 #define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
9216
9217 /*
9218 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
9219 ** used to create the initializers for the FuncDef structures.
9220 **
9221 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
9222 **     Used to create a scalar function definition of a function zName 
9223 **     implemented by C function xFunc that accepts nArg arguments. The
9224 **     value passed as iArg is cast to a (void*) and made available
9225 **     as the user-data (sqlite3_user_data()) for the function. If 
9226 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
9227 **
9228 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
9229 **     Used to create an aggregate function definition implemented by
9230 **     the C functions xStep and xFinal. The first four parameters
9231 **     are interpreted in the same way as the first 4 parameters to
9232 **     FUNCTION().
9233 **
9234 **   LIKEFUNC(zName, nArg, pArg, flags)
9235 **     Used to create a scalar function definition of a function zName 
9236 **     that accepts nArg arguments and is implemented by a call to C 
9237 **     function likeFunc. Argument pArg is cast to a (void *) and made
9238 **     available as the function user-data (sqlite3_user_data()). The
9239 **     FuncDef.flags variable is set to the value passed as the flags
9240 **     parameter.
9241 */
9242 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
9243   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9244    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
9245 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
9246   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9247    pArg, 0, xFunc, 0, 0, #zName, 0, 0}
9248 #define LIKEFUNC(zName, nArg, arg, flags) \
9249   {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
9250 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
9251   {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
9252    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
9253
9254 /*
9255 ** All current savepoints are stored in a linked list starting at
9256 ** sqlite3.pSavepoint. The first element in the list is the most recently
9257 ** opened savepoint. Savepoints are added to the list by the vdbe
9258 ** OP_Savepoint instruction.
9259 */
9260 struct Savepoint {
9261   char *zName;                        /* Savepoint name (nul-terminated) */
9262   i64 nDeferredCons;                  /* Number of deferred fk violations */
9263   Savepoint *pNext;                   /* Parent savepoint (if any) */
9264 };
9265
9266 /*
9267 ** The following are used as the second parameter to sqlite3Savepoint(),
9268 ** and as the P1 argument to the OP_Savepoint instruction.
9269 */
9270 #define SAVEPOINT_BEGIN      0
9271 #define SAVEPOINT_RELEASE    1
9272 #define SAVEPOINT_ROLLBACK   2
9273
9274
9275 /*
9276 ** Each SQLite module (virtual table definition) is defined by an
9277 ** instance of the following structure, stored in the sqlite3.aModule
9278 ** hash table.
9279 */
9280 struct Module {
9281   const sqlite3_module *pModule;       /* Callback pointers */
9282   const char *zName;                   /* Name passed to create_module() */
9283   void *pAux;                          /* pAux passed to create_module() */
9284   void (*xDestroy)(void *);            /* Module destructor function */
9285 };
9286
9287 /*
9288 ** information about each column of an SQL table is held in an instance
9289 ** of this structure.
9290 */
9291 struct Column {
9292   char *zName;     /* Name of this column */
9293   Expr *pDflt;     /* Default value of this column */
9294   char *zDflt;     /* Original text of the default value */
9295   char *zType;     /* Data type for this column */
9296   char *zColl;     /* Collating sequence.  If NULL, use the default */
9297   u8 notNull;      /* True if there is a NOT NULL constraint */
9298   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
9299   char affinity;   /* One of the SQLITE_AFF_... values */
9300 #ifndef SQLITE_OMIT_VIRTUALTABLE
9301   u8 isHidden;     /* True if this column is 'hidden' */
9302 #endif
9303 };
9304
9305 /*
9306 ** A "Collating Sequence" is defined by an instance of the following
9307 ** structure. Conceptually, a collating sequence consists of a name and
9308 ** a comparison routine that defines the order of that sequence.
9309 **
9310 ** There may two separate implementations of the collation function, one
9311 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
9312 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
9313 ** native byte order. When a collation sequence is invoked, SQLite selects
9314 ** the version that will require the least expensive encoding
9315 ** translations, if any.
9316 **
9317 ** The CollSeq.pUser member variable is an extra parameter that passed in
9318 ** as the first argument to the UTF-8 comparison function, xCmp.
9319 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
9320 ** xCmp16.
9321 **
9322 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
9323 ** collating sequence is undefined.  Indices built on an undefined
9324 ** collating sequence may not be read or written.
9325 */
9326 struct CollSeq {
9327   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
9328   u8 enc;               /* Text encoding handled by xCmp() */
9329   u8 type;              /* One of the SQLITE_COLL_... values below */
9330   void *pUser;          /* First argument to xCmp() */
9331   int (*xCmp)(void*,int, const void*, int, const void*);
9332   void (*xDel)(void*);  /* Destructor for pUser */
9333 };
9334
9335 /*
9336 ** Allowed values of CollSeq.type:
9337 */
9338 #define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
9339 #define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
9340 #define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
9341 #define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
9342
9343 /*
9344 ** A sort order can be either ASC or DESC.
9345 */
9346 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
9347 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
9348
9349 /*
9350 ** Column affinity types.
9351 **
9352 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
9353 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
9354 ** the speed a little by numbering the values consecutively.  
9355 **
9356 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
9357 ** when multiple affinity types are concatenated into a string and
9358 ** used as the P4 operand, they will be more readable.
9359 **
9360 ** Note also that the numeric types are grouped together so that testing
9361 ** for a numeric type is a single comparison.
9362 */
9363 #define SQLITE_AFF_TEXT     'a'
9364 #define SQLITE_AFF_NONE     'b'
9365 #define SQLITE_AFF_NUMERIC  'c'
9366 #define SQLITE_AFF_INTEGER  'd'
9367 #define SQLITE_AFF_REAL     'e'
9368
9369 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
9370
9371 /*
9372 ** The SQLITE_AFF_MASK values masks off the significant bits of an
9373 ** affinity value. 
9374 */
9375 #define SQLITE_AFF_MASK     0x67
9376
9377 /*
9378 ** Additional bit values that can be ORed with an affinity without
9379 ** changing the affinity.
9380 */
9381 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
9382 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
9383 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
9384
9385 /*
9386 ** An object of this type is created for each virtual table present in
9387 ** the database schema. 
9388 **
9389 ** If the database schema is shared, then there is one instance of this
9390 ** structure for each database connection (sqlite3*) that uses the shared
9391 ** schema. This is because each database connection requires its own unique
9392 ** instance of the sqlite3_vtab* handle used to access the virtual table 
9393 ** implementation. sqlite3_vtab* handles can not be shared between 
9394 ** database connections, even when the rest of the in-memory database 
9395 ** schema is shared, as the implementation often stores the database
9396 ** connection handle passed to it via the xConnect() or xCreate() method
9397 ** during initialization internally. This database connection handle may
9398 ** then used by the virtual table implementation to access real tables 
9399 ** within the database. So that they appear as part of the callers 
9400 ** transaction, these accesses need to be made via the same database 
9401 ** connection as that used to execute SQL operations on the virtual table.
9402 **
9403 ** All VTable objects that correspond to a single table in a shared
9404 ** database schema are initially stored in a linked-list pointed to by
9405 ** the Table.pVTable member variable of the corresponding Table object.
9406 ** When an sqlite3_prepare() operation is required to access the virtual
9407 ** table, it searches the list for the VTable that corresponds to the
9408 ** database connection doing the preparing so as to use the correct
9409 ** sqlite3_vtab* handle in the compiled query.
9410 **
9411 ** When an in-memory Table object is deleted (for example when the
9412 ** schema is being reloaded for some reason), the VTable objects are not 
9413 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed 
9414 ** immediately. Instead, they are moved from the Table.pVTable list to
9415 ** another linked list headed by the sqlite3.pDisconnect member of the
9416 ** corresponding sqlite3 structure. They are then deleted/xDisconnected 
9417 ** next time a statement is prepared using said sqlite3*. This is done
9418 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
9419 ** Refer to comments above function sqlite3VtabUnlockList() for an
9420 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
9421 ** list without holding the corresponding sqlite3.mutex mutex.
9422 **
9423 ** The memory for objects of this type is always allocated by 
9424 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as 
9425 ** the first argument.
9426 */
9427 struct VTable {
9428   sqlite3 *db;              /* Database connection associated with this table */
9429   Module *pMod;             /* Pointer to module implementation */
9430   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
9431   int nRef;                 /* Number of pointers to this structure */
9432   VTable *pNext;            /* Next in linked list (see above) */
9433 };
9434
9435 /*
9436 ** Each SQL table is represented in memory by an instance of the
9437 ** following structure.
9438 **
9439 ** Table.zName is the name of the table.  The case of the original
9440 ** CREATE TABLE statement is stored, but case is not significant for
9441 ** comparisons.
9442 **
9443 ** Table.nCol is the number of columns in this table.  Table.aCol is a
9444 ** pointer to an array of Column structures, one for each column.
9445 **
9446 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
9447 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
9448 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
9449 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
9450 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
9451 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
9452 ** the table has any PRIMARY KEY, INTEGER or otherwise.
9453 **
9454 ** Table.tnum is the page number for the root BTree page of the table in the
9455 ** database file.  If Table.iDb is the index of the database table backend
9456 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
9457 ** holds temporary tables and indices.  If TF_Ephemeral is set
9458 ** then the table is stored in a file that is automatically deleted
9459 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
9460 ** refers VDBE cursor number that holds the table open, not to the root
9461 ** page number.  Transient tables are used to hold the results of a
9462 ** sub-query that appears instead of a real table name in the FROM clause 
9463 ** of a SELECT statement.
9464 */
9465 struct Table {
9466   char *zName;         /* Name of the table or view */
9467   int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
9468   int nCol;            /* Number of columns in this table */
9469   Column *aCol;        /* Information about each column */
9470   Index *pIndex;       /* List of SQL indexes on this table. */
9471   int tnum;            /* Root BTree node for this table (see note above) */
9472   unsigned nRowEst;    /* Estimated rows in table - from sqlite_stat1 table */
9473   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
9474   u16 nRef;            /* Number of pointers to this Table */
9475   u8 tabFlags;         /* Mask of TF_* values */
9476   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
9477   FKey *pFKey;         /* Linked list of all foreign keys in this table */
9478   char *zColAff;       /* String defining the affinity of each column */
9479 #ifndef SQLITE_OMIT_CHECK
9480   Expr *pCheck;        /* The AND of all CHECK constraints */
9481 #endif
9482 #ifndef SQLITE_OMIT_ALTERTABLE
9483   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
9484 #endif
9485 #ifndef SQLITE_OMIT_VIRTUALTABLE
9486   VTable *pVTable;     /* List of VTable objects. */
9487   int nModuleArg;      /* Number of arguments to the module */
9488   char **azModuleArg;  /* Text of all module args. [0] is module name */
9489 #endif
9490   Trigger *pTrigger;   /* List of triggers stored in pSchema */
9491   Schema *pSchema;     /* Schema that contains this table */
9492   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
9493 };
9494
9495 /*
9496 ** Allowed values for Tabe.tabFlags.
9497 */
9498 #define TF_Readonly        0x01    /* Read-only system table */
9499 #define TF_Ephemeral       0x02    /* An ephemeral table */
9500 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
9501 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
9502 #define TF_Virtual         0x10    /* Is a virtual table */
9503 #define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
9504
9505
9506
9507 /*
9508 ** Test to see whether or not a table is a virtual table.  This is
9509 ** done as a macro so that it will be optimized out when virtual
9510 ** table support is omitted from the build.
9511 */
9512 #ifndef SQLITE_OMIT_VIRTUALTABLE
9513 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
9514 #  define IsHiddenColumn(X) ((X)->isHidden)
9515 #else
9516 #  define IsVirtual(X)      0
9517 #  define IsHiddenColumn(X) 0
9518 #endif
9519
9520 /*
9521 ** Each foreign key constraint is an instance of the following structure.
9522 **
9523 ** A foreign key is associated with two tables.  The "from" table is
9524 ** the table that contains the REFERENCES clause that creates the foreign
9525 ** key.  The "to" table is the table that is named in the REFERENCES clause.
9526 ** Consider this example:
9527 **
9528 **     CREATE TABLE ex1(
9529 **       a INTEGER PRIMARY KEY,
9530 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
9531 **     );
9532 **
9533 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
9534 **
9535 ** Each REFERENCES clause generates an instance of the following structure
9536 ** which is attached to the from-table.  The to-table need not exist when
9537 ** the from-table is created.  The existence of the to-table is not checked.
9538 */
9539 struct FKey {
9540   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
9541   FKey *pNextFrom;  /* Next foreign key in pFrom */
9542   char *zTo;        /* Name of table that the key points to (aka: Parent) */
9543   FKey *pNextTo;    /* Next foreign key on table named zTo */
9544   FKey *pPrevTo;    /* Previous foreign key on table named zTo */
9545   int nCol;         /* Number of columns in this key */
9546   /* EV: R-30323-21917 */
9547   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
9548   u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
9549   Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
9550   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
9551     int iFrom;         /* Index of column in pFrom */
9552     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
9553   } aCol[1];        /* One entry for each of nCol column s */
9554 };
9555
9556 /*
9557 ** SQLite supports many different ways to resolve a constraint
9558 ** error.  ROLLBACK processing means that a constraint violation
9559 ** causes the operation in process to fail and for the current transaction
9560 ** to be rolled back.  ABORT processing means the operation in process
9561 ** fails and any prior changes from that one operation are backed out,
9562 ** but the transaction is not rolled back.  FAIL processing means that
9563 ** the operation in progress stops and returns an error code.  But prior
9564 ** changes due to the same operation are not backed out and no rollback
9565 ** occurs.  IGNORE means that the particular row that caused the constraint
9566 ** error is not inserted or updated.  Processing continues and no error
9567 ** is returned.  REPLACE means that preexisting database rows that caused
9568 ** a UNIQUE constraint violation are removed so that the new insert or
9569 ** update can proceed.  Processing continues and no error is reported.
9570 **
9571 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
9572 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
9573 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
9574 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
9575 ** referenced table row is propagated into the row that holds the
9576 ** foreign key.
9577 ** 
9578 ** The following symbolic values are used to record which type
9579 ** of action to take.
9580 */
9581 #define OE_None     0   /* There is no constraint to check */
9582 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
9583 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
9584 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
9585 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
9586 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
9587
9588 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
9589 #define OE_SetNull  7   /* Set the foreign key value to NULL */
9590 #define OE_SetDflt  8   /* Set the foreign key value to its default */
9591 #define OE_Cascade  9   /* Cascade the changes */
9592
9593 #define OE_Default  99  /* Do whatever the default action is */
9594
9595
9596 /*
9597 ** An instance of the following structure is passed as the first
9598 ** argument to sqlite3VdbeKeyCompare and is used to control the 
9599 ** comparison of the two index keys.
9600 */
9601 struct KeyInfo {
9602   sqlite3 *db;        /* The database connection */
9603   u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
9604   u16 nField;         /* Number of entries in aColl[] */
9605   u8 *aSortOrder;     /* Sort order for each column.  May be NULL */
9606   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
9607 };
9608
9609 /*
9610 ** An instance of the following structure holds information about a
9611 ** single index record that has already been parsed out into individual
9612 ** values.
9613 **
9614 ** A record is an object that contains one or more fields of data.
9615 ** Records are used to store the content of a table row and to store
9616 ** the key of an index.  A blob encoding of a record is created by
9617 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
9618 ** OP_Column opcode.
9619 **
9620 ** This structure holds a record that has already been disassembled
9621 ** into its constituent fields.
9622 */
9623 struct UnpackedRecord {
9624   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
9625   u16 nField;         /* Number of entries in apMem[] */
9626   u16 flags;          /* Boolean settings.  UNPACKED_... below */
9627   i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
9628   Mem *aMem;          /* Values */
9629 };
9630
9631 /*
9632 ** Allowed values of UnpackedRecord.flags
9633 */
9634 #define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
9635 #define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
9636 #define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
9637 #define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
9638 #define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
9639 #define UNPACKED_PREFIX_SEARCH 0x0020  /* A prefix match is considered OK */
9640
9641 /*
9642 ** Each SQL index is represented in memory by an
9643 ** instance of the following structure.
9644 **
9645 ** The columns of the table that are to be indexed are described
9646 ** by the aiColumn[] field of this structure.  For example, suppose
9647 ** we have the following table and index:
9648 **
9649 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
9650 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
9651 **
9652 ** In the Table structure describing Ex1, nCol==3 because there are
9653 ** three columns in the table.  In the Index structure describing
9654 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
9655 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
9656 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
9657 ** The second column to be indexed (c1) has an index of 0 in
9658 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
9659 **
9660 ** The Index.onError field determines whether or not the indexed columns
9661 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
9662 ** it means this is not a unique index.  Otherwise it is a unique index
9663 ** and the value of Index.onError indicate the which conflict resolution 
9664 ** algorithm to employ whenever an attempt is made to insert a non-unique
9665 ** element.
9666 */
9667 struct Index {
9668   char *zName;     /* Name of this index */
9669   int nColumn;     /* Number of columns in the table used by this index */
9670   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
9671   unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
9672   Table *pTable;   /* The SQL table being indexed */
9673   int tnum;        /* Page containing root of this index in database file */
9674   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
9675   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
9676   char *zColAff;   /* String defining the affinity of each column */
9677   Index *pNext;    /* The next index associated with the same table */
9678   Schema *pSchema; /* Schema containing this index */
9679   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
9680   char **azColl;   /* Array of collation sequence names for index */
9681   IndexSample *aSample;    /* Array of SQLITE_INDEX_SAMPLES samples */
9682 };
9683
9684 /*
9685 ** Each sample stored in the sqlite_stat2 table is represented in memory 
9686 ** using a structure of this type.
9687 */
9688 struct IndexSample {
9689   union {
9690     char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
9691     double r;       /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */
9692   } u;
9693   u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
9694   u8 nByte;         /* Size in byte of text or blob. */
9695 };
9696
9697 /*
9698 ** Each token coming out of the lexer is an instance of
9699 ** this structure.  Tokens are also used as part of an expression.
9700 **
9701 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
9702 ** may contain random values.  Do not make any assumptions about Token.dyn
9703 ** and Token.n when Token.z==0.
9704 */
9705 struct Token {
9706   const char *z;     /* Text of the token.  Not NULL-terminated! */
9707   unsigned int n;    /* Number of characters in this token */
9708 };
9709
9710 /*
9711 ** An instance of this structure contains information needed to generate
9712 ** code for a SELECT that contains aggregate functions.
9713 **
9714 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
9715 ** pointer to this structure.  The Expr.iColumn field is the index in
9716 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
9717 ** code for that node.
9718 **
9719 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
9720 ** original Select structure that describes the SELECT statement.  These
9721 ** fields do not need to be freed when deallocating the AggInfo structure.
9722 */
9723 struct AggInfo {
9724   u8 directMode;          /* Direct rendering mode means take data directly
9725                           ** from source tables rather than from accumulators */
9726   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
9727                           ** than the source table */
9728   int sortingIdx;         /* Cursor number of the sorting index */
9729   ExprList *pGroupBy;     /* The group by clause */
9730   int nSortingColumn;     /* Number of columns in the sorting index */
9731   struct AggInfo_col {    /* For each column used in source tables */
9732     Table *pTab;             /* Source table */
9733     int iTable;              /* Cursor number of the source table */
9734     int iColumn;             /* Column number within the source table */
9735     int iSorterColumn;       /* Column number in the sorting index */
9736     int iMem;                /* Memory location that acts as accumulator */
9737     Expr *pExpr;             /* The original expression */
9738   } *aCol;
9739   int nColumn;            /* Number of used entries in aCol[] */
9740   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
9741   int nAccumulator;       /* Number of columns that show through to the output.
9742                           ** Additional columns are used only as parameters to
9743                           ** aggregate functions */
9744   struct AggInfo_func {   /* For each aggregate function */
9745     Expr *pExpr;             /* Expression encoding the function */
9746     FuncDef *pFunc;          /* The aggregate function implementation */
9747     int iMem;                /* Memory location that acts as accumulator */
9748     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
9749   } *aFunc;
9750   int nFunc;              /* Number of entries in aFunc[] */
9751   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
9752 };
9753
9754 /*
9755 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
9756 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
9757 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
9758 ** it uses less memory in the Expr object, which is a big memory user
9759 ** in systems with lots of prepared statements.  And few applications
9760 ** need more than about 10 or 20 variables.  But some extreme users want
9761 ** to have prepared statements with over 32767 variables, and for them
9762 ** the option is available (at compile-time).
9763 */
9764 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
9765 typedef i16 ynVar;
9766 #else
9767 typedef int ynVar;
9768 #endif
9769
9770 /*
9771 ** Each node of an expression in the parse tree is an instance
9772 ** of this structure.
9773 **
9774 ** Expr.op is the opcode. The integer parser token codes are reused
9775 ** as opcodes here. For example, the parser defines TK_GE to be an integer
9776 ** code representing the ">=" operator. This same integer code is reused
9777 ** to represent the greater-than-or-equal-to operator in the expression
9778 ** tree.
9779 **
9780 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, 
9781 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
9782 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the 
9783 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
9784 ** then Expr.token contains the name of the function.
9785 **
9786 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
9787 ** binary operator. Either or both may be NULL.
9788 **
9789 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
9790 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
9791 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
9792 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
9793 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is 
9794 ** valid.
9795 **
9796 ** An expression of the form ID or ID.ID refers to a column in a table.
9797 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
9798 ** the integer cursor number of a VDBE cursor pointing to that table and
9799 ** Expr.iColumn is the column number for the specific column.  If the
9800 ** expression is used as a result in an aggregate SELECT, then the
9801 ** value is also stored in the Expr.iAgg column in the aggregate so that
9802 ** it can be accessed after all aggregates are computed.
9803 **
9804 ** If the expression is an unbound variable marker (a question mark 
9805 ** character '?' in the original SQL) then the Expr.iTable holds the index 
9806 ** number for that variable.
9807 **
9808 ** If the expression is a subquery then Expr.iColumn holds an integer
9809 ** register number containing the result of the subquery.  If the
9810 ** subquery gives a constant result, then iTable is -1.  If the subquery
9811 ** gives a different answer at different times during statement processing
9812 ** then iTable is the address of a subroutine that computes the subquery.
9813 **
9814 ** If the Expr is of type OP_Column, and the table it is selecting from
9815 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
9816 ** corresponding table definition.
9817 **
9818 ** ALLOCATION NOTES:
9819 **
9820 ** Expr objects can use a lot of memory space in database schema.  To
9821 ** help reduce memory requirements, sometimes an Expr object will be
9822 ** truncated.  And to reduce the number of memory allocations, sometimes
9823 ** two or more Expr objects will be stored in a single memory allocation,
9824 ** together with Expr.zToken strings.
9825 **
9826 ** If the EP_Reduced and EP_TokenOnly flags are set when
9827 ** an Expr object is truncated.  When EP_Reduced is set, then all
9828 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
9829 ** are contained within the same memory allocation.  Note, however, that
9830 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
9831 ** allocated, regardless of whether or not EP_Reduced is set.
9832 */
9833 struct Expr {
9834   u8 op;                 /* Operation performed by this node */
9835   char affinity;         /* The affinity of the column or 0 if not a column */
9836   u16 flags;             /* Various flags.  EP_* See below */
9837   union {
9838     char *zToken;          /* Token value. Zero terminated and dequoted */
9839     int iValue;            /* Integer value if EP_IntValue */
9840   } u;
9841
9842   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
9843   ** space is allocated for the fields below this point. An attempt to
9844   ** access them will result in a segfault or malfunction. 
9845   *********************************************************************/
9846
9847   Expr *pLeft;           /* Left subnode */
9848   Expr *pRight;          /* Right subnode */
9849   union {
9850     ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
9851     Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
9852   } x;
9853   CollSeq *pColl;        /* The collation type of the column or 0 */
9854
9855   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
9856   ** space is allocated for the fields below this point. An attempt to
9857   ** access them will result in a segfault or malfunction.
9858   *********************************************************************/
9859
9860   int iTable;            /* TK_COLUMN: cursor number of table holding column
9861                          ** TK_REGISTER: register number
9862                          ** TK_TRIGGER: 1 -> new, 0 -> old */
9863   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
9864                          ** TK_VARIABLE: variable number (always >= 1). */
9865   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
9866   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
9867   u8 flags2;             /* Second set of flags.  EP2_... */
9868   u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
9869   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
9870   Table *pTab;           /* Table for TK_COLUMN expressions. */
9871 #if SQLITE_MAX_EXPR_DEPTH>0
9872   int nHeight;           /* Height of the tree headed by this node */
9873 #endif
9874 };
9875
9876 /*
9877 ** The following are the meanings of bits in the Expr.flags field.
9878 */
9879 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
9880 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
9881 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
9882 #define EP_Error      0x0008  /* Expression contains one or more errors */
9883 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
9884 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
9885 #define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
9886 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
9887 #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
9888 #define EP_FixedDest  0x0200  /* Result needed in a specific register */
9889 #define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
9890 #define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
9891
9892 #define EP_Reduced    0x1000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
9893 #define EP_TokenOnly  0x2000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
9894 #define EP_Static     0x4000  /* Held in memory not obtained from malloc() */
9895
9896 /*
9897 ** The following are the meanings of bits in the Expr.flags2 field.
9898 */
9899 #define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
9900 #define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
9901
9902 /*
9903 ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
9904 ** flag on an expression structure.  This flag is used for VV&A only.  The
9905 ** routine is implemented as a macro that only works when in debugging mode,
9906 ** so as not to burden production code.
9907 */
9908 #ifdef SQLITE_DEBUG
9909 # define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
9910 #else
9911 # define ExprSetIrreducible(X)
9912 #endif
9913
9914 /*
9915 ** These macros can be used to test, set, or clear bits in the 
9916 ** Expr.flags field.
9917 */
9918 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
9919 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
9920 #define ExprSetProperty(E,P)     (E)->flags|=(P)
9921 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
9922
9923 /*
9924 ** Macros to determine the number of bytes required by a normal Expr 
9925 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags 
9926 ** and an Expr struct with the EP_TokenOnly flag set.
9927 */
9928 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
9929 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
9930 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
9931
9932 /*
9933 ** Flags passed to the sqlite3ExprDup() function. See the header comment 
9934 ** above sqlite3ExprDup() for details.
9935 */
9936 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
9937
9938 /*
9939 ** A list of expressions.  Each expression may optionally have a
9940 ** name.  An expr/name combination can be used in several ways, such
9941 ** as the list of "expr AS ID" fields following a "SELECT" or in the
9942 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
9943 ** also be used as the argument to a function, in which case the a.zName
9944 ** field is not used.
9945 */
9946 struct ExprList {
9947   int nExpr;             /* Number of expressions on the list */
9948   int nAlloc;            /* Number of entries allocated below */
9949   int iECursor;          /* VDBE Cursor associated with this ExprList */
9950   struct ExprList_item {
9951     Expr *pExpr;           /* The list of expressions */
9952     char *zName;           /* Token associated with this expression */
9953     char *zSpan;           /* Original text of the expression */
9954     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
9955     u8 done;               /* A flag to indicate when processing is finished */
9956     u16 iCol;              /* For ORDER BY, column number in result set */
9957     u16 iAlias;            /* Index into Parse.aAlias[] for zName */
9958   } *a;                  /* One entry for each expression */
9959 };
9960
9961 /*
9962 ** An instance of this structure is used by the parser to record both
9963 ** the parse tree for an expression and the span of input text for an
9964 ** expression.
9965 */
9966 struct ExprSpan {
9967   Expr *pExpr;          /* The expression parse tree */
9968   const char *zStart;   /* First character of input text */
9969   const char *zEnd;     /* One character past the end of input text */
9970 };
9971
9972 /*
9973 ** An instance of this structure can hold a simple list of identifiers,
9974 ** such as the list "a,b,c" in the following statements:
9975 **
9976 **      INSERT INTO t(a,b,c) VALUES ...;
9977 **      CREATE INDEX idx ON t(a,b,c);
9978 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
9979 **
9980 ** The IdList.a.idx field is used when the IdList represents the list of
9981 ** column names after a table name in an INSERT statement.  In the statement
9982 **
9983 **     INSERT INTO t(a,b,c) ...
9984 **
9985 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
9986 */
9987 struct IdList {
9988   struct IdList_item {
9989     char *zName;      /* Name of the identifier */
9990     int idx;          /* Index in some Table.aCol[] of a column named zName */
9991   } *a;
9992   int nId;         /* Number of identifiers on the list */
9993   int nAlloc;      /* Number of entries allocated for a[] below */
9994 };
9995
9996 /*
9997 ** The bitmask datatype defined below is used for various optimizations.
9998 **
9999 ** Changing this from a 64-bit to a 32-bit type limits the number of
10000 ** tables in a join to 32 instead of 64.  But it also reduces the size
10001 ** of the library by 738 bytes on ix86.
10002 */
10003 typedef u64 Bitmask;
10004
10005 /*
10006 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
10007 */
10008 #define BMS  ((int)(sizeof(Bitmask)*8))
10009
10010 /*
10011 ** The following structure describes the FROM clause of a SELECT statement.
10012 ** Each table or subquery in the FROM clause is a separate element of
10013 ** the SrcList.a[] array.
10014 **
10015 ** With the addition of multiple database support, the following structure
10016 ** can also be used to describe a particular table such as the table that
10017 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
10018 ** such a table must be a simple name: ID.  But in SQLite, the table can
10019 ** now be identified by a database name, a dot, then the table name: ID.ID.
10020 **
10021 ** The jointype starts out showing the join type between the current table
10022 ** and the next table on the list.  The parser builds the list this way.
10023 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
10024 ** jointype expresses the join between the table and the previous table.
10025 **
10026 ** In the colUsed field, the high-order bit (bit 63) is set if the table
10027 ** contains more than 63 columns and the 64-th or later column is used.
10028 */
10029 struct SrcList {
10030   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
10031   i16 nAlloc;      /* Number of entries allocated in a[] below */
10032   struct SrcList_item {
10033     char *zDatabase;  /* Name of database holding this table */
10034     char *zName;      /* Name of the table */
10035     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
10036     Table *pTab;      /* An SQL table corresponding to zName */
10037     Select *pSelect;  /* A SELECT statement used in place of a table name */
10038     u8 isPopulated;   /* Temporary table associated with SELECT is populated */
10039     u8 jointype;      /* Type of join between this able and the previous */
10040     u8 notIndexed;    /* True if there is a NOT INDEXED clause */
10041 #ifndef SQLITE_OMIT_EXPLAIN
10042     u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
10043 #endif
10044     int iCursor;      /* The VDBE cursor number used to access this table */
10045     Expr *pOn;        /* The ON clause of a join */
10046     IdList *pUsing;   /* The USING clause of a join */
10047     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
10048     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
10049     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
10050   } a[1];             /* One entry for each identifier on the list */
10051 };
10052
10053 /*
10054 ** Permitted values of the SrcList.a.jointype field
10055 */
10056 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
10057 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
10058 #define JT_NATURAL   0x0004    /* True for a "natural" join */
10059 #define JT_LEFT      0x0008    /* Left outer join */
10060 #define JT_RIGHT     0x0010    /* Right outer join */
10061 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
10062 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
10063
10064
10065 /*
10066 ** A WherePlan object holds information that describes a lookup
10067 ** strategy.
10068 **
10069 ** This object is intended to be opaque outside of the where.c module.
10070 ** It is included here only so that that compiler will know how big it
10071 ** is.  None of the fields in this object should be used outside of
10072 ** the where.c module.
10073 **
10074 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
10075 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
10076 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
10077 ** case that more than one of these conditions is true.
10078 */
10079 struct WherePlan {
10080   u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
10081   u32 nEq;                       /* Number of == constraints */
10082   double nRow;                   /* Estimated number of rows (for EQP) */
10083   union {
10084     Index *pIdx;                   /* Index when WHERE_INDEXED is true */
10085     struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
10086     sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
10087   } u;
10088 };
10089
10090 /*
10091 ** For each nested loop in a WHERE clause implementation, the WhereInfo
10092 ** structure contains a single instance of this structure.  This structure
10093 ** is intended to be private the the where.c module and should not be
10094 ** access or modified by other modules.
10095 **
10096 ** The pIdxInfo field is used to help pick the best index on a
10097 ** virtual table.  The pIdxInfo pointer contains indexing
10098 ** information for the i-th table in the FROM clause before reordering.
10099 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
10100 ** All other information in the i-th WhereLevel object for the i-th table
10101 ** after FROM clause ordering.
10102 */
10103 struct WhereLevel {
10104   WherePlan plan;       /* query plan for this element of the FROM clause */
10105   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
10106   int iTabCur;          /* The VDBE cursor used to access the table */
10107   int iIdxCur;          /* The VDBE cursor used to access pIdx */
10108   int addrBrk;          /* Jump here to break out of the loop */
10109   int addrNxt;          /* Jump here to start the next IN combination */
10110   int addrCont;         /* Jump here to continue with the next loop cycle */
10111   int addrFirst;        /* First instruction of interior of the loop */
10112   u8 iFrom;             /* Which entry in the FROM clause */
10113   u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
10114   int p1, p2;           /* Operands of the opcode used to ends the loop */
10115   union {               /* Information that depends on plan.wsFlags */
10116     struct {
10117       int nIn;              /* Number of entries in aInLoop[] */
10118       struct InLoop {
10119         int iCur;              /* The VDBE cursor used by this IN operator */
10120         int addrInTop;         /* Top of the IN loop */
10121       } *aInLoop;           /* Information about each nested IN operator */
10122     } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
10123   } u;
10124
10125   /* The following field is really not part of the current level.  But
10126   ** we need a place to cache virtual table index information for each
10127   ** virtual table in the FROM clause and the WhereLevel structure is
10128   ** a convenient place since there is one WhereLevel for each FROM clause
10129   ** element.
10130   */
10131   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
10132 };
10133
10134 /*
10135 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
10136 ** and the WhereInfo.wctrlFlags member.
10137 */
10138 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
10139 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
10140 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
10141 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
10142 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
10143 #define WHERE_OMIT_OPEN        0x0010 /* Table cursors are already open */
10144 #define WHERE_OMIT_CLOSE       0x0020 /* Omit close of table & index cursors */
10145 #define WHERE_FORCE_TABLE      0x0040 /* Do not use an index-only search */
10146 #define WHERE_ONETABLE_ONLY    0x0080 /* Only code the 1st table in pTabList */
10147
10148 /*
10149 ** The WHERE clause processing routine has two halves.  The
10150 ** first part does the start of the WHERE loop and the second
10151 ** half does the tail of the WHERE loop.  An instance of
10152 ** this structure is returned by the first half and passed
10153 ** into the second half to give some continuity.
10154 */
10155 struct WhereInfo {
10156   Parse *pParse;       /* Parsing and code generating context */
10157   u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
10158   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
10159   u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
10160   SrcList *pTabList;             /* List of tables in the join */
10161   int iTop;                      /* The very beginning of the WHERE loop */
10162   int iContinue;                 /* Jump here to continue with next record */
10163   int iBreak;                    /* Jump here to break out of the loop */
10164   int nLevel;                    /* Number of nested loop */
10165   struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
10166   double savedNQueryLoop;        /* pParse->nQueryLoop outside the WHERE loop */
10167   double nRowOut;                /* Estimated number of output rows */
10168   WhereLevel a[1];               /* Information about each nest loop in WHERE */
10169 };
10170
10171 /*
10172 ** A NameContext defines a context in which to resolve table and column
10173 ** names.  The context consists of a list of tables (the pSrcList) field and
10174 ** a list of named expression (pEList).  The named expression list may
10175 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
10176 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
10177 ** pEList corresponds to the result set of a SELECT and is NULL for
10178 ** other statements.
10179 **
10180 ** NameContexts can be nested.  When resolving names, the inner-most 
10181 ** context is searched first.  If no match is found, the next outer
10182 ** context is checked.  If there is still no match, the next context
10183 ** is checked.  This process continues until either a match is found
10184 ** or all contexts are check.  When a match is found, the nRef member of
10185 ** the context containing the match is incremented. 
10186 **
10187 ** Each subquery gets a new NameContext.  The pNext field points to the
10188 ** NameContext in the parent query.  Thus the process of scanning the
10189 ** NameContext list corresponds to searching through successively outer
10190 ** subqueries looking for a match.
10191 */
10192 struct NameContext {
10193   Parse *pParse;       /* The parser */
10194   SrcList *pSrcList;   /* One or more tables used to resolve names */
10195   ExprList *pEList;    /* Optional list of named expressions */
10196   int nRef;            /* Number of names resolved by this context */
10197   int nErr;            /* Number of errors encountered while resolving names */
10198   u8 allowAgg;         /* Aggregate functions allowed here */
10199   u8 hasAgg;           /* True if aggregates are seen */
10200   u8 isCheck;          /* True if resolving names in a CHECK constraint */
10201   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
10202   AggInfo *pAggInfo;   /* Information about aggregates at this level */
10203   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
10204 };
10205
10206 /*
10207 ** An instance of the following structure contains all information
10208 ** needed to generate code for a single SELECT statement.
10209 **
10210 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
10211 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
10212 ** limit and nOffset to the value of the offset (or 0 if there is not
10213 ** offset).  But later on, nLimit and nOffset become the memory locations
10214 ** in the VDBE that record the limit and offset counters.
10215 **
10216 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
10217 ** These addresses must be stored so that we can go back and fill in
10218 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
10219 ** the number of columns in P2 can be computed at the same time
10220 ** as the OP_OpenEphm instruction is coded because not
10221 ** enough information about the compound query is known at that point.
10222 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
10223 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
10224 ** sequences for the ORDER BY clause.
10225 */
10226 struct Select {
10227   ExprList *pEList;      /* The fields of the result */
10228   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
10229   char affinity;         /* MakeRecord with this affinity for SRT_Set */
10230   u16 selFlags;          /* Various SF_* values */
10231   SrcList *pSrc;         /* The FROM clause */
10232   Expr *pWhere;          /* The WHERE clause */
10233   ExprList *pGroupBy;    /* The GROUP BY clause */
10234   Expr *pHaving;         /* The HAVING clause */
10235   ExprList *pOrderBy;    /* The ORDER BY clause */
10236   Select *pPrior;        /* Prior select in a compound select statement */
10237   Select *pNext;         /* Next select to the left in a compound */
10238   Select *pRightmost;    /* Right-most select in a compound select statement */
10239   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
10240   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
10241   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
10242   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
10243   double nSelectRow;     /* Estimated number of result rows */
10244 };
10245
10246 /*
10247 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
10248 ** "Select Flag".
10249 */
10250 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
10251 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
10252 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
10253 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
10254 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
10255 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
10256
10257
10258 /*
10259 ** The results of a select can be distributed in several ways.  The
10260 ** "SRT" prefix means "SELECT Result Type".
10261 */
10262 #define SRT_Union        1  /* Store result as keys in an index */
10263 #define SRT_Except       2  /* Remove result from a UNION index */
10264 #define SRT_Exists       3  /* Store 1 if the result is not empty */
10265 #define SRT_Discard      4  /* Do not save the results anywhere */
10266
10267 /* The ORDER BY clause is ignored for all of the above */
10268 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
10269
10270 #define SRT_Output       5  /* Output each row of result */
10271 #define SRT_Mem          6  /* Store result in a memory cell */
10272 #define SRT_Set          7  /* Store results as keys in an index */
10273 #define SRT_Table        8  /* Store result as data with an automatic rowid */
10274 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
10275 #define SRT_Coroutine   10  /* Generate a single row of result */
10276
10277 /*
10278 ** A structure used to customize the behavior of sqlite3Select(). See
10279 ** comments above sqlite3Select() for details.
10280 */
10281 typedef struct SelectDest SelectDest;
10282 struct SelectDest {
10283   u8 eDest;         /* How to dispose of the results */
10284   u8 affinity;      /* Affinity used when eDest==SRT_Set */
10285   int iParm;        /* A parameter used by the eDest disposal method */
10286   int iMem;         /* Base register where results are written */
10287   int nMem;         /* Number of registers allocated */
10288 };
10289
10290 /*
10291 ** During code generation of statements that do inserts into AUTOINCREMENT 
10292 ** tables, the following information is attached to the Table.u.autoInc.p
10293 ** pointer of each autoincrement table to record some side information that
10294 ** the code generator needs.  We have to keep per-table autoincrement
10295 ** information in case inserts are down within triggers.  Triggers do not
10296 ** normally coordinate their activities, but we do need to coordinate the
10297 ** loading and saving of autoincrement information.
10298 */
10299 struct AutoincInfo {
10300   AutoincInfo *pNext;   /* Next info block in a list of them all */
10301   Table *pTab;          /* Table this info block refers to */
10302   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
10303   int regCtr;           /* Memory register holding the rowid counter */
10304 };
10305
10306 /*
10307 ** Size of the column cache
10308 */
10309 #ifndef SQLITE_N_COLCACHE
10310 # define SQLITE_N_COLCACHE 10
10311 #endif
10312
10313 /*
10314 ** At least one instance of the following structure is created for each 
10315 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
10316 ** statement. All such objects are stored in the linked list headed at
10317 ** Parse.pTriggerPrg and deleted once statement compilation has been
10318 ** completed.
10319 **
10320 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
10321 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
10322 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
10323 ** The Parse.pTriggerPrg list never contains two entries with the same
10324 ** values for both pTrigger and orconf.
10325 **
10326 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
10327 ** accessed (or set to 0 for triggers fired as a result of INSERT 
10328 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
10329 ** a mask of new.* columns used by the program.
10330 */
10331 struct TriggerPrg {
10332   Trigger *pTrigger;      /* Trigger this program was coded from */
10333   int orconf;             /* Default ON CONFLICT policy */
10334   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
10335   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
10336   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
10337 };
10338
10339 /*
10340 ** An SQL parser context.  A copy of this structure is passed through
10341 ** the parser and down into all the parser action routine in order to
10342 ** carry around information that is global to the entire parse.
10343 **
10344 ** The structure is divided into two parts.  When the parser and code
10345 ** generate call themselves recursively, the first part of the structure
10346 ** is constant but the second part is reset at the beginning and end of
10347 ** each recursion.
10348 **
10349 ** The nTableLock and aTableLock variables are only used if the shared-cache 
10350 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
10351 ** used to store the set of table-locks required by the statement being
10352 ** compiled. Function sqlite3TableLock() is used to add entries to the
10353 ** list.
10354 */
10355 struct Parse {
10356   sqlite3 *db;         /* The main database structure */
10357   int rc;              /* Return code from execution */
10358   char *zErrMsg;       /* An error message */
10359   Vdbe *pVdbe;         /* An engine for executing database bytecode */
10360   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
10361   u8 nameClash;        /* A permanent table name clashes with temp table name */
10362   u8 checkSchema;      /* Causes schema cookie check after an error */
10363   u8 nested;           /* Number of nested calls to the parser/code generator */
10364   u8 parseError;       /* True after a parsing error.  Ticket #1794 */
10365   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
10366   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
10367   int aTempReg[8];     /* Holding area for temporary registers */
10368   int nRangeReg;       /* Size of the temporary register block */
10369   int iRangeReg;       /* First register in temporary register block */
10370   int nErr;            /* Number of errors seen */
10371   int nTab;            /* Number of previously allocated VDBE cursors */
10372   int nMem;            /* Number of memory cells used so far */
10373   int nSet;            /* Number of sets used so far */
10374   int ckBase;          /* Base register of data during check constraints */
10375   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
10376   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
10377   u8 nColCache;        /* Number of entries in the column cache */
10378   u8 iColCache;        /* Next entry of the cache to replace */
10379   struct yColCache {
10380     int iTable;           /* Table cursor number */
10381     int iColumn;          /* Table column number */
10382     u8 tempReg;           /* iReg is a temp register that needs to be freed */
10383     int iLevel;           /* Nesting level */
10384     int iReg;             /* Reg with value of this column. 0 means none. */
10385     int lru;              /* Least recently used entry has the smallest value */
10386   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
10387   u32 writeMask;       /* Start a write transaction on these databases */
10388   u32 cookieMask;      /* Bitmask of schema verified databases */
10389   u8 isMultiWrite;     /* True if statement may affect/insert multiple rows */
10390   u8 mayAbort;         /* True if statement may throw an ABORT exception */
10391   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
10392   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
10393 #ifndef SQLITE_OMIT_SHARED_CACHE
10394   int nTableLock;        /* Number of locks in aTableLock */
10395   TableLock *aTableLock; /* Required table locks for shared-cache mode */
10396 #endif
10397   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
10398   int regRoot;         /* Register holding root page number for new objects */
10399   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
10400   int nMaxArg;         /* Max args passed to user function by sub-program */
10401
10402   /* Information used while coding trigger programs. */
10403   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
10404   Table *pTriggerTab;  /* Table triggers are being coded for */
10405   u32 oldmask;         /* Mask of old.* columns referenced */
10406   u32 newmask;         /* Mask of new.* columns referenced */
10407   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
10408   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
10409   u8 disableTriggers;  /* True to disable triggers */
10410   double nQueryLoop;   /* Estimated number of iterations of a query */
10411
10412   /* Above is constant between recursions.  Below is reset before and after
10413   ** each recursion */
10414
10415   int nVar;            /* Number of '?' variables seen in the SQL so far */
10416   int nVarExpr;        /* Number of used slots in apVarExpr[] */
10417   int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
10418   Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
10419   Vdbe *pReprepare;    /* VM being reprepared (sqlite3Reprepare()) */
10420   int nAlias;          /* Number of aliased result set columns */
10421   int nAliasAlloc;     /* Number of allocated slots for aAlias[] */
10422   int *aAlias;         /* Register used to hold aliased result */
10423   u8 explain;          /* True if the EXPLAIN flag is found on the query */
10424   Token sNameToken;    /* Token with unqualified schema object name */
10425   Token sLastToken;    /* The last token parsed */
10426   const char *zTail;   /* All SQL text past the last semicolon parsed */
10427   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
10428   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
10429   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
10430 #ifndef SQLITE_OMIT_VIRTUALTABLE
10431   Token sArg;                /* Complete text of a module argument */
10432   u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
10433   int nVtabLock;             /* Number of virtual tables to lock */
10434   Table **apVtabLock;        /* Pointer to virtual tables needing locking */
10435 #endif
10436   int nHeight;            /* Expression tree height of current sub-select */
10437   Table *pZombieTab;      /* List of Table objects to delete after code gen */
10438   TriggerPrg *pTriggerPrg;    /* Linked list of coded triggers */
10439
10440 #ifndef SQLITE_OMIT_EXPLAIN
10441   int iSelectId;
10442   int iNextSelectId;
10443 #endif
10444 };
10445
10446 #ifdef SQLITE_OMIT_VIRTUALTABLE
10447   #define IN_DECLARE_VTAB 0
10448 #else
10449   #define IN_DECLARE_VTAB (pParse->declareVtab)
10450 #endif
10451
10452 /*
10453 ** An instance of the following structure can be declared on a stack and used
10454 ** to save the Parse.zAuthContext value so that it can be restored later.
10455 */
10456 struct AuthContext {
10457   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
10458   Parse *pParse;              /* The Parse structure */
10459 };
10460
10461 /*
10462 ** Bitfield flags for P5 value in OP_Insert and OP_Delete
10463 */
10464 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
10465 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
10466 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
10467 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
10468 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
10469 #define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
10470
10471 /*
10472  * Each trigger present in the database schema is stored as an instance of
10473  * struct Trigger. 
10474  *
10475  * Pointers to instances of struct Trigger are stored in two ways.
10476  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
10477  *    database). This allows Trigger structures to be retrieved by name.
10478  * 2. All triggers associated with a single table form a linked list, using the
10479  *    pNext member of struct Trigger. A pointer to the first element of the
10480  *    linked list is stored as the "pTrigger" member of the associated
10481  *    struct Table.
10482  *
10483  * The "step_list" member points to the first element of a linked list
10484  * containing the SQL statements specified as the trigger program.
10485  */
10486 struct Trigger {
10487   char *zName;            /* The name of the trigger                        */
10488   char *table;            /* The table or view to which the trigger applies */
10489   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
10490   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
10491   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
10492   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
10493                              the <column-list> is stored here */
10494   Schema *pSchema;        /* Schema containing the trigger */
10495   Schema *pTabSchema;     /* Schema containing the table */
10496   TriggerStep *step_list; /* Link list of trigger program steps             */
10497   Trigger *pNext;         /* Next trigger associated with the table */
10498 };
10499
10500 /*
10501 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
10502 ** determine which. 
10503 **
10504 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
10505 ** In that cases, the constants below can be ORed together.
10506 */
10507 #define TRIGGER_BEFORE  1
10508 #define TRIGGER_AFTER   2
10509
10510 /*
10511  * An instance of struct TriggerStep is used to store a single SQL statement
10512  * that is a part of a trigger-program. 
10513  *
10514  * Instances of struct TriggerStep are stored in a singly linked list (linked
10515  * using the "pNext" member) referenced by the "step_list" member of the 
10516  * associated struct Trigger instance. The first element of the linked list is
10517  * the first step of the trigger-program.
10518  * 
10519  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
10520  * "SELECT" statement. The meanings of the other members is determined by the 
10521  * value of "op" as follows:
10522  *
10523  * (op == TK_INSERT)
10524  * orconf    -> stores the ON CONFLICT algorithm
10525  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
10526  *              this stores a pointer to the SELECT statement. Otherwise NULL.
10527  * target    -> A token holding the quoted name of the table to insert into.
10528  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
10529  *              this stores values to be inserted. Otherwise NULL.
10530  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
10531  *              statement, then this stores the column-names to be
10532  *              inserted into.
10533  *
10534  * (op == TK_DELETE)
10535  * target    -> A token holding the quoted name of the table to delete from.
10536  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
10537  *              Otherwise NULL.
10538  * 
10539  * (op == TK_UPDATE)
10540  * target    -> A token holding the quoted name of the table to update rows of.
10541  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
10542  *              Otherwise NULL.
10543  * pExprList -> A list of the columns to update and the expressions to update
10544  *              them to. See sqlite3Update() documentation of "pChanges"
10545  *              argument.
10546  * 
10547  */
10548 struct TriggerStep {
10549   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
10550   u8 orconf;           /* OE_Rollback etc. */
10551   Trigger *pTrig;      /* The trigger that this step is a part of */
10552   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
10553   Token target;        /* Target table for DELETE, UPDATE, INSERT */
10554   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
10555   ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
10556   IdList *pIdList;     /* Column names for INSERT */
10557   TriggerStep *pNext;  /* Next in the link-list */
10558   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
10559 };
10560
10561 /*
10562 ** The following structure contains information used by the sqliteFix...
10563 ** routines as they walk the parse tree to make database references
10564 ** explicit.  
10565 */
10566 typedef struct DbFixer DbFixer;
10567 struct DbFixer {
10568   Parse *pParse;      /* The parsing context.  Error messages written here */
10569   const char *zDb;    /* Make sure all objects are contained in this database */
10570   const char *zType;  /* Type of the container - used for error messages */
10571   const Token *pName; /* Name of the container - used for error messages */
10572 };
10573
10574 /*
10575 ** An objected used to accumulate the text of a string where we
10576 ** do not necessarily know how big the string will be in the end.
10577 */
10578 struct StrAccum {
10579   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
10580   char *zBase;         /* A base allocation.  Not from malloc. */
10581   char *zText;         /* The string collected so far */
10582   int  nChar;          /* Length of the string so far */
10583   int  nAlloc;         /* Amount of space allocated in zText */
10584   int  mxAlloc;        /* Maximum allowed string length */
10585   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
10586   u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
10587   u8   tooBig;         /* Becomes true if string size exceeds limits */
10588 };
10589
10590 /*
10591 ** A pointer to this structure is used to communicate information
10592 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
10593 */
10594 typedef struct {
10595   sqlite3 *db;        /* The database being initialized */
10596   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
10597   char **pzErrMsg;    /* Error message stored here */
10598   int rc;             /* Result code stored here */
10599 } InitData;
10600
10601 /*
10602 ** Structure containing global configuration data for the SQLite library.
10603 **
10604 ** This structure also contains some state information.
10605 */
10606 struct Sqlite3Config {
10607   int bMemstat;                     /* True to enable memory status */
10608   int bCoreMutex;                   /* True to enable core mutexing */
10609   int bFullMutex;                   /* True to enable full mutexing */
10610   int mxStrlen;                     /* Maximum string length */
10611   int szLookaside;                  /* Default lookaside buffer size */
10612   int nLookaside;                   /* Default lookaside buffer count */
10613   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
10614   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
10615   sqlite3_pcache_methods pcache;    /* Low-level page-cache interface */
10616   void *pHeap;                      /* Heap storage space */
10617   int nHeap;                        /* Size of pHeap[] */
10618   int mnReq, mxReq;                 /* Min and max heap requests sizes */
10619   void *pScratch;                   /* Scratch memory */
10620   int szScratch;                    /* Size of each scratch buffer */
10621   int nScratch;                     /* Number of scratch buffers */
10622   void *pPage;                      /* Page cache memory */
10623   int szPage;                       /* Size of each page in pPage[] */
10624   int nPage;                        /* Number of pages in pPage[] */
10625   int mxParserStack;                /* maximum depth of the parser stack */
10626   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
10627   /* The above might be initialized to non-zero.  The following need to always
10628   ** initially be zero, however. */
10629   int isInit;                       /* True after initialization has finished */
10630   int inProgress;                   /* True while initialization in progress */
10631   int isMutexInit;                  /* True after mutexes are initialized */
10632   int isMallocInit;                 /* True after malloc is initialized */
10633   int isPCacheInit;                 /* True after malloc is initialized */
10634   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
10635   int nRefInitMutex;                /* Number of users of pInitMutex */
10636   void (*xLog)(void*,int,const char*); /* Function for logging */
10637   void *pLogArg;                       /* First argument to xLog() */
10638 };
10639
10640 /*
10641 ** Context pointer passed down through the tree-walk.
10642 */
10643 struct Walker {
10644   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
10645   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
10646   Parse *pParse;                            /* Parser context.  */
10647   union {                                   /* Extra data for callback */
10648     NameContext *pNC;                          /* Naming context */
10649     int i;                                     /* Integer value */
10650   } u;
10651 };
10652
10653 /* Forward declarations */
10654 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
10655 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
10656 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
10657 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
10658 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
10659
10660 /*
10661 ** Return code from the parse-tree walking primitives and their
10662 ** callbacks.
10663 */
10664 #define WRC_Continue    0   /* Continue down into children */
10665 #define WRC_Prune       1   /* Omit children but continue walking siblings */
10666 #define WRC_Abort       2   /* Abandon the tree walk */
10667
10668 /*
10669 ** Assuming zIn points to the first byte of a UTF-8 character,
10670 ** advance zIn to point to the first byte of the next UTF-8 character.
10671 */
10672 #define SQLITE_SKIP_UTF8(zIn) {                        \
10673   if( (*(zIn++))>=0xc0 ){                              \
10674     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
10675   }                                                    \
10676 }
10677
10678 /*
10679 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
10680 ** the same name but without the _BKPT suffix.  These macros invoke
10681 ** routines that report the line-number on which the error originated
10682 ** using sqlite3_log().  The routines also provide a convenient place
10683 ** to set a debugger breakpoint.
10684 */
10685 SQLITE_PRIVATE int sqlite3CorruptError(int);
10686 SQLITE_PRIVATE int sqlite3MisuseError(int);
10687 SQLITE_PRIVATE int sqlite3CantopenError(int);
10688 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
10689 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
10690 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
10691
10692
10693 /*
10694 ** FTS4 is really an extension for FTS3.  It is enabled using the
10695 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
10696 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
10697 */
10698 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
10699 # define SQLITE_ENABLE_FTS3
10700 #endif
10701
10702 /*
10703 ** The ctype.h header is needed for non-ASCII systems.  It is also
10704 ** needed by FTS3 when FTS3 is included in the amalgamation.
10705 */
10706 #if !defined(SQLITE_ASCII) || \
10707     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
10708 # include <ctype.h>
10709 #endif
10710
10711 /*
10712 ** The following macros mimic the standard library functions toupper(),
10713 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
10714 ** sqlite versions only work for ASCII characters, regardless of locale.
10715 */
10716 #ifdef SQLITE_ASCII
10717 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
10718 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
10719 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
10720 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
10721 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
10722 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
10723 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
10724 #else
10725 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
10726 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
10727 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
10728 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
10729 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
10730 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
10731 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
10732 #endif
10733
10734 /*
10735 ** Internal function prototypes
10736 */
10737 SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
10738 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
10739 #define sqlite3StrNICmp sqlite3_strnicmp
10740
10741 SQLITE_PRIVATE int sqlite3MallocInit(void);
10742 SQLITE_PRIVATE void sqlite3MallocEnd(void);
10743 SQLITE_PRIVATE void *sqlite3Malloc(int);
10744 SQLITE_PRIVATE void *sqlite3MallocZero(int);
10745 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
10746 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
10747 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
10748 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
10749 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
10750 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
10751 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
10752 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
10753 SQLITE_PRIVATE int sqlite3MallocSize(void*);
10754 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
10755 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
10756 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
10757 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
10758 SQLITE_PRIVATE void sqlite3PageFree(void*);
10759 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
10760 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
10761 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
10762
10763 /*
10764 ** On systems with ample stack space and that support alloca(), make
10765 ** use of alloca() to obtain space for large automatic objects.  By default,
10766 ** obtain space from malloc().
10767 **
10768 ** The alloca() routine never returns NULL.  This will cause code paths
10769 ** that deal with sqlite3StackAlloc() failures to be unreachable.
10770 */
10771 #ifdef SQLITE_USE_ALLOCA
10772 # define sqlite3StackAllocRaw(D,N)   alloca(N)
10773 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
10774 # define sqlite3StackFree(D,P)       
10775 #else
10776 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
10777 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
10778 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
10779 #endif
10780
10781 #ifdef SQLITE_ENABLE_MEMSYS3
10782 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
10783 #endif
10784 #ifdef SQLITE_ENABLE_MEMSYS5
10785 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
10786 #endif
10787
10788
10789 #ifndef SQLITE_MUTEX_OMIT
10790 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
10791 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
10792 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
10793 SQLITE_PRIVATE   int sqlite3MutexInit(void);
10794 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
10795 #endif
10796
10797 SQLITE_PRIVATE int sqlite3StatusValue(int);
10798 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
10799 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
10800
10801 #ifndef SQLITE_OMIT_FLOATING_POINT
10802 SQLITE_PRIVATE   int sqlite3IsNaN(double);
10803 #else
10804 # define sqlite3IsNaN(X)  0
10805 #endif
10806
10807 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
10808 #ifndef SQLITE_OMIT_TRACE
10809 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
10810 #endif
10811 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
10812 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
10813 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
10814 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
10815 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
10816 #endif
10817 #if defined(SQLITE_TEST)
10818 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
10819 #endif
10820 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
10821 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
10822 SQLITE_PRIVATE int sqlite3Dequote(char*);
10823 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
10824 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
10825 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
10826 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
10827 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
10828 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
10829 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
10830 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
10831 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
10832 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
10833 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
10834 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
10835 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
10836 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
10837 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
10838 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
10839 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
10840 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
10841 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
10842 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
10843 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
10844 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
10845 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
10846 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
10847 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
10848 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
10849 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
10850 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
10851 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
10852 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
10853 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
10854 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
10855 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
10856 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
10857 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
10858 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
10859
10860 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
10861 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
10862 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
10863 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
10864 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
10865 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
10866 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
10867
10868 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
10869 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
10870 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
10871 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
10872 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
10873
10874 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
10875
10876 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
10877 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
10878 #else
10879 # define sqlite3ViewGetColumnNames(A,B) 0
10880 #endif
10881
10882 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
10883 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
10884 #ifndef SQLITE_OMIT_AUTOINCREMENT
10885 SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
10886 SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
10887 #else
10888 # define sqlite3AutoincrementBegin(X)
10889 # define sqlite3AutoincrementEnd(X)
10890 #endif
10891 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
10892 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
10893 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
10894 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
10895 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
10896 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
10897 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
10898                                       Token*, Select*, Expr*, IdList*);
10899 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
10900 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
10901 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
10902 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
10903 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
10904 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
10905 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
10906                         Token*, int, int);
10907 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
10908 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
10909 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
10910                          Expr*,ExprList*,int,Expr*,Expr*);
10911 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
10912 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
10913 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
10914 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
10915 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
10916 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
10917 #endif
10918 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
10919 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
10920 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
10921 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
10922 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
10923 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
10924 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
10925 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
10926 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
10927 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
10928 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
10929 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
10930 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
10931 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
10932 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
10933 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
10934 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
10935 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
10936 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
10937 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
10938 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
10939 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
10940 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
10941 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
10942 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
10943 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
10944 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
10945 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
10946 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
10947 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
10948 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
10949 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
10950 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
10951 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
10952 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
10953 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
10954 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
10955 SQLITE_PRIVATE void sqlite3PrngResetState(void);
10956 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
10957 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
10958 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
10959 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
10960 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
10961 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
10962 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
10963 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
10964 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
10965 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
10966 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
10967 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
10968 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
10969 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
10970 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
10971 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
10972 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
10973 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
10974 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
10975                                      int*,int,int,int,int,int*);
10976 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
10977 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
10978 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
10979 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
10980 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
10981 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
10982 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
10983 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
10984 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
10985 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
10986 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
10987 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
10988 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
10989 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
10990 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
10991 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
10992 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
10993 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
10994 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
10995
10996 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
10997 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
10998 #endif
10999
11000 #ifndef SQLITE_OMIT_TRIGGER
11001 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
11002                            Expr*,int, int);
11003 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
11004 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
11005 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
11006 SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
11007 SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
11008 SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
11009                             int, int, int);
11010 SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
11011   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
11012 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
11013 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
11014 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
11015                                         ExprList*,Select*,u8);
11016 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
11017 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
11018 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
11019 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
11020 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
11021 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
11022 #else
11023 # define sqlite3TriggersExist(B,C,D,E,F) 0
11024 # define sqlite3DeleteTrigger(A,B)
11025 # define sqlite3DropTriggerPtr(A,B)
11026 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
11027 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
11028 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
11029 # define sqlite3TriggerList(X, Y) 0
11030 # define sqlite3ParseToplevel(p) p
11031 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
11032 #endif
11033
11034 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
11035 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
11036 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
11037 #ifndef SQLITE_OMIT_AUTHORIZATION
11038 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
11039 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
11040 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
11041 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
11042 SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
11043 #else
11044 # define sqlite3AuthRead(a,b,c,d)
11045 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
11046 # define sqlite3AuthContextPush(a,b,c)
11047 # define sqlite3AuthContextPop(a)  ((void)(a))
11048 #endif
11049 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
11050 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
11051 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
11052 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
11053 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
11054 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
11055 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
11056 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
11057 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
11058 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
11059 SQLITE_PRIVATE int sqlite3Atoi(const char*);
11060 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
11061 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
11062 SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8**);
11063
11064 /*
11065 ** Routines to read and write variable-length integers.  These used to
11066 ** be defined locally, but now we use the varint routines in the util.c
11067 ** file.  Code should use the MACRO forms below, as the Varint32 versions
11068 ** are coded to assume the single byte case is already handled (which 
11069 ** the MACRO form does).
11070 */
11071 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
11072 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
11073 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
11074 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
11075 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
11076
11077 /*
11078 ** The header of a record consists of a sequence variable-length integers.
11079 ** These integers are almost always small and are encoded as a single byte.
11080 ** The following macros take advantage this fact to provide a fast encode
11081 ** and decode of the integers in a record header.  It is faster for the common
11082 ** case where the integer is a single byte.  It is a little slower when the
11083 ** integer is two or more bytes.  But overall it is faster.
11084 **
11085 ** The following expressions are equivalent:
11086 **
11087 **     x = sqlite3GetVarint32( A, &B );
11088 **     x = sqlite3PutVarint32( A, B );
11089 **
11090 **     x = getVarint32( A, B );
11091 **     x = putVarint32( A, B );
11092 **
11093 */
11094 #define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
11095 #define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
11096 #define getVarint    sqlite3GetVarint
11097 #define putVarint    sqlite3PutVarint
11098
11099
11100 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
11101 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
11102 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
11103 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
11104 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
11105 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
11106 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
11107 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
11108 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
11109 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
11110 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
11111 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
11112 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
11113 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
11114 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr*, CollSeq*);
11115 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr*, Token*);
11116 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
11117 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
11118 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
11119
11120 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
11121 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
11122 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
11123                         void(*)(void*));
11124 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
11125 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
11126 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
11127 #ifdef SQLITE_ENABLE_STAT2
11128 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
11129 #endif
11130 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
11131 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
11132 #ifndef SQLITE_AMALGAMATION
11133 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
11134 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
11135 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
11136 SQLITE_PRIVATE const Token sqlite3IntTokens[];
11137 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
11138 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11139 #ifndef SQLITE_OMIT_WSD
11140 SQLITE_PRIVATE int sqlite3PendingByte;
11141 #endif
11142 #endif
11143 SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
11144 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
11145 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
11146 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
11147 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
11148 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
11149 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
11150 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
11151 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
11152 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
11153 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
11154 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
11155 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
11156 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
11157 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
11158 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
11159 SQLITE_PRIVATE char sqlite3AffinityType(const char*);
11160 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
11161 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
11162 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
11163 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
11164 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
11165 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
11166 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
11167 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
11168 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
11169 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
11170 SQLITE_PRIVATE void sqlite3SchemaFree(void *);
11171 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
11172 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
11173 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
11174 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
11175   void (*)(sqlite3_context*,int,sqlite3_value **),
11176   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
11177   FuncDestructor *pDestructor
11178 );
11179 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
11180 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
11181
11182 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
11183 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
11184 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
11185 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
11186 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
11187 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
11188
11189 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
11190 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
11191
11192 /*
11193 ** The interface to the LEMON-generated parser
11194 */
11195 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
11196 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
11197 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
11198 #ifdef YYTRACKMAXSTACKDEPTH
11199 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
11200 #endif
11201
11202 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
11203 #ifndef SQLITE_OMIT_LOAD_EXTENSION
11204 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
11205 #else
11206 # define sqlite3CloseExtensions(X)
11207 #endif
11208
11209 #ifndef SQLITE_OMIT_SHARED_CACHE
11210 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
11211 #else
11212   #define sqlite3TableLock(v,w,x,y,z)
11213 #endif
11214
11215 #ifdef SQLITE_TEST
11216 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
11217 #endif
11218
11219 #ifdef SQLITE_OMIT_VIRTUALTABLE
11220 #  define sqlite3VtabClear(Y)
11221 #  define sqlite3VtabSync(X,Y) SQLITE_OK
11222 #  define sqlite3VtabRollback(X)
11223 #  define sqlite3VtabCommit(X)
11224 #  define sqlite3VtabInSync(db) 0
11225 #  define sqlite3VtabLock(X) 
11226 #  define sqlite3VtabUnlock(X)
11227 #  define sqlite3VtabUnlockList(X)
11228 #else
11229 SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
11230 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
11231 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
11232 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
11233 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
11234 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
11235 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
11236 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
11237 #endif
11238 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
11239 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
11240 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
11241 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
11242 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
11243 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
11244 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
11245 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
11246 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
11247 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
11248 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
11249 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
11250 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
11251 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
11252 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
11253 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
11254 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
11255 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
11256 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
11257 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int);
11258 SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
11259
11260 /* Declarations for functions in fkey.c. All of these are replaced by
11261 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
11262 ** key functionality is available. If OMIT_TRIGGER is defined but
11263 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
11264 ** this case foreign keys are parsed, but no other functionality is 
11265 ** provided (enforcement of FK constraints requires the triggers sub-system).
11266 */
11267 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
11268 SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
11269 SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
11270 SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
11271 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
11272 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
11273 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
11274 #else
11275   #define sqlite3FkActions(a,b,c,d)
11276   #define sqlite3FkCheck(a,b,c,d)
11277   #define sqlite3FkDropTable(a,b,c)
11278   #define sqlite3FkOldmask(a,b)      0
11279   #define sqlite3FkRequired(a,b,c,d) 0
11280 #endif
11281 #ifndef SQLITE_OMIT_FOREIGN_KEY
11282 SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
11283 #else
11284   #define sqlite3FkDelete(a,b)
11285 #endif
11286
11287
11288 /*
11289 ** Available fault injectors.  Should be numbered beginning with 0.
11290 */
11291 #define SQLITE_FAULTINJECTOR_MALLOC     0
11292 #define SQLITE_FAULTINJECTOR_COUNT      1
11293
11294 /*
11295 ** The interface to the code in fault.c used for identifying "benign"
11296 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
11297 ** is not defined.
11298 */
11299 #ifndef SQLITE_OMIT_BUILTIN_TEST
11300 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
11301 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
11302 #else
11303   #define sqlite3BeginBenignMalloc()
11304   #define sqlite3EndBenignMalloc()
11305 #endif
11306
11307 #define IN_INDEX_ROWID           1
11308 #define IN_INDEX_EPH             2
11309 #define IN_INDEX_INDEX           3
11310 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
11311
11312 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
11313 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
11314 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
11315 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
11316 #else
11317   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
11318 #endif
11319
11320 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
11321 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
11322 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
11323
11324 #if SQLITE_MAX_EXPR_DEPTH>0
11325 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
11326 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
11327 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
11328 #else
11329   #define sqlite3ExprSetHeight(x,y)
11330   #define sqlite3SelectExprHeight(x) 0
11331   #define sqlite3ExprCheckHeight(x,y)
11332 #endif
11333
11334 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
11335 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
11336
11337 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
11338 SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
11339 SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
11340 SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
11341 #else
11342   #define sqlite3ConnectionBlocked(x,y)
11343   #define sqlite3ConnectionUnlocked(x)
11344   #define sqlite3ConnectionClosed(x)
11345 #endif
11346
11347 #ifdef SQLITE_DEBUG
11348 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
11349 #endif
11350
11351 /*
11352 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
11353 ** sqlite3IoTrace is a pointer to a printf-like routine used to
11354 ** print I/O tracing messages. 
11355 */
11356 #ifdef SQLITE_ENABLE_IOTRACE
11357 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
11358 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
11359 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
11360 #else
11361 # define IOTRACE(A)
11362 # define sqlite3VdbeIOTraceSql(X)
11363 #endif
11364
11365 /*
11366 ** These routines are available for the mem2.c debugging memory allocator
11367 ** only.  They are used to verify that different "types" of memory
11368 ** allocations are properly tracked by the system.
11369 **
11370 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
11371 ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
11372 ** a single bit set.
11373 **
11374 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
11375 ** argument match the type set by the previous sqlite3MemdebugSetType().
11376 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
11377 **
11378 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
11379 ** argument match the type set by the previous sqlite3MemdebugSetType().
11380 **
11381 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
11382 ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
11383 ** it might have been allocated by lookaside, except the allocation was
11384 ** too large or lookaside was already full.  It is important to verify
11385 ** that allocations that might have been satisfied by lookaside are not
11386 ** passed back to non-lookaside free() routines.  Asserts such as the
11387 ** example above are placed on the non-lookaside free() routines to verify
11388 ** this constraint. 
11389 **
11390 ** All of this is no-op for a production build.  It only comes into
11391 ** play when the SQLITE_MEMDEBUG compile-time option is used.
11392 */
11393 #ifdef SQLITE_MEMDEBUG
11394 SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
11395 SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
11396 SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
11397 #else
11398 # define sqlite3MemdebugSetType(X,Y)  /* no-op */
11399 # define sqlite3MemdebugHasType(X,Y)  1
11400 # define sqlite3MemdebugNoType(X,Y)   1
11401 #endif
11402 #define MEMTYPE_HEAP       0x01  /* General heap allocations */
11403 #define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
11404 #define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
11405 #define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
11406 #define MEMTYPE_DB         0x10  /* Uses sqlite3DbMalloc, not sqlite_malloc */
11407
11408 #endif /* _SQLITEINT_H_ */
11409
11410 /************** End of sqliteInt.h *******************************************/
11411 /************** Begin file global.c ******************************************/
11412 /*
11413 ** 2008 June 13
11414 **
11415 ** The author disclaims copyright to this source code.  In place of
11416 ** a legal notice, here is a blessing:
11417 **
11418 **    May you do good and not evil.
11419 **    May you find forgiveness for yourself and forgive others.
11420 **    May you share freely, never taking more than you give.
11421 **
11422 *************************************************************************
11423 **
11424 ** This file contains definitions of global variables and contants.
11425 */
11426
11427 /* An array to map all upper-case characters into their corresponding
11428 ** lower-case character. 
11429 **
11430 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
11431 ** handle case conversions for the UTF character set since the tables
11432 ** involved are nearly as big or bigger than SQLite itself.
11433 */
11434 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
11435 #ifdef SQLITE_ASCII
11436       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
11437      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
11438      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
11439      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
11440     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
11441     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
11442     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
11443     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
11444     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
11445     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
11446     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
11447     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
11448     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
11449     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
11450     252,253,254,255
11451 #endif
11452 #ifdef SQLITE_EBCDIC
11453       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
11454      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
11455      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
11456      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
11457      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
11458      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
11459      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
11460     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
11461     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
11462     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
11463     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
11464     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
11465     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
11466     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
11467     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
11468     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
11469 #endif
11470 };
11471
11472 /*
11473 ** The following 256 byte lookup table is used to support SQLites built-in
11474 ** equivalents to the following standard library functions:
11475 **
11476 **   isspace()                        0x01
11477 **   isalpha()                        0x02
11478 **   isdigit()                        0x04
11479 **   isalnum()                        0x06
11480 **   isxdigit()                       0x08
11481 **   toupper()                        0x20
11482 **   SQLite identifier character      0x40
11483 **
11484 ** Bit 0x20 is set if the mapped character requires translation to upper
11485 ** case. i.e. if the character is a lower-case ASCII character.
11486 ** If x is a lower-case ASCII character, then its upper-case equivalent
11487 ** is (x - 0x20). Therefore toupper() can be implemented as:
11488 **
11489 **   (x & ~(map[x]&0x20))
11490 **
11491 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
11492 ** array. tolower() is used more often than toupper() by SQLite.
11493 **
11494 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an 
11495 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
11496 ** non-ASCII UTF character. Hence the test for whether or not a character is
11497 ** part of an identifier is 0x46.
11498 **
11499 ** SQLite's versions are identical to the standard versions assuming a
11500 ** locale of "C". They are implemented as macros in sqliteInt.h.
11501 */
11502 #ifdef SQLITE_ASCII
11503 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
11504   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
11505   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
11506   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
11507   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
11508   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
11509   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
11510   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
11511   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
11512
11513   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
11514   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
11515   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
11516   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
11517   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
11518   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
11519   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
11520   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
11521
11522   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
11523   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
11524   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
11525   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
11526   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
11527   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
11528   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
11529   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
11530
11531   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
11532   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
11533   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
11534   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
11535   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
11536   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
11537   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
11538   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
11539 };
11540 #endif
11541
11542
11543
11544 /*
11545 ** The following singleton contains the global configuration for
11546 ** the SQLite library.
11547 */
11548 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
11549    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
11550    1,                         /* bCoreMutex */
11551    SQLITE_THREADSAFE==1,      /* bFullMutex */
11552    0x7ffffffe,                /* mxStrlen */
11553    100,                       /* szLookaside */
11554    500,                       /* nLookaside */
11555    {0,0,0,0,0,0,0,0},         /* m */
11556    {0,0,0,0,0,0,0,0,0},       /* mutex */
11557    {0,0,0,0,0,0,0,0,0,0,0},   /* pcache */
11558    (void*)0,                  /* pHeap */
11559    0,                         /* nHeap */
11560    0, 0,                      /* mnHeap, mxHeap */
11561    (void*)0,                  /* pScratch */
11562    0,                         /* szScratch */
11563    0,                         /* nScratch */
11564    (void*)0,                  /* pPage */
11565    0,                         /* szPage */
11566    0,                         /* nPage */
11567    0,                         /* mxParserStack */
11568    0,                         /* sharedCacheEnabled */
11569    /* All the rest should always be initialized to zero */
11570    0,                         /* isInit */
11571    0,                         /* inProgress */
11572    0,                         /* isMutexInit */
11573    0,                         /* isMallocInit */
11574    0,                         /* isPCacheInit */
11575    0,                         /* pInitMutex */
11576    0,                         /* nRefInitMutex */
11577    0,                         /* xLog */
11578    0,                         /* pLogArg */
11579 };
11580
11581
11582 /*
11583 ** Hash table for global functions - functions common to all
11584 ** database connections.  After initialization, this table is
11585 ** read-only.
11586 */
11587 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11588
11589 /*
11590 ** Constant tokens for values 0 and 1.
11591 */
11592 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
11593    { "0", 1 },
11594    { "1", 1 }
11595 };
11596
11597
11598 /*
11599 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
11600 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
11601 ** the database page that contains the pending byte.  It never attempts
11602 ** to read or write that page.  The pending byte page is set assign
11603 ** for use by the VFS layers as space for managing file locks.
11604 **
11605 ** During testing, it is often desirable to move the pending byte to
11606 ** a different position in the file.  This allows code that has to
11607 ** deal with the pending byte to run on files that are much smaller
11608 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
11609 ** move the pending byte.
11610 **
11611 ** IMPORTANT:  Changing the pending byte to any value other than
11612 ** 0x40000000 results in an incompatible database file format!
11613 ** Changing the pending byte during operating results in undefined
11614 ** and dileterious behavior.
11615 */
11616 #ifndef SQLITE_OMIT_WSD
11617 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
11618 #endif
11619
11620 /*
11621 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
11622 ** created by mkopcodeh.awk during compilation.  Data is obtained
11623 ** from the comments following the "case OP_xxxx:" statements in
11624 ** the vdbe.c file.  
11625 */
11626 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
11627
11628 /************** End of global.c **********************************************/
11629 /************** Begin file ctime.c *******************************************/
11630 /*
11631 ** 2010 February 23
11632 **
11633 ** The author disclaims copyright to this source code.  In place of
11634 ** a legal notice, here is a blessing:
11635 **
11636 **    May you do good and not evil.
11637 **    May you find forgiveness for yourself and forgive others.
11638 **    May you share freely, never taking more than you give.
11639 **
11640 *************************************************************************
11641 **
11642 ** This file implements routines used to report what compile-time options
11643 ** SQLite was built with.
11644 */
11645
11646 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
11647
11648
11649 /*
11650 ** An array of names of all compile-time options.  This array should 
11651 ** be sorted A-Z.
11652 **
11653 ** This array looks large, but in a typical installation actually uses
11654 ** only a handful of compile-time options, so most times this array is usually
11655 ** rather short and uses little memory space.
11656 */
11657 static const char * const azCompileOpt[] = {
11658
11659 /* These macros are provided to "stringify" the value of the define
11660 ** for those options in which the value is meaningful. */
11661 #define CTIMEOPT_VAL_(opt) #opt
11662 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11663
11664 #ifdef SQLITE_32BIT_ROWID
11665   "32BIT_ROWID",
11666 #endif
11667 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
11668   "4_BYTE_ALIGNED_MALLOC",
11669 #endif
11670 #ifdef SQLITE_CASE_SENSITIVE_LIKE
11671   "CASE_SENSITIVE_LIKE",
11672 #endif
11673 #ifdef SQLITE_CHECK_PAGES
11674   "CHECK_PAGES",
11675 #endif
11676 #ifdef SQLITE_COVERAGE_TEST
11677   "COVERAGE_TEST",
11678 #endif
11679 #ifdef SQLITE_DEBUG
11680   "DEBUG",
11681 #endif
11682 #ifdef SQLITE_DEFAULT_LOCKING_MODE
11683   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
11684 #endif
11685 #ifdef SQLITE_DISABLE_DIRSYNC
11686   "DISABLE_DIRSYNC",
11687 #endif
11688 #ifdef SQLITE_DISABLE_LFS
11689   "DISABLE_LFS",
11690 #endif
11691 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
11692   "ENABLE_ATOMIC_WRITE",
11693 #endif
11694 #ifdef SQLITE_ENABLE_CEROD
11695   "ENABLE_CEROD",
11696 #endif
11697 #ifdef SQLITE_ENABLE_COLUMN_METADATA
11698   "ENABLE_COLUMN_METADATA",
11699 #endif
11700 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
11701   "ENABLE_EXPENSIVE_ASSERT",
11702 #endif
11703 #ifdef SQLITE_ENABLE_FTS1
11704   "ENABLE_FTS1",
11705 #endif
11706 #ifdef SQLITE_ENABLE_FTS2
11707   "ENABLE_FTS2",
11708 #endif
11709 #ifdef SQLITE_ENABLE_FTS3
11710   "ENABLE_FTS3",
11711 #endif
11712 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
11713   "ENABLE_FTS3_PARENTHESIS",
11714 #endif
11715 #ifdef SQLITE_ENABLE_FTS4
11716   "ENABLE_FTS4",
11717 #endif
11718 #ifdef SQLITE_ENABLE_ICU
11719   "ENABLE_ICU",
11720 #endif
11721 #ifdef SQLITE_ENABLE_IOTRACE
11722   "ENABLE_IOTRACE",
11723 #endif
11724 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
11725   "ENABLE_LOAD_EXTENSION",
11726 #endif
11727 #ifdef SQLITE_ENABLE_LOCKING_STYLE
11728   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
11729 #endif
11730 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
11731   "ENABLE_MEMORY_MANAGEMENT",
11732 #endif
11733 #ifdef SQLITE_ENABLE_MEMSYS3
11734   "ENABLE_MEMSYS3",
11735 #endif
11736 #ifdef SQLITE_ENABLE_MEMSYS5
11737   "ENABLE_MEMSYS5",
11738 #endif
11739 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
11740   "ENABLE_OVERSIZE_CELL_CHECK",
11741 #endif
11742 #ifdef SQLITE_ENABLE_RTREE
11743   "ENABLE_RTREE",
11744 #endif
11745 #ifdef SQLITE_ENABLE_STAT2
11746   "ENABLE_STAT2",
11747 #endif
11748 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
11749   "ENABLE_UNLOCK_NOTIFY",
11750 #endif
11751 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
11752   "ENABLE_UPDATE_DELETE_LIMIT",
11753 #endif
11754 #ifdef SQLITE_HAS_CODEC
11755   "HAS_CODEC",
11756 #endif
11757 #ifdef SQLITE_HAVE_ISNAN
11758   "HAVE_ISNAN",
11759 #endif
11760 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
11761   "HOMEGROWN_RECURSIVE_MUTEX",
11762 #endif
11763 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
11764   "IGNORE_AFP_LOCK_ERRORS",
11765 #endif
11766 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
11767   "IGNORE_FLOCK_LOCK_ERRORS",
11768 #endif
11769 #ifdef SQLITE_INT64_TYPE
11770   "INT64_TYPE",
11771 #endif
11772 #ifdef SQLITE_LOCK_TRACE
11773   "LOCK_TRACE",
11774 #endif
11775 #ifdef SQLITE_MEMDEBUG
11776   "MEMDEBUG",
11777 #endif
11778 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
11779   "MIXED_ENDIAN_64BIT_FLOAT",
11780 #endif
11781 #ifdef SQLITE_NO_SYNC
11782   "NO_SYNC",
11783 #endif
11784 #ifdef SQLITE_OMIT_ALTERTABLE
11785   "OMIT_ALTERTABLE",
11786 #endif
11787 #ifdef SQLITE_OMIT_ANALYZE
11788   "OMIT_ANALYZE",
11789 #endif
11790 #ifdef SQLITE_OMIT_ATTACH
11791   "OMIT_ATTACH",
11792 #endif
11793 #ifdef SQLITE_OMIT_AUTHORIZATION
11794   "OMIT_AUTHORIZATION",
11795 #endif
11796 #ifdef SQLITE_OMIT_AUTOINCREMENT
11797   "OMIT_AUTOINCREMENT",
11798 #endif
11799 #ifdef SQLITE_OMIT_AUTOINIT
11800   "OMIT_AUTOINIT",
11801 #endif
11802 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
11803   "OMIT_AUTOMATIC_INDEX",
11804 #endif
11805 #ifdef SQLITE_OMIT_AUTORESET
11806   "OMIT_AUTORESET",
11807 #endif
11808 #ifdef SQLITE_OMIT_AUTOVACUUM
11809   "OMIT_AUTOVACUUM",
11810 #endif
11811 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
11812   "OMIT_BETWEEN_OPTIMIZATION",
11813 #endif
11814 #ifdef SQLITE_OMIT_BLOB_LITERAL
11815   "OMIT_BLOB_LITERAL",
11816 #endif
11817 #ifdef SQLITE_OMIT_BTREECOUNT
11818   "OMIT_BTREECOUNT",
11819 #endif
11820 #ifdef SQLITE_OMIT_BUILTIN_TEST
11821   "OMIT_BUILTIN_TEST",
11822 #endif
11823 #ifdef SQLITE_OMIT_CAST
11824   "OMIT_CAST",
11825 #endif
11826 #ifdef SQLITE_OMIT_CHECK
11827   "OMIT_CHECK",
11828 #endif
11829 /* // redundant
11830 ** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
11831 **   "OMIT_COMPILEOPTION_DIAGS",
11832 ** #endif
11833 */
11834 #ifdef SQLITE_OMIT_COMPLETE
11835   "OMIT_COMPLETE",
11836 #endif
11837 #ifdef SQLITE_OMIT_COMPOUND_SELECT
11838   "OMIT_COMPOUND_SELECT",
11839 #endif
11840 #ifdef SQLITE_OMIT_DATETIME_FUNCS
11841   "OMIT_DATETIME_FUNCS",
11842 #endif
11843 #ifdef SQLITE_OMIT_DECLTYPE
11844   "OMIT_DECLTYPE",
11845 #endif
11846 #ifdef SQLITE_OMIT_DEPRECATED
11847   "OMIT_DEPRECATED",
11848 #endif
11849 #ifdef SQLITE_OMIT_DISKIO
11850   "OMIT_DISKIO",
11851 #endif
11852 #ifdef SQLITE_OMIT_EXPLAIN
11853   "OMIT_EXPLAIN",
11854 #endif
11855 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
11856   "OMIT_FLAG_PRAGMAS",
11857 #endif
11858 #ifdef SQLITE_OMIT_FLOATING_POINT
11859   "OMIT_FLOATING_POINT",
11860 #endif
11861 #ifdef SQLITE_OMIT_FOREIGN_KEY
11862   "OMIT_FOREIGN_KEY",
11863 #endif
11864 #ifdef SQLITE_OMIT_GET_TABLE
11865   "OMIT_GET_TABLE",
11866 #endif
11867 #ifdef SQLITE_OMIT_INCRBLOB
11868   "OMIT_INCRBLOB",
11869 #endif
11870 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
11871   "OMIT_INTEGRITY_CHECK",
11872 #endif
11873 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
11874   "OMIT_LIKE_OPTIMIZATION",
11875 #endif
11876 #ifdef SQLITE_OMIT_LOAD_EXTENSION
11877   "OMIT_LOAD_EXTENSION",
11878 #endif
11879 #ifdef SQLITE_OMIT_LOCALTIME
11880   "OMIT_LOCALTIME",
11881 #endif
11882 #ifdef SQLITE_OMIT_LOOKASIDE
11883   "OMIT_LOOKASIDE",
11884 #endif
11885 #ifdef SQLITE_OMIT_MEMORYDB
11886   "OMIT_MEMORYDB",
11887 #endif
11888 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
11889   "OMIT_OR_OPTIMIZATION",
11890 #endif
11891 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
11892   "OMIT_PAGER_PRAGMAS",
11893 #endif
11894 #ifdef SQLITE_OMIT_PRAGMA
11895   "OMIT_PRAGMA",
11896 #endif
11897 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
11898   "OMIT_PROGRESS_CALLBACK",
11899 #endif
11900 #ifdef SQLITE_OMIT_QUICKBALANCE
11901   "OMIT_QUICKBALANCE",
11902 #endif
11903 #ifdef SQLITE_OMIT_REINDEX
11904   "OMIT_REINDEX",
11905 #endif
11906 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
11907   "OMIT_SCHEMA_PRAGMAS",
11908 #endif
11909 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
11910   "OMIT_SCHEMA_VERSION_PRAGMAS",
11911 #endif
11912 #ifdef SQLITE_OMIT_SHARED_CACHE
11913   "OMIT_SHARED_CACHE",
11914 #endif
11915 #ifdef SQLITE_OMIT_SUBQUERY
11916   "OMIT_SUBQUERY",
11917 #endif
11918 #ifdef SQLITE_OMIT_TCL_VARIABLE
11919   "OMIT_TCL_VARIABLE",
11920 #endif
11921 #ifdef SQLITE_OMIT_TEMPDB
11922   "OMIT_TEMPDB",
11923 #endif
11924 #ifdef SQLITE_OMIT_TRACE
11925   "OMIT_TRACE",
11926 #endif
11927 #ifdef SQLITE_OMIT_TRIGGER
11928   "OMIT_TRIGGER",
11929 #endif
11930 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
11931   "OMIT_TRUNCATE_OPTIMIZATION",
11932 #endif
11933 #ifdef SQLITE_OMIT_UTF16
11934   "OMIT_UTF16",
11935 #endif
11936 #ifdef SQLITE_OMIT_VACUUM
11937   "OMIT_VACUUM",
11938 #endif
11939 #ifdef SQLITE_OMIT_VIEW
11940   "OMIT_VIEW",
11941 #endif
11942 #ifdef SQLITE_OMIT_VIRTUALTABLE
11943   "OMIT_VIRTUALTABLE",
11944 #endif
11945 #ifdef SQLITE_OMIT_WAL
11946   "OMIT_WAL",
11947 #endif
11948 #ifdef SQLITE_OMIT_WSD
11949   "OMIT_WSD",
11950 #endif
11951 #ifdef SQLITE_OMIT_XFER_OPT
11952   "OMIT_XFER_OPT",
11953 #endif
11954 #ifdef SQLITE_PERFORMANCE_TRACE
11955   "PERFORMANCE_TRACE",
11956 #endif
11957 #ifdef SQLITE_PROXY_DEBUG
11958   "PROXY_DEBUG",
11959 #endif
11960 #ifdef SQLITE_SECURE_DELETE
11961   "SECURE_DELETE",
11962 #endif
11963 #ifdef SQLITE_SMALL_STACK
11964   "SMALL_STACK",
11965 #endif
11966 #ifdef SQLITE_SOUNDEX
11967   "SOUNDEX",
11968 #endif
11969 #ifdef SQLITE_TCL
11970   "TCL",
11971 #endif
11972 #ifdef SQLITE_TEMP_STORE
11973   "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
11974 #endif
11975 #ifdef SQLITE_TEST
11976   "TEST",
11977 #endif
11978 #ifdef SQLITE_THREADSAFE
11979   "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
11980 #endif
11981 #ifdef SQLITE_USE_ALLOCA
11982   "USE_ALLOCA",
11983 #endif
11984 #ifdef SQLITE_ZERO_MALLOC
11985   "ZERO_MALLOC"
11986 #endif
11987 };
11988
11989 /*
11990 ** Given the name of a compile-time option, return true if that option
11991 ** was used and false if not.
11992 **
11993 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
11994 ** is not required for a match.
11995 */
11996 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
11997   int i, n;
11998   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
11999   n = sqlite3Strlen30(zOptName);
12000
12001   /* Since ArraySize(azCompileOpt) is normally in single digits, a
12002   ** linear search is adequate.  No need for a binary search. */
12003   for(i=0; i<ArraySize(azCompileOpt); i++){
12004     if(   (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
12005        && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
12006   }
12007   return 0;
12008 }
12009
12010 /*
12011 ** Return the N-th compile-time option string.  If N is out of range,
12012 ** return a NULL pointer.
12013 */
12014 SQLITE_API const char *sqlite3_compileoption_get(int N){
12015   if( N>=0 && N<ArraySize(azCompileOpt) ){
12016     return azCompileOpt[N];
12017   }
12018   return 0;
12019 }
12020
12021 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
12022
12023 /************** End of ctime.c ***********************************************/
12024 /************** Begin file status.c ******************************************/
12025 /*
12026 ** 2008 June 18
12027 **
12028 ** The author disclaims copyright to this source code.  In place of
12029 ** a legal notice, here is a blessing:
12030 **
12031 **    May you do good and not evil.
12032 **    May you find forgiveness for yourself and forgive others.
12033 **    May you share freely, never taking more than you give.
12034 **
12035 *************************************************************************
12036 **
12037 ** This module implements the sqlite3_status() interface and related
12038 ** functionality.
12039 */
12040 /************** Include vdbeInt.h in the middle of status.c ******************/
12041 /************** Begin file vdbeInt.h *****************************************/
12042 /*
12043 ** 2003 September 6
12044 **
12045 ** The author disclaims copyright to this source code.  In place of
12046 ** a legal notice, here is a blessing:
12047 **
12048 **    May you do good and not evil.
12049 **    May you find forgiveness for yourself and forgive others.
12050 **    May you share freely, never taking more than you give.
12051 **
12052 *************************************************************************
12053 ** This is the header file for information that is private to the
12054 ** VDBE.  This information used to all be at the top of the single
12055 ** source code file "vdbe.c".  When that file became too big (over
12056 ** 6000 lines long) it was split up into several smaller files and
12057 ** this header information was factored out.
12058 */
12059 #ifndef _VDBEINT_H_
12060 #define _VDBEINT_H_
12061
12062 /*
12063 ** SQL is translated into a sequence of instructions to be
12064 ** executed by a virtual machine.  Each instruction is an instance
12065 ** of the following structure.
12066 */
12067 typedef struct VdbeOp Op;
12068
12069 /*
12070 ** Boolean values
12071 */
12072 typedef unsigned char Bool;
12073
12074 /*
12075 ** A cursor is a pointer into a single BTree within a database file.
12076 ** The cursor can seek to a BTree entry with a particular key, or
12077 ** loop over all entries of the Btree.  You can also insert new BTree
12078 ** entries or retrieve the key or data from the entry that the cursor
12079 ** is currently pointing to.
12080 ** 
12081 ** Every cursor that the virtual machine has open is represented by an
12082 ** instance of the following structure.
12083 */
12084 struct VdbeCursor {
12085   BtCursor *pCursor;    /* The cursor structure of the backend */
12086   Btree *pBt;           /* Separate file holding temporary table */
12087   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
12088   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
12089   int pseudoTableReg;   /* Register holding pseudotable content. */
12090   int nField;           /* Number of fields in the header */
12091   Bool zeroed;          /* True if zeroed out and ready for reuse */
12092   Bool rowidIsValid;    /* True if lastRowid is valid */
12093   Bool atFirst;         /* True if pointing to first entry */
12094   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
12095   Bool nullRow;         /* True if pointing to a row with no data */
12096   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
12097   Bool isTable;         /* True if a table requiring integer keys */
12098   Bool isIndex;         /* True if an index containing keys only - no data */
12099   Bool isOrdered;       /* True if the underlying table is BTREE_UNORDERED */
12100   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
12101   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
12102   i64 seqCount;         /* Sequence counter */
12103   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
12104   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
12105
12106   /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or 
12107   ** OP_IsUnique opcode on this cursor. */
12108   int seekResult;
12109
12110   /* Cached information about the header for the data record that the
12111   ** cursor is currently pointing to.  Only valid if cacheStatus matches
12112   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
12113   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
12114   ** the cache is out of date.
12115   **
12116   ** aRow might point to (ephemeral) data for the current row, or it might
12117   ** be NULL.
12118   */
12119   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
12120   int payloadSize;      /* Total number of bytes in the record */
12121   u32 *aType;           /* Type values for all entries in the record */
12122   u32 *aOffset;         /* Cached offsets to the start of each columns data */
12123   u8 *aRow;             /* Data for the current row, if all on one page */
12124 };
12125 typedef struct VdbeCursor VdbeCursor;
12126
12127 /*
12128 ** When a sub-program is executed (OP_Program), a structure of this type
12129 ** is allocated to store the current value of the program counter, as
12130 ** well as the current memory cell array and various other frame specific
12131 ** values stored in the Vdbe struct. When the sub-program is finished, 
12132 ** these values are copied back to the Vdbe from the VdbeFrame structure,
12133 ** restoring the state of the VM to as it was before the sub-program
12134 ** began executing.
12135 **
12136 ** The memory for a VdbeFrame object is allocated and managed by a memory
12137 ** cell in the parent (calling) frame. When the memory cell is deleted or
12138 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
12139 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
12140 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
12141 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
12142 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
12143 ** child frame are released.
12144 **
12145 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
12146 ** set to NULL if the currently executing frame is the main program.
12147 */
12148 typedef struct VdbeFrame VdbeFrame;
12149 struct VdbeFrame {
12150   Vdbe *v;                /* VM this frame belongs to */
12151   int pc;                 /* Program Counter in parent (calling) frame */
12152   Op *aOp;                /* Program instructions for parent frame */
12153   int nOp;                /* Size of aOp array */
12154   Mem *aMem;              /* Array of memory cells for parent frame */
12155   int nMem;               /* Number of entries in aMem */
12156   VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
12157   u16 nCursor;            /* Number of entries in apCsr */
12158   void *token;            /* Copy of SubProgram.token */
12159   int nChildMem;          /* Number of memory cells for child frame */
12160   int nChildCsr;          /* Number of cursors for child frame */
12161   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
12162   int nChange;            /* Statement changes (Vdbe.nChanges)     */
12163   VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
12164 };
12165
12166 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
12167
12168 /*
12169 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
12170 */
12171 #define CACHE_STALE 0
12172
12173 /*
12174 ** Internally, the vdbe manipulates nearly all SQL values as Mem
12175 ** structures. Each Mem struct may cache multiple representations (string,
12176 ** integer etc.) of the same value.
12177 */
12178 struct Mem {
12179   sqlite3 *db;        /* The associated database connection */
12180   char *z;            /* String or BLOB value */
12181   double r;           /* Real value */
12182   union {
12183     i64 i;              /* Integer value used when MEM_Int is set in flags */
12184     int nZero;          /* Used when bit MEM_Zero is set in flags */
12185     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
12186     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
12187     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
12188   } u;
12189   int n;              /* Number of characters in string value, excluding '\0' */
12190   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
12191   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
12192   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
12193 #ifdef SQLITE_DEBUG
12194   Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
12195   void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
12196 #endif
12197   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
12198   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
12199 };
12200
12201 /* One or more of the following flags are set to indicate the validOK
12202 ** representations of the value stored in the Mem struct.
12203 **
12204 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
12205 ** No other flags may be set in this case.
12206 **
12207 ** If the MEM_Str flag is set then Mem.z points at a string representation.
12208 ** Usually this is encoded in the same unicode encoding as the main
12209 ** database (see below for exceptions). If the MEM_Term flag is also
12210 ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
12211 ** flags may coexist with the MEM_Str flag.
12212 */
12213 #define MEM_Null      0x0001   /* Value is NULL */
12214 #define MEM_Str       0x0002   /* Value is a string */
12215 #define MEM_Int       0x0004   /* Value is an integer */
12216 #define MEM_Real      0x0008   /* Value is a real number */
12217 #define MEM_Blob      0x0010   /* Value is a BLOB */
12218 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
12219 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
12220 #define MEM_Invalid   0x0080   /* Value is undefined */
12221 #define MEM_TypeMask  0x00ff   /* Mask of type bits */
12222
12223 /* Whenever Mem contains a valid string or blob representation, one of
12224 ** the following flags must be set to determine the memory management
12225 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
12226 ** string is \000 or \u0000 terminated
12227 */
12228 #define MEM_Term      0x0200   /* String rep is nul terminated */
12229 #define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
12230 #define MEM_Static    0x0800   /* Mem.z points to a static string */
12231 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
12232 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
12233 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
12234 #ifdef SQLITE_OMIT_INCRBLOB
12235   #undef MEM_Zero
12236   #define MEM_Zero 0x0000
12237 #endif
12238
12239 /*
12240 ** Clear any existing type flags from a Mem and replace them with f
12241 */
12242 #define MemSetTypeFlag(p, f) \
12243    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
12244
12245 /*
12246 ** Return true if a memory cell is not marked as invalid.  This macro
12247 ** is for use inside assert() statements only.
12248 */
12249 #ifdef SQLITE_DEBUG
12250 #define memIsValid(M)  ((M)->flags & MEM_Invalid)==0
12251 #endif
12252
12253
12254 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
12255 ** additional information about auxiliary information bound to arguments
12256 ** of the function.  This is used to implement the sqlite3_get_auxdata()
12257 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
12258 ** that can be associated with a constant argument to a function.  This
12259 ** allows functions such as "regexp" to compile their constant regular
12260 ** expression argument once and reused the compiled code for multiple
12261 ** invocations.
12262 */
12263 struct VdbeFunc {
12264   FuncDef *pFunc;               /* The definition of the function */
12265   int nAux;                     /* Number of entries allocated for apAux[] */
12266   struct AuxData {
12267     void *pAux;                   /* Aux data for the i-th argument */
12268     void (*xDelete)(void *);      /* Destructor for the aux data */
12269   } apAux[1];                   /* One slot for each function argument */
12270 };
12271
12272 /*
12273 ** The "context" argument for a installable function.  A pointer to an
12274 ** instance of this structure is the first argument to the routines used
12275 ** implement the SQL functions.
12276 **
12277 ** There is a typedef for this structure in sqlite.h.  So all routines,
12278 ** even the public interface to SQLite, can use a pointer to this structure.
12279 ** But this file is the only place where the internal details of this
12280 ** structure are known.
12281 **
12282 ** This structure is defined inside of vdbeInt.h because it uses substructures
12283 ** (Mem) which are only defined there.
12284 */
12285 struct sqlite3_context {
12286   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
12287   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
12288   Mem s;                /* The return value is stored here */
12289   Mem *pMem;            /* Memory cell used to store aggregate context */
12290   int isError;          /* Error code returned by the function. */
12291   CollSeq *pColl;       /* Collating sequence */
12292 };
12293
12294 /*
12295 ** An instance of the virtual machine.  This structure contains the complete
12296 ** state of the virtual machine.
12297 **
12298 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
12299 ** is really a pointer to an instance of this structure.
12300 **
12301 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
12302 ** any virtual table method invocations made by the vdbe program. It is
12303 ** set to 2 for xDestroy method calls and 1 for all other methods. This
12304 ** variable is used for two purposes: to allow xDestroy methods to execute
12305 ** "DROP TABLE" statements and to prevent some nasty side effects of
12306 ** malloc failure when SQLite is invoked recursively by a virtual table 
12307 ** method function.
12308 */
12309 struct Vdbe {
12310   sqlite3 *db;            /* The database connection that owns this statement */
12311   Op *aOp;                /* Space to hold the virtual machine's program */
12312   Mem *aMem;              /* The memory locations */
12313   Mem **apArg;            /* Arguments to currently executing user function */
12314   Mem *aColName;          /* Column names to return */
12315   Mem *pResultSet;        /* Pointer to an array of results */
12316   int nMem;               /* Number of memory locations currently allocated */
12317   int nOp;                /* Number of instructions in the program */
12318   int nOpAlloc;           /* Number of slots allocated for aOp[] */
12319   int nLabel;             /* Number of labels used */
12320   int nLabelAlloc;        /* Number of slots allocated in aLabel[] */
12321   int *aLabel;            /* Space to hold the labels */
12322   u16 nResColumn;         /* Number of columns in one row of the result set */
12323   u16 nCursor;            /* Number of slots in apCsr[] */
12324   u32 magic;              /* Magic number for sanity checking */
12325   char *zErrMsg;          /* Error message written here */
12326   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
12327   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
12328   Mem *aVar;              /* Values for the OP_Variable opcode. */
12329   char **azVar;           /* Name of variables */
12330   ynVar nVar;             /* Number of entries in aVar[] */
12331   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
12332   int pc;                 /* The program counter */
12333   int rc;                 /* Value to return */
12334   u8 errorAction;         /* Recovery action to do in case of an error */
12335   u8 okVar;               /* True if azVar[] has been initialized */
12336   u8 explain;             /* True if EXPLAIN present on SQL command */
12337   u8 changeCntOn;         /* True to update the change-counter */
12338   u8 expired;             /* True if the VM needs to be recompiled */
12339   u8 runOnlyOnce;         /* Automatically expire on reset */
12340   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
12341   u8 inVtabMethod;        /* See comments above */
12342   u8 usesStmtJournal;     /* True if uses a statement journal */
12343   u8 readOnly;            /* True for read-only statements */
12344   u8 isPrepareV2;         /* True if prepared with prepare_v2() */
12345   int nChange;            /* Number of db changes made since last reset */
12346   int btreeMask;          /* Bitmask of db->aDb[] entries referenced */
12347   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
12348   int aCounter[3];        /* Counters used by sqlite3_stmt_status() */
12349   BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
12350 #ifndef SQLITE_OMIT_TRACE
12351   i64 startTime;          /* Time when query started - used for profiling */
12352 #endif
12353   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
12354   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
12355   char *zSql;             /* Text of the SQL statement that generated this */
12356   void *pFree;            /* Free this when deleting the vdbe */
12357 #ifdef SQLITE_DEBUG
12358   FILE *trace;            /* Write an execution trace here, if not NULL */
12359 #endif
12360   VdbeFrame *pFrame;      /* Parent frame */
12361   VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
12362   int nFrame;             /* Number of frames in pFrame list */
12363   u32 expmask;            /* Binding to these vars invalidates VM */
12364   SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
12365 };
12366
12367 /*
12368 ** The following are allowed values for Vdbe.magic
12369 */
12370 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
12371 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
12372 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
12373 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
12374
12375 /*
12376 ** Function prototypes
12377 */
12378 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
12379 void sqliteVdbePopStack(Vdbe*,int);
12380 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
12381 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
12382 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
12383 #endif
12384 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
12385 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
12386 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
12387 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
12388 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
12389
12390 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
12391 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
12392 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
12393 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
12394 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
12395 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
12396 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
12397 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
12398 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
12399 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
12400 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
12401 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
12402 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
12403 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
12404 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
12405 #ifdef SQLITE_OMIT_FLOATING_POINT
12406 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
12407 #else
12408 SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
12409 #endif
12410 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
12411 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
12412 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
12413 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
12414 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
12415 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
12416 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
12417 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
12418 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
12419 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
12420 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
12421 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
12422 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
12423 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
12424 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
12425 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
12426 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
12427 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
12428 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
12429 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
12430 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
12431
12432 #ifdef SQLITE_DEBUG
12433 SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe*,Mem*);
12434 #endif
12435
12436 #ifndef SQLITE_OMIT_FOREIGN_KEY
12437 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
12438 #else
12439 # define sqlite3VdbeCheckFk(p,i) 0
12440 #endif
12441
12442 #ifndef SQLITE_OMIT_SHARED_CACHE
12443 SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p);
12444 #else
12445 # define sqlite3VdbeMutexArrayEnter(p)
12446 #endif
12447
12448 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
12449 #ifdef SQLITE_DEBUG
12450 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
12451 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
12452 #endif
12453 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
12454
12455 #ifndef SQLITE_OMIT_INCRBLOB
12456 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
12457 #else
12458   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
12459 #endif
12460
12461 #endif /* !defined(_VDBEINT_H_) */
12462
12463 /************** End of vdbeInt.h *********************************************/
12464 /************** Continuing where we left off in status.c *********************/
12465
12466 /*
12467 ** Variables in which to record status information.
12468 */
12469 typedef struct sqlite3StatType sqlite3StatType;
12470 static SQLITE_WSD struct sqlite3StatType {
12471   int nowValue[10];         /* Current value */
12472   int mxValue[10];          /* Maximum value */
12473 } sqlite3Stat = { {0,}, {0,} };
12474
12475
12476 /* The "wsdStat" macro will resolve to the status information
12477 ** state vector.  If writable static data is unsupported on the target,
12478 ** we have to locate the state vector at run-time.  In the more common
12479 ** case where writable static data is supported, wsdStat can refer directly
12480 ** to the "sqlite3Stat" state vector declared above.
12481 */
12482 #ifdef SQLITE_OMIT_WSD
12483 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
12484 # define wsdStat x[0]
12485 #else
12486 # define wsdStatInit
12487 # define wsdStat sqlite3Stat
12488 #endif
12489
12490 /*
12491 ** Return the current value of a status parameter.
12492 */
12493 SQLITE_PRIVATE int sqlite3StatusValue(int op){
12494   wsdStatInit;
12495   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12496   return wsdStat.nowValue[op];
12497 }
12498
12499 /*
12500 ** Add N to the value of a status record.  It is assumed that the
12501 ** caller holds appropriate locks.
12502 */
12503 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
12504   wsdStatInit;
12505   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12506   wsdStat.nowValue[op] += N;
12507   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
12508     wsdStat.mxValue[op] = wsdStat.nowValue[op];
12509   }
12510 }
12511
12512 /*
12513 ** Set the value of a status to X.
12514 */
12515 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
12516   wsdStatInit;
12517   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12518   wsdStat.nowValue[op] = X;
12519   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
12520     wsdStat.mxValue[op] = wsdStat.nowValue[op];
12521   }
12522 }
12523
12524 /*
12525 ** Query status information.
12526 **
12527 ** This implementation assumes that reading or writing an aligned
12528 ** 32-bit integer is an atomic operation.  If that assumption is not true,
12529 ** then this routine is not threadsafe.
12530 */
12531 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
12532   wsdStatInit;
12533   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
12534     return SQLITE_MISUSE_BKPT;
12535   }
12536   *pCurrent = wsdStat.nowValue[op];
12537   *pHighwater = wsdStat.mxValue[op];
12538   if( resetFlag ){
12539     wsdStat.mxValue[op] = wsdStat.nowValue[op];
12540   }
12541   return SQLITE_OK;
12542 }
12543
12544 /*
12545 ** Query status information for a single database connection
12546 */
12547 SQLITE_API int sqlite3_db_status(
12548   sqlite3 *db,          /* The database connection whose status is desired */
12549   int op,               /* Status verb */
12550   int *pCurrent,        /* Write current value here */
12551   int *pHighwater,      /* Write high-water mark here */
12552   int resetFlag         /* Reset high-water mark if true */
12553 ){
12554   int rc = SQLITE_OK;   /* Return code */
12555   sqlite3_mutex_enter(db->mutex);
12556   switch( op ){
12557     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
12558       *pCurrent = db->lookaside.nOut;
12559       *pHighwater = db->lookaside.mxOut;
12560       if( resetFlag ){
12561         db->lookaside.mxOut = db->lookaside.nOut;
12562       }
12563       break;
12564     }
12565
12566     case SQLITE_DBSTATUS_LOOKASIDE_HIT:
12567     case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
12568     case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
12569       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
12570       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
12571       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
12572       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
12573       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
12574       *pCurrent = 0;
12575       *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
12576       if( resetFlag ){
12577         db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
12578       }
12579       break;
12580     }
12581
12582     /* 
12583     ** Return an approximation for the amount of memory currently used
12584     ** by all pagers associated with the given database connection.  The
12585     ** highwater mark is meaningless and is returned as zero.
12586     */
12587     case SQLITE_DBSTATUS_CACHE_USED: {
12588       int totalUsed = 0;
12589       int i;
12590       sqlite3BtreeEnterAll(db);
12591       for(i=0; i<db->nDb; i++){
12592         Btree *pBt = db->aDb[i].pBt;
12593         if( pBt ){
12594           Pager *pPager = sqlite3BtreePager(pBt);
12595           totalUsed += sqlite3PagerMemUsed(pPager);
12596         }
12597       }
12598       sqlite3BtreeLeaveAll(db);
12599       *pCurrent = totalUsed;
12600       *pHighwater = 0;
12601       break;
12602     }
12603
12604     /*
12605     ** *pCurrent gets an accurate estimate of the amount of memory used
12606     ** to store the schema for all databases (main, temp, and any ATTACHed
12607     ** databases.  *pHighwater is set to zero.
12608     */
12609     case SQLITE_DBSTATUS_SCHEMA_USED: {
12610       int i;                      /* Used to iterate through schemas */
12611       int nByte = 0;              /* Used to accumulate return value */
12612
12613       db->pnBytesFreed = &nByte;
12614       for(i=0; i<db->nDb; i++){
12615         Schema *pSchema = db->aDb[i].pSchema;
12616         if( ALWAYS(pSchema!=0) ){
12617           HashElem *p;
12618
12619           nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
12620               pSchema->tblHash.count 
12621             + pSchema->trigHash.count
12622             + pSchema->idxHash.count
12623             + pSchema->fkeyHash.count
12624           );
12625           nByte += sqlite3MallocSize(pSchema->tblHash.ht);
12626           nByte += sqlite3MallocSize(pSchema->trigHash.ht);
12627           nByte += sqlite3MallocSize(pSchema->idxHash.ht);
12628           nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
12629
12630           for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
12631             sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
12632           }
12633           for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
12634             sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
12635           }
12636         }
12637       }
12638       db->pnBytesFreed = 0;
12639
12640       *pHighwater = 0;
12641       *pCurrent = nByte;
12642       break;
12643     }
12644
12645     /*
12646     ** *pCurrent gets an accurate estimate of the amount of memory used
12647     ** to store all prepared statements.
12648     ** *pHighwater is set to zero.
12649     */
12650     case SQLITE_DBSTATUS_STMT_USED: {
12651       struct Vdbe *pVdbe;         /* Used to iterate through VMs */
12652       int nByte = 0;              /* Used to accumulate return value */
12653
12654       db->pnBytesFreed = &nByte;
12655       for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
12656         sqlite3VdbeDeleteObject(db, pVdbe);
12657       }
12658       db->pnBytesFreed = 0;
12659
12660       *pHighwater = 0;
12661       *pCurrent = nByte;
12662
12663       break;
12664     }
12665
12666     default: {
12667       rc = SQLITE_ERROR;
12668     }
12669   }
12670   sqlite3_mutex_leave(db->mutex);
12671   return rc;
12672 }
12673
12674 /************** End of status.c **********************************************/
12675 /************** Begin file date.c ********************************************/
12676 /*
12677 ** 2003 October 31
12678 **
12679 ** The author disclaims copyright to this source code.  In place of
12680 ** a legal notice, here is a blessing:
12681 **
12682 **    May you do good and not evil.
12683 **    May you find forgiveness for yourself and forgive others.
12684 **    May you share freely, never taking more than you give.
12685 **
12686 *************************************************************************
12687 ** This file contains the C functions that implement date and time
12688 ** functions for SQLite.  
12689 **
12690 ** There is only one exported symbol in this file - the function
12691 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
12692 ** All other code has file scope.
12693 **
12694 ** SQLite processes all times and dates as Julian Day numbers.  The
12695 ** dates and times are stored as the number of days since noon
12696 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
12697 ** calendar system. 
12698 **
12699 ** 1970-01-01 00:00:00 is JD 2440587.5
12700 ** 2000-01-01 00:00:00 is JD 2451544.5
12701 **
12702 ** This implemention requires years to be expressed as a 4-digit number
12703 ** which means that only dates between 0000-01-01 and 9999-12-31 can
12704 ** be represented, even though julian day numbers allow a much wider
12705 ** range of dates.
12706 **
12707 ** The Gregorian calendar system is used for all dates and times,
12708 ** even those that predate the Gregorian calendar.  Historians usually
12709 ** use the Julian calendar for dates prior to 1582-10-15 and for some
12710 ** dates afterwards, depending on locale.  Beware of this difference.
12711 **
12712 ** The conversion algorithms are implemented based on descriptions
12713 ** in the following text:
12714 **
12715 **      Jean Meeus
12716 **      Astronomical Algorithms, 2nd Edition, 1998
12717 **      ISBM 0-943396-61-1
12718 **      Willmann-Bell, Inc
12719 **      Richmond, Virginia (USA)
12720 */
12721 #include <time.h>
12722
12723 #ifndef SQLITE_OMIT_DATETIME_FUNCS
12724
12725 /*
12726 ** On recent Windows platforms, the localtime_s() function is available
12727 ** as part of the "Secure CRT". It is essentially equivalent to 
12728 ** localtime_r() available under most POSIX platforms, except that the 
12729 ** order of the parameters is reversed.
12730 **
12731 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
12732 **
12733 ** If the user has not indicated to use localtime_r() or localtime_s()
12734 ** already, check for an MSVC build environment that provides 
12735 ** localtime_s().
12736 */
12737 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
12738      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
12739 #define HAVE_LOCALTIME_S 1
12740 #endif
12741
12742 /*
12743 ** A structure for holding a single date and time.
12744 */
12745 typedef struct DateTime DateTime;
12746 struct DateTime {
12747   sqlite3_int64 iJD; /* The julian day number times 86400000 */
12748   int Y, M, D;       /* Year, month, and day */
12749   int h, m;          /* Hour and minutes */
12750   int tz;            /* Timezone offset in minutes */
12751   double s;          /* Seconds */
12752   char validYMD;     /* True (1) if Y,M,D are valid */
12753   char validHMS;     /* True (1) if h,m,s are valid */
12754   char validJD;      /* True (1) if iJD is valid */
12755   char validTZ;      /* True (1) if tz is valid */
12756 };
12757
12758
12759 /*
12760 ** Convert zDate into one or more integers.  Additional arguments
12761 ** come in groups of 5 as follows:
12762 **
12763 **       N       number of digits in the integer
12764 **       min     minimum allowed value of the integer
12765 **       max     maximum allowed value of the integer
12766 **       nextC   first character after the integer
12767 **       pVal    where to write the integers value.
12768 **
12769 ** Conversions continue until one with nextC==0 is encountered.
12770 ** The function returns the number of successful conversions.
12771 */
12772 static int getDigits(const char *zDate, ...){
12773   va_list ap;
12774   int val;
12775   int N;
12776   int min;
12777   int max;
12778   int nextC;
12779   int *pVal;
12780   int cnt = 0;
12781   va_start(ap, zDate);
12782   do{
12783     N = va_arg(ap, int);
12784     min = va_arg(ap, int);
12785     max = va_arg(ap, int);
12786     nextC = va_arg(ap, int);
12787     pVal = va_arg(ap, int*);
12788     val = 0;
12789     while( N-- ){
12790       if( !sqlite3Isdigit(*zDate) ){
12791         goto end_getDigits;
12792       }
12793       val = val*10 + *zDate - '0';
12794       zDate++;
12795     }
12796     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
12797       goto end_getDigits;
12798     }
12799     *pVal = val;
12800     zDate++;
12801     cnt++;
12802   }while( nextC );
12803 end_getDigits:
12804   va_end(ap);
12805   return cnt;
12806 }
12807
12808 /*
12809 ** Parse a timezone extension on the end of a date-time.
12810 ** The extension is of the form:
12811 **
12812 **        (+/-)HH:MM
12813 **
12814 ** Or the "zulu" notation:
12815 **
12816 **        Z
12817 **
12818 ** If the parse is successful, write the number of minutes
12819 ** of change in p->tz and return 0.  If a parser error occurs,
12820 ** return non-zero.
12821 **
12822 ** A missing specifier is not considered an error.
12823 */
12824 static int parseTimezone(const char *zDate, DateTime *p){
12825   int sgn = 0;
12826   int nHr, nMn;
12827   int c;
12828   while( sqlite3Isspace(*zDate) ){ zDate++; }
12829   p->tz = 0;
12830   c = *zDate;
12831   if( c=='-' ){
12832     sgn = -1;
12833   }else if( c=='+' ){
12834     sgn = +1;
12835   }else if( c=='Z' || c=='z' ){
12836     zDate++;
12837     goto zulu_time;
12838   }else{
12839     return c!=0;
12840   }
12841   zDate++;
12842   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
12843     return 1;
12844   }
12845   zDate += 5;
12846   p->tz = sgn*(nMn + nHr*60);
12847 zulu_time:
12848   while( sqlite3Isspace(*zDate) ){ zDate++; }
12849   return *zDate!=0;
12850 }
12851
12852 /*
12853 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
12854 ** The HH, MM, and SS must each be exactly 2 digits.  The
12855 ** fractional seconds FFFF can be one or more digits.
12856 **
12857 ** Return 1 if there is a parsing error and 0 on success.
12858 */
12859 static int parseHhMmSs(const char *zDate, DateTime *p){
12860   int h, m, s;
12861   double ms = 0.0;
12862   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
12863     return 1;
12864   }
12865   zDate += 5;
12866   if( *zDate==':' ){
12867     zDate++;
12868     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
12869       return 1;
12870     }
12871     zDate += 2;
12872     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
12873       double rScale = 1.0;
12874       zDate++;
12875       while( sqlite3Isdigit(*zDate) ){
12876         ms = ms*10.0 + *zDate - '0';
12877         rScale *= 10.0;
12878         zDate++;
12879       }
12880       ms /= rScale;
12881     }
12882   }else{
12883     s = 0;
12884   }
12885   p->validJD = 0;
12886   p->validHMS = 1;
12887   p->h = h;
12888   p->m = m;
12889   p->s = s + ms;
12890   if( parseTimezone(zDate, p) ) return 1;
12891   p->validTZ = (p->tz!=0)?1:0;
12892   return 0;
12893 }
12894
12895 /*
12896 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
12897 ** that the YYYY-MM-DD is according to the Gregorian calendar.
12898 **
12899 ** Reference:  Meeus page 61
12900 */
12901 static void computeJD(DateTime *p){
12902   int Y, M, D, A, B, X1, X2;
12903
12904   if( p->validJD ) return;
12905   if( p->validYMD ){
12906     Y = p->Y;
12907     M = p->M;
12908     D = p->D;
12909   }else{
12910     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
12911     M = 1;
12912     D = 1;
12913   }
12914   if( M<=2 ){
12915     Y--;
12916     M += 12;
12917   }
12918   A = Y/100;
12919   B = 2 - A + (A/4);
12920   X1 = 36525*(Y+4716)/100;
12921   X2 = 306001*(M+1)/10000;
12922   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
12923   p->validJD = 1;
12924   if( p->validHMS ){
12925     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
12926     if( p->validTZ ){
12927       p->iJD -= p->tz*60000;
12928       p->validYMD = 0;
12929       p->validHMS = 0;
12930       p->validTZ = 0;
12931     }
12932   }
12933 }
12934
12935 /*
12936 ** Parse dates of the form
12937 **
12938 **     YYYY-MM-DD HH:MM:SS.FFF
12939 **     YYYY-MM-DD HH:MM:SS
12940 **     YYYY-MM-DD HH:MM
12941 **     YYYY-MM-DD
12942 **
12943 ** Write the result into the DateTime structure and return 0
12944 ** on success and 1 if the input string is not a well-formed
12945 ** date.
12946 */
12947 static int parseYyyyMmDd(const char *zDate, DateTime *p){
12948   int Y, M, D, neg;
12949
12950   if( zDate[0]=='-' ){
12951     zDate++;
12952     neg = 1;
12953   }else{
12954     neg = 0;
12955   }
12956   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
12957     return 1;
12958   }
12959   zDate += 10;
12960   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
12961   if( parseHhMmSs(zDate, p)==0 ){
12962     /* We got the time */
12963   }else if( *zDate==0 ){
12964     p->validHMS = 0;
12965   }else{
12966     return 1;
12967   }
12968   p->validJD = 0;
12969   p->validYMD = 1;
12970   p->Y = neg ? -Y : Y;
12971   p->M = M;
12972   p->D = D;
12973   if( p->validTZ ){
12974     computeJD(p);
12975   }
12976   return 0;
12977 }
12978
12979 /*
12980 ** Set the time to the current time reported by the VFS
12981 */
12982 static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
12983   sqlite3 *db = sqlite3_context_db_handle(context);
12984   sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD);
12985   p->validJD = 1;
12986 }
12987
12988 /*
12989 ** Attempt to parse the given string into a Julian Day Number.  Return
12990 ** the number of errors.
12991 **
12992 ** The following are acceptable forms for the input string:
12993 **
12994 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
12995 **      DDDD.DD 
12996 **      now
12997 **
12998 ** In the first form, the +/-HH:MM is always optional.  The fractional
12999 ** seconds extension (the ".FFF") is optional.  The seconds portion
13000 ** (":SS.FFF") is option.  The year and date can be omitted as long
13001 ** as there is a time string.  The time string can be omitted as long
13002 ** as there is a year and date.
13003 */
13004 static int parseDateOrTime(
13005   sqlite3_context *context, 
13006   const char *zDate, 
13007   DateTime *p
13008 ){
13009   double r;
13010   if( parseYyyyMmDd(zDate,p)==0 ){
13011     return 0;
13012   }else if( parseHhMmSs(zDate, p)==0 ){
13013     return 0;
13014   }else if( sqlite3StrICmp(zDate,"now")==0){
13015     setDateTimeToCurrent(context, p);
13016     return 0;
13017   }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
13018     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
13019     p->validJD = 1;
13020     return 0;
13021   }
13022   return 1;
13023 }
13024
13025 /*
13026 ** Compute the Year, Month, and Day from the julian day number.
13027 */
13028 static void computeYMD(DateTime *p){
13029   int Z, A, B, C, D, E, X1;
13030   if( p->validYMD ) return;
13031   if( !p->validJD ){
13032     p->Y = 2000;
13033     p->M = 1;
13034     p->D = 1;
13035   }else{
13036     Z = (int)((p->iJD + 43200000)/86400000);
13037     A = (int)((Z - 1867216.25)/36524.25);
13038     A = Z + 1 + A - (A/4);
13039     B = A + 1524;
13040     C = (int)((B - 122.1)/365.25);
13041     D = (36525*C)/100;
13042     E = (int)((B-D)/30.6001);
13043     X1 = (int)(30.6001*E);
13044     p->D = B - D - X1;
13045     p->M = E<14 ? E-1 : E-13;
13046     p->Y = p->M>2 ? C - 4716 : C - 4715;
13047   }
13048   p->validYMD = 1;
13049 }
13050
13051 /*
13052 ** Compute the Hour, Minute, and Seconds from the julian day number.
13053 */
13054 static void computeHMS(DateTime *p){
13055   int s;
13056   if( p->validHMS ) return;
13057   computeJD(p);
13058   s = (int)((p->iJD + 43200000) % 86400000);
13059   p->s = s/1000.0;
13060   s = (int)p->s;
13061   p->s -= s;
13062   p->h = s/3600;
13063   s -= p->h*3600;
13064   p->m = s/60;
13065   p->s += s - p->m*60;
13066   p->validHMS = 1;
13067 }
13068
13069 /*
13070 ** Compute both YMD and HMS
13071 */
13072 static void computeYMD_HMS(DateTime *p){
13073   computeYMD(p);
13074   computeHMS(p);
13075 }
13076
13077 /*
13078 ** Clear the YMD and HMS and the TZ
13079 */
13080 static void clearYMD_HMS_TZ(DateTime *p){
13081   p->validYMD = 0;
13082   p->validHMS = 0;
13083   p->validTZ = 0;
13084 }
13085
13086 #ifndef SQLITE_OMIT_LOCALTIME
13087 /*
13088 ** Compute the difference (in milliseconds)
13089 ** between localtime and UTC (a.k.a. GMT)
13090 ** for the time value p where p is in UTC.
13091 */
13092 static sqlite3_int64 localtimeOffset(DateTime *p){
13093   DateTime x, y;
13094   time_t t;
13095   x = *p;
13096   computeYMD_HMS(&x);
13097   if( x.Y<1971 || x.Y>=2038 ){
13098     x.Y = 2000;
13099     x.M = 1;
13100     x.D = 1;
13101     x.h = 0;
13102     x.m = 0;
13103     x.s = 0.0;
13104   } else {
13105     int s = (int)(x.s + 0.5);
13106     x.s = s;
13107   }
13108   x.tz = 0;
13109   x.validJD = 0;
13110   computeJD(&x);
13111   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
13112 #ifdef HAVE_LOCALTIME_R
13113   {
13114     struct tm sLocal;
13115     localtime_r(&t, &sLocal);
13116     y.Y = sLocal.tm_year + 1900;
13117     y.M = sLocal.tm_mon + 1;
13118     y.D = sLocal.tm_mday;
13119     y.h = sLocal.tm_hour;
13120     y.m = sLocal.tm_min;
13121     y.s = sLocal.tm_sec;
13122   }
13123 #elif defined(HAVE_LOCALTIME_S) && HAVE_LOCALTIME_S
13124   {
13125     struct tm sLocal;
13126     localtime_s(&sLocal, &t);
13127     y.Y = sLocal.tm_year + 1900;
13128     y.M = sLocal.tm_mon + 1;
13129     y.D = sLocal.tm_mday;
13130     y.h = sLocal.tm_hour;
13131     y.m = sLocal.tm_min;
13132     y.s = sLocal.tm_sec;
13133   }
13134 #else
13135   {
13136     struct tm *pTm;
13137     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13138     pTm = localtime(&t);
13139     y.Y = pTm->tm_year + 1900;
13140     y.M = pTm->tm_mon + 1;
13141     y.D = pTm->tm_mday;
13142     y.h = pTm->tm_hour;
13143     y.m = pTm->tm_min;
13144     y.s = pTm->tm_sec;
13145     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13146   }
13147 #endif
13148   y.validYMD = 1;
13149   y.validHMS = 1;
13150   y.validJD = 0;
13151   y.validTZ = 0;
13152   computeJD(&y);
13153   return y.iJD - x.iJD;
13154 }
13155 #endif /* SQLITE_OMIT_LOCALTIME */
13156
13157 /*
13158 ** Process a modifier to a date-time stamp.  The modifiers are
13159 ** as follows:
13160 **
13161 **     NNN days
13162 **     NNN hours
13163 **     NNN minutes
13164 **     NNN.NNNN seconds
13165 **     NNN months
13166 **     NNN years
13167 **     start of month
13168 **     start of year
13169 **     start of week
13170 **     start of day
13171 **     weekday N
13172 **     unixepoch
13173 **     localtime
13174 **     utc
13175 **
13176 ** Return 0 on success and 1 if there is any kind of error.
13177 */
13178 static int parseModifier(const char *zMod, DateTime *p){
13179   int rc = 1;
13180   int n;
13181   double r;
13182   char *z, zBuf[30];
13183   z = zBuf;
13184   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
13185     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
13186   }
13187   z[n] = 0;
13188   switch( z[0] ){
13189 #ifndef SQLITE_OMIT_LOCALTIME
13190     case 'l': {
13191       /*    localtime
13192       **
13193       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
13194       ** show local time.
13195       */
13196       if( strcmp(z, "localtime")==0 ){
13197         computeJD(p);
13198         p->iJD += localtimeOffset(p);
13199         clearYMD_HMS_TZ(p);
13200         rc = 0;
13201       }
13202       break;
13203     }
13204 #endif
13205     case 'u': {
13206       /*
13207       **    unixepoch
13208       **
13209       ** Treat the current value of p->iJD as the number of
13210       ** seconds since 1970.  Convert to a real julian day number.
13211       */
13212       if( strcmp(z, "unixepoch")==0 && p->validJD ){
13213         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
13214         clearYMD_HMS_TZ(p);
13215         rc = 0;
13216       }
13217 #ifndef SQLITE_OMIT_LOCALTIME
13218       else if( strcmp(z, "utc")==0 ){
13219         sqlite3_int64 c1;
13220         computeJD(p);
13221         c1 = localtimeOffset(p);
13222         p->iJD -= c1;
13223         clearYMD_HMS_TZ(p);
13224         p->iJD += c1 - localtimeOffset(p);
13225         rc = 0;
13226       }
13227 #endif
13228       break;
13229     }
13230     case 'w': {
13231       /*
13232       **    weekday N
13233       **
13234       ** Move the date to the same time on the next occurrence of
13235       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
13236       ** date is already on the appropriate weekday, this is a no-op.
13237       */
13238       if( strncmp(z, "weekday ", 8)==0
13239                && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
13240                && (n=(int)r)==r && n>=0 && r<7 ){
13241         sqlite3_int64 Z;
13242         computeYMD_HMS(p);
13243         p->validTZ = 0;
13244         p->validJD = 0;
13245         computeJD(p);
13246         Z = ((p->iJD + 129600000)/86400000) % 7;
13247         if( Z>n ) Z -= 7;
13248         p->iJD += (n - Z)*86400000;
13249         clearYMD_HMS_TZ(p);
13250         rc = 0;
13251       }
13252       break;
13253     }
13254     case 's': {
13255       /*
13256       **    start of TTTTT
13257       **
13258       ** Move the date backwards to the beginning of the current day,
13259       ** or month or year.
13260       */
13261       if( strncmp(z, "start of ", 9)!=0 ) break;
13262       z += 9;
13263       computeYMD(p);
13264       p->validHMS = 1;
13265       p->h = p->m = 0;
13266       p->s = 0.0;
13267       p->validTZ = 0;
13268       p->validJD = 0;
13269       if( strcmp(z,"month")==0 ){
13270         p->D = 1;
13271         rc = 0;
13272       }else if( strcmp(z,"year")==0 ){
13273         computeYMD(p);
13274         p->M = 1;
13275         p->D = 1;
13276         rc = 0;
13277       }else if( strcmp(z,"day")==0 ){
13278         rc = 0;
13279       }
13280       break;
13281     }
13282     case '+':
13283     case '-':
13284     case '0':
13285     case '1':
13286     case '2':
13287     case '3':
13288     case '4':
13289     case '5':
13290     case '6':
13291     case '7':
13292     case '8':
13293     case '9': {
13294       double rRounder;
13295       for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
13296       if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
13297         rc = 1;
13298         break;
13299       }
13300       if( z[n]==':' ){
13301         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
13302         ** specified number of hours, minutes, seconds, and fractional seconds
13303         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
13304         ** omitted.
13305         */
13306         const char *z2 = z;
13307         DateTime tx;
13308         sqlite3_int64 day;
13309         if( !sqlite3Isdigit(*z2) ) z2++;
13310         memset(&tx, 0, sizeof(tx));
13311         if( parseHhMmSs(z2, &tx) ) break;
13312         computeJD(&tx);
13313         tx.iJD -= 43200000;
13314         day = tx.iJD/86400000;
13315         tx.iJD -= day*86400000;
13316         if( z[0]=='-' ) tx.iJD = -tx.iJD;
13317         computeJD(p);
13318         clearYMD_HMS_TZ(p);
13319         p->iJD += tx.iJD;
13320         rc = 0;
13321         break;
13322       }
13323       z += n;
13324       while( sqlite3Isspace(*z) ) z++;
13325       n = sqlite3Strlen30(z);
13326       if( n>10 || n<3 ) break;
13327       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
13328       computeJD(p);
13329       rc = 0;
13330       rRounder = r<0 ? -0.5 : +0.5;
13331       if( n==3 && strcmp(z,"day")==0 ){
13332         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
13333       }else if( n==4 && strcmp(z,"hour")==0 ){
13334         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
13335       }else if( n==6 && strcmp(z,"minute")==0 ){
13336         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
13337       }else if( n==6 && strcmp(z,"second")==0 ){
13338         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
13339       }else if( n==5 && strcmp(z,"month")==0 ){
13340         int x, y;
13341         computeYMD_HMS(p);
13342         p->M += (int)r;
13343         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
13344         p->Y += x;
13345         p->M -= x*12;
13346         p->validJD = 0;
13347         computeJD(p);
13348         y = (int)r;
13349         if( y!=r ){
13350           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
13351         }
13352       }else if( n==4 && strcmp(z,"year")==0 ){
13353         int y = (int)r;
13354         computeYMD_HMS(p);
13355         p->Y += y;
13356         p->validJD = 0;
13357         computeJD(p);
13358         if( y!=r ){
13359           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
13360         }
13361       }else{
13362         rc = 1;
13363       }
13364       clearYMD_HMS_TZ(p);
13365       break;
13366     }
13367     default: {
13368       break;
13369     }
13370   }
13371   return rc;
13372 }
13373
13374 /*
13375 ** Process time function arguments.  argv[0] is a date-time stamp.
13376 ** argv[1] and following are modifiers.  Parse them all and write
13377 ** the resulting time into the DateTime structure p.  Return 0
13378 ** on success and 1 if there are any errors.
13379 **
13380 ** If there are zero parameters (if even argv[0] is undefined)
13381 ** then assume a default value of "now" for argv[0].
13382 */
13383 static int isDate(
13384   sqlite3_context *context, 
13385   int argc, 
13386   sqlite3_value **argv, 
13387   DateTime *p
13388 ){
13389   int i;
13390   const unsigned char *z;
13391   int eType;
13392   memset(p, 0, sizeof(*p));
13393   if( argc==0 ){
13394     setDateTimeToCurrent(context, p);
13395   }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
13396                    || eType==SQLITE_INTEGER ){
13397     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
13398     p->validJD = 1;
13399   }else{
13400     z = sqlite3_value_text(argv[0]);
13401     if( !z || parseDateOrTime(context, (char*)z, p) ){
13402       return 1;
13403     }
13404   }
13405   for(i=1; i<argc; i++){
13406     if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
13407       return 1;
13408     }
13409   }
13410   return 0;
13411 }
13412
13413
13414 /*
13415 ** The following routines implement the various date and time functions
13416 ** of SQLite.
13417 */
13418
13419 /*
13420 **    julianday( TIMESTRING, MOD, MOD, ...)
13421 **
13422 ** Return the julian day number of the date specified in the arguments
13423 */
13424 static void juliandayFunc(
13425   sqlite3_context *context,
13426   int argc,
13427   sqlite3_value **argv
13428 ){
13429   DateTime x;
13430   if( isDate(context, argc, argv, &x)==0 ){
13431     computeJD(&x);
13432     sqlite3_result_double(context, x.iJD/86400000.0);
13433   }
13434 }
13435
13436 /*
13437 **    datetime( TIMESTRING, MOD, MOD, ...)
13438 **
13439 ** Return YYYY-MM-DD HH:MM:SS
13440 */
13441 static void datetimeFunc(
13442   sqlite3_context *context,
13443   int argc,
13444   sqlite3_value **argv
13445 ){
13446   DateTime x;
13447   if( isDate(context, argc, argv, &x)==0 ){
13448     char zBuf[100];
13449     computeYMD_HMS(&x);
13450     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
13451                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
13452     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13453   }
13454 }
13455
13456 /*
13457 **    time( TIMESTRING, MOD, MOD, ...)
13458 **
13459 ** Return HH:MM:SS
13460 */
13461 static void timeFunc(
13462   sqlite3_context *context,
13463   int argc,
13464   sqlite3_value **argv
13465 ){
13466   DateTime x;
13467   if( isDate(context, argc, argv, &x)==0 ){
13468     char zBuf[100];
13469     computeHMS(&x);
13470     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
13471     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13472   }
13473 }
13474
13475 /*
13476 **    date( TIMESTRING, MOD, MOD, ...)
13477 **
13478 ** Return YYYY-MM-DD
13479 */
13480 static void dateFunc(
13481   sqlite3_context *context,
13482   int argc,
13483   sqlite3_value **argv
13484 ){
13485   DateTime x;
13486   if( isDate(context, argc, argv, &x)==0 ){
13487     char zBuf[100];
13488     computeYMD(&x);
13489     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
13490     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13491   }
13492 }
13493
13494 /*
13495 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
13496 **
13497 ** Return a string described by FORMAT.  Conversions as follows:
13498 **
13499 **   %d  day of month
13500 **   %f  ** fractional seconds  SS.SSS
13501 **   %H  hour 00-24
13502 **   %j  day of year 000-366
13503 **   %J  ** Julian day number
13504 **   %m  month 01-12
13505 **   %M  minute 00-59
13506 **   %s  seconds since 1970-01-01
13507 **   %S  seconds 00-59
13508 **   %w  day of week 0-6  sunday==0
13509 **   %W  week of year 00-53
13510 **   %Y  year 0000-9999
13511 **   %%  %
13512 */
13513 static void strftimeFunc(
13514   sqlite3_context *context,
13515   int argc,
13516   sqlite3_value **argv
13517 ){
13518   DateTime x;
13519   u64 n;
13520   size_t i,j;
13521   char *z;
13522   sqlite3 *db;
13523   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
13524   char zBuf[100];
13525   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
13526   db = sqlite3_context_db_handle(context);
13527   for(i=0, n=1; zFmt[i]; i++, n++){
13528     if( zFmt[i]=='%' ){
13529       switch( zFmt[i+1] ){
13530         case 'd':
13531         case 'H':
13532         case 'm':
13533         case 'M':
13534         case 'S':
13535         case 'W':
13536           n++;
13537           /* fall thru */
13538         case 'w':
13539         case '%':
13540           break;
13541         case 'f':
13542           n += 8;
13543           break;
13544         case 'j':
13545           n += 3;
13546           break;
13547         case 'Y':
13548           n += 8;
13549           break;
13550         case 's':
13551         case 'J':
13552           n += 50;
13553           break;
13554         default:
13555           return;  /* ERROR.  return a NULL */
13556       }
13557       i++;
13558     }
13559   }
13560   testcase( n==sizeof(zBuf)-1 );
13561   testcase( n==sizeof(zBuf) );
13562   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
13563   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
13564   if( n<sizeof(zBuf) ){
13565     z = zBuf;
13566   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
13567     sqlite3_result_error_toobig(context);
13568     return;
13569   }else{
13570     z = sqlite3DbMallocRaw(db, (int)n);
13571     if( z==0 ){
13572       sqlite3_result_error_nomem(context);
13573       return;
13574     }
13575   }
13576   computeJD(&x);
13577   computeYMD_HMS(&x);
13578   for(i=j=0; zFmt[i]; i++){
13579     if( zFmt[i]!='%' ){
13580       z[j++] = zFmt[i];
13581     }else{
13582       i++;
13583       switch( zFmt[i] ){
13584         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
13585         case 'f': {
13586           double s = x.s;
13587           if( s>59.999 ) s = 59.999;
13588           sqlite3_snprintf(7, &z[j],"%06.3f", s);
13589           j += sqlite3Strlen30(&z[j]);
13590           break;
13591         }
13592         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
13593         case 'W': /* Fall thru */
13594         case 'j': {
13595           int nDay;             /* Number of days since 1st day of year */
13596           DateTime y = x;
13597           y.validJD = 0;
13598           y.M = 1;
13599           y.D = 1;
13600           computeJD(&y);
13601           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
13602           if( zFmt[i]=='W' ){
13603             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
13604             wd = (int)(((x.iJD+43200000)/86400000)%7);
13605             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
13606             j += 2;
13607           }else{
13608             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
13609             j += 3;
13610           }
13611           break;
13612         }
13613         case 'J': {
13614           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
13615           j+=sqlite3Strlen30(&z[j]);
13616           break;
13617         }
13618         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
13619         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
13620         case 's': {
13621           sqlite3_snprintf(30,&z[j],"%lld",
13622                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
13623           j += sqlite3Strlen30(&z[j]);
13624           break;
13625         }
13626         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
13627         case 'w': {
13628           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
13629           break;
13630         }
13631         case 'Y': {
13632           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
13633           break;
13634         }
13635         default:   z[j++] = '%'; break;
13636       }
13637     }
13638   }
13639   z[j] = 0;
13640   sqlite3_result_text(context, z, -1,
13641                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
13642 }
13643
13644 /*
13645 ** current_time()
13646 **
13647 ** This function returns the same value as time('now').
13648 */
13649 static void ctimeFunc(
13650   sqlite3_context *context,
13651   int NotUsed,
13652   sqlite3_value **NotUsed2
13653 ){
13654   UNUSED_PARAMETER2(NotUsed, NotUsed2);
13655   timeFunc(context, 0, 0);
13656 }
13657
13658 /*
13659 ** current_date()
13660 **
13661 ** This function returns the same value as date('now').
13662 */
13663 static void cdateFunc(
13664   sqlite3_context *context,
13665   int NotUsed,
13666   sqlite3_value **NotUsed2
13667 ){
13668   UNUSED_PARAMETER2(NotUsed, NotUsed2);
13669   dateFunc(context, 0, 0);
13670 }
13671
13672 /*
13673 ** current_timestamp()
13674 **
13675 ** This function returns the same value as datetime('now').
13676 */
13677 static void ctimestampFunc(
13678   sqlite3_context *context,
13679   int NotUsed,
13680   sqlite3_value **NotUsed2
13681 ){
13682   UNUSED_PARAMETER2(NotUsed, NotUsed2);
13683   datetimeFunc(context, 0, 0);
13684 }
13685 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
13686
13687 #ifdef SQLITE_OMIT_DATETIME_FUNCS
13688 /*
13689 ** If the library is compiled to omit the full-scale date and time
13690 ** handling (to get a smaller binary), the following minimal version
13691 ** of the functions current_time(), current_date() and current_timestamp()
13692 ** are included instead. This is to support column declarations that
13693 ** include "DEFAULT CURRENT_TIME" etc.
13694 **
13695 ** This function uses the C-library functions time(), gmtime()
13696 ** and strftime(). The format string to pass to strftime() is supplied
13697 ** as the user-data for the function.
13698 */
13699 static void currentTimeFunc(
13700   sqlite3_context *context,
13701   int argc,
13702   sqlite3_value **argv
13703 ){
13704   time_t t;
13705   char *zFormat = (char *)sqlite3_user_data(context);
13706   sqlite3 *db;
13707   sqlite3_int64 iT;
13708   char zBuf[20];
13709
13710   UNUSED_PARAMETER(argc);
13711   UNUSED_PARAMETER(argv);
13712
13713   db = sqlite3_context_db_handle(context);
13714   sqlite3OsCurrentTimeInt64(db->pVfs, &iT);
13715   t = iT/1000 - 10000*(sqlite3_int64)21086676;
13716 #ifdef HAVE_GMTIME_R
13717   {
13718     struct tm sNow;
13719     gmtime_r(&t, &sNow);
13720     strftime(zBuf, 20, zFormat, &sNow);
13721   }
13722 #else
13723   {
13724     struct tm *pTm;
13725     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13726     pTm = gmtime(&t);
13727     strftime(zBuf, 20, zFormat, pTm);
13728     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13729   }
13730 #endif
13731
13732   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13733 }
13734 #endif
13735
13736 /*
13737 ** This function registered all of the above C functions as SQL
13738 ** functions.  This should be the only routine in this file with
13739 ** external linkage.
13740 */
13741 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
13742   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
13743 #ifndef SQLITE_OMIT_DATETIME_FUNCS
13744     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
13745     FUNCTION(date,             -1, 0, 0, dateFunc      ),
13746     FUNCTION(time,             -1, 0, 0, timeFunc      ),
13747     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
13748     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
13749     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
13750     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
13751     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
13752 #else
13753     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
13754     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
13755     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
13756 #endif
13757   };
13758   int i;
13759   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
13760   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
13761
13762   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
13763     sqlite3FuncDefInsert(pHash, &aFunc[i]);
13764   }
13765 }
13766
13767 /************** End of date.c ************************************************/
13768 /************** Begin file os.c **********************************************/
13769 /*
13770 ** 2005 November 29
13771 **
13772 ** The author disclaims copyright to this source code.  In place of
13773 ** a legal notice, here is a blessing:
13774 **
13775 **    May you do good and not evil.
13776 **    May you find forgiveness for yourself and forgive others.
13777 **    May you share freely, never taking more than you give.
13778 **
13779 ******************************************************************************
13780 **
13781 ** This file contains OS interface code that is common to all
13782 ** architectures.
13783 */
13784 #define _SQLITE_OS_C_ 1
13785 #undef _SQLITE_OS_C_
13786
13787 /*
13788 ** The default SQLite sqlite3_vfs implementations do not allocate
13789 ** memory (actually, os_unix.c allocates a small amount of memory
13790 ** from within OsOpen()), but some third-party implementations may.
13791 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
13792 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
13793 **
13794 ** The following functions are instrumented for malloc() failure 
13795 ** testing:
13796 **
13797 **     sqlite3OsOpen()
13798 **     sqlite3OsRead()
13799 **     sqlite3OsWrite()
13800 **     sqlite3OsSync()
13801 **     sqlite3OsLock()
13802 **
13803 */
13804 #if defined(SQLITE_TEST)
13805 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
13806   #define DO_OS_MALLOC_TEST(x)                                       \
13807   if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
13808     void *pTstAlloc = sqlite3Malloc(10);                             \
13809     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
13810     sqlite3_free(pTstAlloc);                                         \
13811   }
13812 #else
13813   #define DO_OS_MALLOC_TEST(x)
13814 #endif
13815
13816 /*
13817 ** The following routines are convenience wrappers around methods
13818 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
13819 ** of this would be completely automatic if SQLite were coded using
13820 ** C++ instead of plain old C.
13821 */
13822 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
13823   int rc = SQLITE_OK;
13824   if( pId->pMethods ){
13825     rc = pId->pMethods->xClose(pId);
13826     pId->pMethods = 0;
13827   }
13828   return rc;
13829 }
13830 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
13831   DO_OS_MALLOC_TEST(id);
13832   return id->pMethods->xRead(id, pBuf, amt, offset);
13833 }
13834 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
13835   DO_OS_MALLOC_TEST(id);
13836   return id->pMethods->xWrite(id, pBuf, amt, offset);
13837 }
13838 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
13839   return id->pMethods->xTruncate(id, size);
13840 }
13841 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
13842   DO_OS_MALLOC_TEST(id);
13843   return id->pMethods->xSync(id, flags);
13844 }
13845 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
13846   DO_OS_MALLOC_TEST(id);
13847   return id->pMethods->xFileSize(id, pSize);
13848 }
13849 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
13850   DO_OS_MALLOC_TEST(id);
13851   return id->pMethods->xLock(id, lockType);
13852 }
13853 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
13854   return id->pMethods->xUnlock(id, lockType);
13855 }
13856 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
13857   DO_OS_MALLOC_TEST(id);
13858   return id->pMethods->xCheckReservedLock(id, pResOut);
13859 }
13860 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
13861   return id->pMethods->xFileControl(id, op, pArg);
13862 }
13863 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
13864   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
13865   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
13866 }
13867 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
13868   return id->pMethods->xDeviceCharacteristics(id);
13869 }
13870 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
13871   return id->pMethods->xShmLock(id, offset, n, flags);
13872 }
13873 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
13874   id->pMethods->xShmBarrier(id);
13875 }
13876 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
13877   return id->pMethods->xShmUnmap(id, deleteFlag);
13878 }
13879 SQLITE_PRIVATE int sqlite3OsShmMap(
13880   sqlite3_file *id,               /* Database file handle */
13881   int iPage,
13882   int pgsz,
13883   int bExtend,                    /* True to extend file if necessary */
13884   void volatile **pp              /* OUT: Pointer to mapping */
13885 ){
13886   return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
13887 }
13888
13889 /*
13890 ** The next group of routines are convenience wrappers around the
13891 ** VFS methods.
13892 */
13893 SQLITE_PRIVATE int sqlite3OsOpen(
13894   sqlite3_vfs *pVfs, 
13895   const char *zPath, 
13896   sqlite3_file *pFile, 
13897   int flags, 
13898   int *pFlagsOut
13899 ){
13900   int rc;
13901   DO_OS_MALLOC_TEST(0);
13902   /* 0x87f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed
13903   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
13904   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
13905   ** reaching the VFS. */
13906   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f3f, pFlagsOut);
13907   assert( rc==SQLITE_OK || pFile->pMethods==0 );
13908   return rc;
13909 }
13910 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
13911   return pVfs->xDelete(pVfs, zPath, dirSync);
13912 }
13913 SQLITE_PRIVATE int sqlite3OsAccess(
13914   sqlite3_vfs *pVfs, 
13915   const char *zPath, 
13916   int flags, 
13917   int *pResOut
13918 ){
13919   DO_OS_MALLOC_TEST(0);
13920   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
13921 }
13922 SQLITE_PRIVATE int sqlite3OsFullPathname(
13923   sqlite3_vfs *pVfs, 
13924   const char *zPath, 
13925   int nPathOut, 
13926   char *zPathOut
13927 ){
13928   zPathOut[0] = 0;
13929   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
13930 }
13931 #ifndef SQLITE_OMIT_LOAD_EXTENSION
13932 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
13933   return pVfs->xDlOpen(pVfs, zPath);
13934 }
13935 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
13936   pVfs->xDlError(pVfs, nByte, zBufOut);
13937 }
13938 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
13939   return pVfs->xDlSym(pVfs, pHdle, zSym);
13940 }
13941 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
13942   pVfs->xDlClose(pVfs, pHandle);
13943 }
13944 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
13945 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
13946   return pVfs->xRandomness(pVfs, nByte, zBufOut);
13947 }
13948 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
13949   return pVfs->xSleep(pVfs, nMicro);
13950 }
13951 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
13952   int rc;
13953   /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
13954   ** method to get the current date and time if that method is available
13955   ** (if iVersion is 2 or greater and the function pointer is not NULL) and
13956   ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
13957   ** unavailable.
13958   */
13959   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
13960     rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
13961   }else{
13962     double r;
13963     rc = pVfs->xCurrentTime(pVfs, &r);
13964     *pTimeOut = (sqlite3_int64)(r*86400000.0);
13965   }
13966   return rc;
13967 }
13968
13969 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
13970   sqlite3_vfs *pVfs, 
13971   const char *zFile, 
13972   sqlite3_file **ppFile, 
13973   int flags,
13974   int *pOutFlags
13975 ){
13976   int rc = SQLITE_NOMEM;
13977   sqlite3_file *pFile;
13978   pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
13979   if( pFile ){
13980     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
13981     if( rc!=SQLITE_OK ){
13982       sqlite3_free(pFile);
13983     }else{
13984       *ppFile = pFile;
13985     }
13986   }
13987   return rc;
13988 }
13989 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
13990   int rc = SQLITE_OK;
13991   assert( pFile );
13992   rc = sqlite3OsClose(pFile);
13993   sqlite3_free(pFile);
13994   return rc;
13995 }
13996
13997 /*
13998 ** This function is a wrapper around the OS specific implementation of
13999 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
14000 ** ability to simulate a malloc failure, so that the handling of an
14001 ** error in sqlite3_os_init() by the upper layers can be tested.
14002 */
14003 SQLITE_PRIVATE int sqlite3OsInit(void){
14004   void *p = sqlite3_malloc(10);
14005   if( p==0 ) return SQLITE_NOMEM;
14006   sqlite3_free(p);
14007   return sqlite3_os_init();
14008 }
14009
14010 /*
14011 ** The list of all registered VFS implementations.
14012 */
14013 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
14014 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
14015
14016 /*
14017 ** Locate a VFS by name.  If no name is given, simply return the
14018 ** first VFS on the list.
14019 */
14020 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
14021   sqlite3_vfs *pVfs = 0;
14022 #if SQLITE_THREADSAFE
14023   sqlite3_mutex *mutex;
14024 #endif
14025 #ifndef SQLITE_OMIT_AUTOINIT
14026   int rc = sqlite3_initialize();
14027   if( rc ) return 0;
14028 #endif
14029 #if SQLITE_THREADSAFE
14030   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14031 #endif
14032   sqlite3_mutex_enter(mutex);
14033   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
14034     if( zVfs==0 ) break;
14035     if( strcmp(zVfs, pVfs->zName)==0 ) break;
14036   }
14037   sqlite3_mutex_leave(mutex);
14038   return pVfs;
14039 }
14040
14041 /*
14042 ** Unlink a VFS from the linked list
14043 */
14044 static void vfsUnlink(sqlite3_vfs *pVfs){
14045   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
14046   if( pVfs==0 ){
14047     /* No-op */
14048   }else if( vfsList==pVfs ){
14049     vfsList = pVfs->pNext;
14050   }else if( vfsList ){
14051     sqlite3_vfs *p = vfsList;
14052     while( p->pNext && p->pNext!=pVfs ){
14053       p = p->pNext;
14054     }
14055     if( p->pNext==pVfs ){
14056       p->pNext = pVfs->pNext;
14057     }
14058   }
14059 }
14060
14061 /*
14062 ** Register a VFS with the system.  It is harmless to register the same
14063 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
14064 ** true.
14065 */
14066 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
14067   sqlite3_mutex *mutex = 0;
14068 #ifndef SQLITE_OMIT_AUTOINIT
14069   int rc = sqlite3_initialize();
14070   if( rc ) return rc;
14071 #endif
14072   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14073   sqlite3_mutex_enter(mutex);
14074   vfsUnlink(pVfs);
14075   if( makeDflt || vfsList==0 ){
14076     pVfs->pNext = vfsList;
14077     vfsList = pVfs;
14078   }else{
14079     pVfs->pNext = vfsList->pNext;
14080     vfsList->pNext = pVfs;
14081   }
14082   assert(vfsList);
14083   sqlite3_mutex_leave(mutex);
14084   return SQLITE_OK;
14085 }
14086
14087 /*
14088 ** Unregister a VFS so that it is no longer accessible.
14089 */
14090 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
14091 #if SQLITE_THREADSAFE
14092   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14093 #endif
14094   sqlite3_mutex_enter(mutex);
14095   vfsUnlink(pVfs);
14096   sqlite3_mutex_leave(mutex);
14097   return SQLITE_OK;
14098 }
14099
14100 /************** End of os.c **************************************************/
14101 /************** Begin file fault.c *******************************************/
14102 /*
14103 ** 2008 Jan 22
14104 **
14105 ** The author disclaims copyright to this source code.  In place of
14106 ** a legal notice, here is a blessing:
14107 **
14108 **    May you do good and not evil.
14109 **    May you find forgiveness for yourself and forgive others.
14110 **    May you share freely, never taking more than you give.
14111 **
14112 *************************************************************************
14113 **
14114 ** This file contains code to support the concept of "benign" 
14115 ** malloc failures (when the xMalloc() or xRealloc() method of the
14116 ** sqlite3_mem_methods structure fails to allocate a block of memory
14117 ** and returns 0). 
14118 **
14119 ** Most malloc failures are non-benign. After they occur, SQLite
14120 ** abandons the current operation and returns an error code (usually
14121 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
14122 ** fatal. For example, if a malloc fails while resizing a hash table, this 
14123 ** is completely recoverable simply by not carrying out the resize. The 
14124 ** hash table will continue to function normally.  So a malloc failure 
14125 ** during a hash table resize is a benign fault.
14126 */
14127
14128
14129 #ifndef SQLITE_OMIT_BUILTIN_TEST
14130
14131 /*
14132 ** Global variables.
14133 */
14134 typedef struct BenignMallocHooks BenignMallocHooks;
14135 static SQLITE_WSD struct BenignMallocHooks {
14136   void (*xBenignBegin)(void);
14137   void (*xBenignEnd)(void);
14138 } sqlite3Hooks = { 0, 0 };
14139
14140 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
14141 ** structure.  If writable static data is unsupported on the target,
14142 ** we have to locate the state vector at run-time.  In the more common
14143 ** case where writable static data is supported, wsdHooks can refer directly
14144 ** to the "sqlite3Hooks" state vector declared above.
14145 */
14146 #ifdef SQLITE_OMIT_WSD
14147 # define wsdHooksInit \
14148   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
14149 # define wsdHooks x[0]
14150 #else
14151 # define wsdHooksInit
14152 # define wsdHooks sqlite3Hooks
14153 #endif
14154
14155
14156 /*
14157 ** Register hooks to call when sqlite3BeginBenignMalloc() and
14158 ** sqlite3EndBenignMalloc() are called, respectively.
14159 */
14160 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
14161   void (*xBenignBegin)(void),
14162   void (*xBenignEnd)(void)
14163 ){
14164   wsdHooksInit;
14165   wsdHooks.xBenignBegin = xBenignBegin;
14166   wsdHooks.xBenignEnd = xBenignEnd;
14167 }
14168
14169 /*
14170 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
14171 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
14172 ** indicates that subsequent malloc failures are non-benign.
14173 */
14174 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
14175   wsdHooksInit;
14176   if( wsdHooks.xBenignBegin ){
14177     wsdHooks.xBenignBegin();
14178   }
14179 }
14180 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
14181   wsdHooksInit;
14182   if( wsdHooks.xBenignEnd ){
14183     wsdHooks.xBenignEnd();
14184   }
14185 }
14186
14187 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
14188
14189 /************** End of fault.c ***********************************************/
14190 /************** Begin file mem0.c ********************************************/
14191 /*
14192 ** 2008 October 28
14193 **
14194 ** The author disclaims copyright to this source code.  In place of
14195 ** a legal notice, here is a blessing:
14196 **
14197 **    May you do good and not evil.
14198 **    May you find forgiveness for yourself and forgive others.
14199 **    May you share freely, never taking more than you give.
14200 **
14201 *************************************************************************
14202 **
14203 ** This file contains a no-op memory allocation drivers for use when
14204 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
14205 ** here always fail.  SQLite will not operate with these drivers.  These
14206 ** are merely placeholders.  Real drivers must be substituted using
14207 ** sqlite3_config() before SQLite will operate.
14208 */
14209
14210 /*
14211 ** This version of the memory allocator is the default.  It is
14212 ** used when no other memory allocator is specified using compile-time
14213 ** macros.
14214 */
14215 #ifdef SQLITE_ZERO_MALLOC
14216
14217 /*
14218 ** No-op versions of all memory allocation routines
14219 */
14220 static void *sqlite3MemMalloc(int nByte){ return 0; }
14221 static void sqlite3MemFree(void *pPrior){ return; }
14222 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
14223 static int sqlite3MemSize(void *pPrior){ return 0; }
14224 static int sqlite3MemRoundup(int n){ return n; }
14225 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
14226 static void sqlite3MemShutdown(void *NotUsed){ return; }
14227
14228 /*
14229 ** This routine is the only routine in this file with external linkage.
14230 **
14231 ** Populate the low-level memory allocation function pointers in
14232 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
14233 */
14234 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14235   static const sqlite3_mem_methods defaultMethods = {
14236      sqlite3MemMalloc,
14237      sqlite3MemFree,
14238      sqlite3MemRealloc,
14239      sqlite3MemSize,
14240      sqlite3MemRoundup,
14241      sqlite3MemInit,
14242      sqlite3MemShutdown,
14243      0
14244   };
14245   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14246 }
14247
14248 #endif /* SQLITE_ZERO_MALLOC */
14249
14250 /************** End of mem0.c ************************************************/
14251 /************** Begin file mem1.c ********************************************/
14252 /*
14253 ** 2007 August 14
14254 **
14255 ** The author disclaims copyright to this source code.  In place of
14256 ** a legal notice, here is a blessing:
14257 **
14258 **    May you do good and not evil.
14259 **    May you find forgiveness for yourself and forgive others.
14260 **    May you share freely, never taking more than you give.
14261 **
14262 *************************************************************************
14263 **
14264 ** This file contains low-level memory allocation drivers for when
14265 ** SQLite will use the standard C-library malloc/realloc/free interface
14266 ** to obtain the memory it needs.
14267 **
14268 ** This file contains implementations of the low-level memory allocation
14269 ** routines specified in the sqlite3_mem_methods object.
14270 */
14271
14272 /*
14273 ** This version of the memory allocator is the default.  It is
14274 ** used when no other memory allocator is specified using compile-time
14275 ** macros.
14276 */
14277 #ifdef SQLITE_SYSTEM_MALLOC
14278
14279 /*
14280 ** Like malloc(), but remember the size of the allocation
14281 ** so that we can find it later using sqlite3MemSize().
14282 **
14283 ** For this low-level routine, we are guaranteed that nByte>0 because
14284 ** cases of nByte<=0 will be intercepted and dealt with by higher level
14285 ** routines.
14286 */
14287 static void *sqlite3MemMalloc(int nByte){
14288   sqlite3_int64 *p;
14289   assert( nByte>0 );
14290   nByte = ROUND8(nByte);
14291   p = malloc( nByte+8 );
14292   if( p ){
14293     p[0] = nByte;
14294     p++;
14295   }else{
14296     testcase( sqlite3GlobalConfig.xLog!=0 );
14297     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
14298   }
14299   return (void *)p;
14300 }
14301
14302 /*
14303 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
14304 ** or sqlite3MemRealloc().
14305 **
14306 ** For this low-level routine, we already know that pPrior!=0 since
14307 ** cases where pPrior==0 will have been intecepted and dealt with
14308 ** by higher-level routines.
14309 */
14310 static void sqlite3MemFree(void *pPrior){
14311   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
14312   assert( pPrior!=0 );
14313   p--;
14314   free(p);
14315 }
14316
14317 /*
14318 ** Report the allocated size of a prior return from xMalloc()
14319 ** or xRealloc().
14320 */
14321 static int sqlite3MemSize(void *pPrior){
14322   sqlite3_int64 *p;
14323   if( pPrior==0 ) return 0;
14324   p = (sqlite3_int64*)pPrior;
14325   p--;
14326   return (int)p[0];
14327 }
14328
14329 /*
14330 ** Like realloc().  Resize an allocation previously obtained from
14331 ** sqlite3MemMalloc().
14332 **
14333 ** For this low-level interface, we know that pPrior!=0.  Cases where
14334 ** pPrior==0 while have been intercepted by higher-level routine and
14335 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
14336 ** cases where nByte<=0 will have been intercepted by higher-level
14337 ** routines and redirected to xFree.
14338 */
14339 static void *sqlite3MemRealloc(void *pPrior, int nByte){
14340   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
14341   assert( pPrior!=0 && nByte>0 );
14342   assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
14343   p--;
14344   p = realloc(p, nByte+8 );
14345   if( p ){
14346     p[0] = nByte;
14347     p++;
14348   }else{
14349     testcase( sqlite3GlobalConfig.xLog!=0 );
14350     sqlite3_log(SQLITE_NOMEM,
14351       "failed memory resize %u to %u bytes",
14352       sqlite3MemSize(pPrior), nByte);
14353   }
14354   return (void*)p;
14355 }
14356
14357 /*
14358 ** Round up a request size to the next valid allocation size.
14359 */
14360 static int sqlite3MemRoundup(int n){
14361   return ROUND8(n);
14362 }
14363
14364 /*
14365 ** Initialize this module.
14366 */
14367 static int sqlite3MemInit(void *NotUsed){
14368   UNUSED_PARAMETER(NotUsed);
14369   return SQLITE_OK;
14370 }
14371
14372 /*
14373 ** Deinitialize this module.
14374 */
14375 static void sqlite3MemShutdown(void *NotUsed){
14376   UNUSED_PARAMETER(NotUsed);
14377   return;
14378 }
14379
14380 /*
14381 ** This routine is the only routine in this file with external linkage.
14382 **
14383 ** Populate the low-level memory allocation function pointers in
14384 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
14385 */
14386 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14387   static const sqlite3_mem_methods defaultMethods = {
14388      sqlite3MemMalloc,
14389      sqlite3MemFree,
14390      sqlite3MemRealloc,
14391      sqlite3MemSize,
14392      sqlite3MemRoundup,
14393      sqlite3MemInit,
14394      sqlite3MemShutdown,
14395      0
14396   };
14397   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14398 }
14399
14400 #endif /* SQLITE_SYSTEM_MALLOC */
14401
14402 /************** End of mem1.c ************************************************/
14403 /************** Begin file mem2.c ********************************************/
14404 /*
14405 ** 2007 August 15
14406 **
14407 ** The author disclaims copyright to this source code.  In place of
14408 ** a legal notice, here is a blessing:
14409 **
14410 **    May you do good and not evil.
14411 **    May you find forgiveness for yourself and forgive others.
14412 **    May you share freely, never taking more than you give.
14413 **
14414 *************************************************************************
14415 **
14416 ** This file contains low-level memory allocation drivers for when
14417 ** SQLite will use the standard C-library malloc/realloc/free interface
14418 ** to obtain the memory it needs while adding lots of additional debugging
14419 ** information to each allocation in order to help detect and fix memory
14420 ** leaks and memory usage errors.
14421 **
14422 ** This file contains implementations of the low-level memory allocation
14423 ** routines specified in the sqlite3_mem_methods object.
14424 */
14425
14426 /*
14427 ** This version of the memory allocator is used only if the
14428 ** SQLITE_MEMDEBUG macro is defined
14429 */
14430 #ifdef SQLITE_MEMDEBUG
14431
14432 /*
14433 ** The backtrace functionality is only available with GLIBC
14434 */
14435 #ifdef __GLIBC__
14436   extern int backtrace(void**,int);
14437   extern void backtrace_symbols_fd(void*const*,int,int);
14438 #else
14439 # define backtrace(A,B) 1
14440 # define backtrace_symbols_fd(A,B,C)
14441 #endif
14442
14443 /*
14444 ** Each memory allocation looks like this:
14445 **
14446 **  ------------------------------------------------------------------------
14447 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
14448 **  ------------------------------------------------------------------------
14449 **
14450 ** The application code sees only a pointer to the allocation.  We have
14451 ** to back up from the allocation pointer to find the MemBlockHdr.  The
14452 ** MemBlockHdr tells us the size of the allocation and the number of
14453 ** backtrace pointers.  There is also a guard word at the end of the
14454 ** MemBlockHdr.
14455 */
14456 struct MemBlockHdr {
14457   i64 iSize;                          /* Size of this allocation */
14458   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
14459   char nBacktrace;                    /* Number of backtraces on this alloc */
14460   char nBacktraceSlots;               /* Available backtrace slots */
14461   u8 nTitle;                          /* Bytes of title; includes '\0' */
14462   u8 eType;                           /* Allocation type code */
14463   int iForeGuard;                     /* Guard word for sanity */
14464 };
14465
14466 /*
14467 ** Guard words
14468 */
14469 #define FOREGUARD 0x80F5E153
14470 #define REARGUARD 0xE4676B53
14471
14472 /*
14473 ** Number of malloc size increments to track.
14474 */
14475 #define NCSIZE  1000
14476
14477 /*
14478 ** All of the static variables used by this module are collected
14479 ** into a single structure named "mem".  This is to keep the
14480 ** static variables organized and to reduce namespace pollution
14481 ** when this module is combined with other in the amalgamation.
14482 */
14483 static struct {
14484   
14485   /*
14486   ** Mutex to control access to the memory allocation subsystem.
14487   */
14488   sqlite3_mutex *mutex;
14489
14490   /*
14491   ** Head and tail of a linked list of all outstanding allocations
14492   */
14493   struct MemBlockHdr *pFirst;
14494   struct MemBlockHdr *pLast;
14495   
14496   /*
14497   ** The number of levels of backtrace to save in new allocations.
14498   */
14499   int nBacktrace;
14500   void (*xBacktrace)(int, int, void **);
14501
14502   /*
14503   ** Title text to insert in front of each block
14504   */
14505   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
14506   char zTitle[100];  /* The title text */
14507
14508   /* 
14509   ** sqlite3MallocDisallow() increments the following counter.
14510   ** sqlite3MallocAllow() decrements it.
14511   */
14512   int disallow; /* Do not allow memory allocation */
14513
14514   /*
14515   ** Gather statistics on the sizes of memory allocations.
14516   ** nAlloc[i] is the number of allocation attempts of i*8
14517   ** bytes.  i==NCSIZE is the number of allocation attempts for
14518   ** sizes more than NCSIZE*8 bytes.
14519   */
14520   int nAlloc[NCSIZE];      /* Total number of allocations */
14521   int nCurrent[NCSIZE];    /* Current number of allocations */
14522   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
14523
14524 } mem;
14525
14526
14527 /*
14528 ** Adjust memory usage statistics
14529 */
14530 static void adjustStats(int iSize, int increment){
14531   int i = ROUND8(iSize)/8;
14532   if( i>NCSIZE-1 ){
14533     i = NCSIZE - 1;
14534   }
14535   if( increment>0 ){
14536     mem.nAlloc[i]++;
14537     mem.nCurrent[i]++;
14538     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
14539       mem.mxCurrent[i] = mem.nCurrent[i];
14540     }
14541   }else{
14542     mem.nCurrent[i]--;
14543     assert( mem.nCurrent[i]>=0 );
14544   }
14545 }
14546
14547 /*
14548 ** Given an allocation, find the MemBlockHdr for that allocation.
14549 **
14550 ** This routine checks the guards at either end of the allocation and
14551 ** if they are incorrect it asserts.
14552 */
14553 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
14554   struct MemBlockHdr *p;
14555   int *pInt;
14556   u8 *pU8;
14557   int nReserve;
14558
14559   p = (struct MemBlockHdr*)pAllocation;
14560   p--;
14561   assert( p->iForeGuard==(int)FOREGUARD );
14562   nReserve = ROUND8(p->iSize);
14563   pInt = (int*)pAllocation;
14564   pU8 = (u8*)pAllocation;
14565   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
14566   /* This checks any of the "extra" bytes allocated due
14567   ** to rounding up to an 8 byte boundary to ensure 
14568   ** they haven't been overwritten.
14569   */
14570   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
14571   return p;
14572 }
14573
14574 /*
14575 ** Return the number of bytes currently allocated at address p.
14576 */
14577 static int sqlite3MemSize(void *p){
14578   struct MemBlockHdr *pHdr;
14579   if( !p ){
14580     return 0;
14581   }
14582   pHdr = sqlite3MemsysGetHeader(p);
14583   return pHdr->iSize;
14584 }
14585
14586 /*
14587 ** Initialize the memory allocation subsystem.
14588 */
14589 static int sqlite3MemInit(void *NotUsed){
14590   UNUSED_PARAMETER(NotUsed);
14591   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
14592   if( !sqlite3GlobalConfig.bMemstat ){
14593     /* If memory status is enabled, then the malloc.c wrapper will already
14594     ** hold the STATIC_MEM mutex when the routines here are invoked. */
14595     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14596   }
14597   return SQLITE_OK;
14598 }
14599
14600 /*
14601 ** Deinitialize the memory allocation subsystem.
14602 */
14603 static void sqlite3MemShutdown(void *NotUsed){
14604   UNUSED_PARAMETER(NotUsed);
14605   mem.mutex = 0;
14606 }
14607
14608 /*
14609 ** Round up a request size to the next valid allocation size.
14610 */
14611 static int sqlite3MemRoundup(int n){
14612   return ROUND8(n);
14613 }
14614
14615 /*
14616 ** Fill a buffer with pseudo-random bytes.  This is used to preset
14617 ** the content of a new memory allocation to unpredictable values and
14618 ** to clear the content of a freed allocation to unpredictable values.
14619 */
14620 static void randomFill(char *pBuf, int nByte){
14621   unsigned int x, y, r;
14622   x = SQLITE_PTR_TO_INT(pBuf);
14623   y = nByte | 1;
14624   while( nByte >= 4 ){
14625     x = (x>>1) ^ (-(x&1) & 0xd0000001);
14626     y = y*1103515245 + 12345;
14627     r = x ^ y;
14628     *(int*)pBuf = r;
14629     pBuf += 4;
14630     nByte -= 4;
14631   }
14632   while( nByte-- > 0 ){
14633     x = (x>>1) ^ (-(x&1) & 0xd0000001);
14634     y = y*1103515245 + 12345;
14635     r = x ^ y;
14636     *(pBuf++) = r & 0xff;
14637   }
14638 }
14639
14640 /*
14641 ** Allocate nByte bytes of memory.
14642 */
14643 static void *sqlite3MemMalloc(int nByte){
14644   struct MemBlockHdr *pHdr;
14645   void **pBt;
14646   char *z;
14647   int *pInt;
14648   void *p = 0;
14649   int totalSize;
14650   int nReserve;
14651   sqlite3_mutex_enter(mem.mutex);
14652   assert( mem.disallow==0 );
14653   nReserve = ROUND8(nByte);
14654   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
14655                mem.nBacktrace*sizeof(void*) + mem.nTitle;
14656   p = malloc(totalSize);
14657   if( p ){
14658     z = p;
14659     pBt = (void**)&z[mem.nTitle];
14660     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
14661     pHdr->pNext = 0;
14662     pHdr->pPrev = mem.pLast;
14663     if( mem.pLast ){
14664       mem.pLast->pNext = pHdr;
14665     }else{
14666       mem.pFirst = pHdr;
14667     }
14668     mem.pLast = pHdr;
14669     pHdr->iForeGuard = FOREGUARD;
14670     pHdr->eType = MEMTYPE_HEAP;
14671     pHdr->nBacktraceSlots = mem.nBacktrace;
14672     pHdr->nTitle = mem.nTitle;
14673     if( mem.nBacktrace ){
14674       void *aAddr[40];
14675       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
14676       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
14677       assert(pBt[0]);
14678       if( mem.xBacktrace ){
14679         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
14680       }
14681     }else{
14682       pHdr->nBacktrace = 0;
14683     }
14684     if( mem.nTitle ){
14685       memcpy(z, mem.zTitle, mem.nTitle);
14686     }
14687     pHdr->iSize = nByte;
14688     adjustStats(nByte, +1);
14689     pInt = (int*)&pHdr[1];
14690     pInt[nReserve/sizeof(int)] = REARGUARD;
14691     randomFill((char*)pInt, nByte);
14692     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
14693     p = (void*)pInt;
14694   }
14695   sqlite3_mutex_leave(mem.mutex);
14696   return p; 
14697 }
14698
14699 /*
14700 ** Free memory.
14701 */
14702 static void sqlite3MemFree(void *pPrior){
14703   struct MemBlockHdr *pHdr;
14704   void **pBt;
14705   char *z;
14706   assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 
14707        || mem.mutex!=0 );
14708   pHdr = sqlite3MemsysGetHeader(pPrior);
14709   pBt = (void**)pHdr;
14710   pBt -= pHdr->nBacktraceSlots;
14711   sqlite3_mutex_enter(mem.mutex);
14712   if( pHdr->pPrev ){
14713     assert( pHdr->pPrev->pNext==pHdr );
14714     pHdr->pPrev->pNext = pHdr->pNext;
14715   }else{
14716     assert( mem.pFirst==pHdr );
14717     mem.pFirst = pHdr->pNext;
14718   }
14719   if( pHdr->pNext ){
14720     assert( pHdr->pNext->pPrev==pHdr );
14721     pHdr->pNext->pPrev = pHdr->pPrev;
14722   }else{
14723     assert( mem.pLast==pHdr );
14724     mem.pLast = pHdr->pPrev;
14725   }
14726   z = (char*)pBt;
14727   z -= pHdr->nTitle;
14728   adjustStats(pHdr->iSize, -1);
14729   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
14730                 pHdr->iSize + sizeof(int) + pHdr->nTitle);
14731   free(z);
14732   sqlite3_mutex_leave(mem.mutex);  
14733 }
14734
14735 /*
14736 ** Change the size of an existing memory allocation.
14737 **
14738 ** For this debugging implementation, we *always* make a copy of the
14739 ** allocation into a new place in memory.  In this way, if the 
14740 ** higher level code is using pointer to the old allocation, it is 
14741 ** much more likely to break and we are much more liking to find
14742 ** the error.
14743 */
14744 static void *sqlite3MemRealloc(void *pPrior, int nByte){
14745   struct MemBlockHdr *pOldHdr;
14746   void *pNew;
14747   assert( mem.disallow==0 );
14748   assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
14749   pOldHdr = sqlite3MemsysGetHeader(pPrior);
14750   pNew = sqlite3MemMalloc(nByte);
14751   if( pNew ){
14752     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
14753     if( nByte>pOldHdr->iSize ){
14754       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
14755     }
14756     sqlite3MemFree(pPrior);
14757   }
14758   return pNew;
14759 }
14760
14761 /*
14762 ** Populate the low-level memory allocation function pointers in
14763 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
14764 */
14765 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14766   static const sqlite3_mem_methods defaultMethods = {
14767      sqlite3MemMalloc,
14768      sqlite3MemFree,
14769      sqlite3MemRealloc,
14770      sqlite3MemSize,
14771      sqlite3MemRoundup,
14772      sqlite3MemInit,
14773      sqlite3MemShutdown,
14774      0
14775   };
14776   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14777 }
14778
14779 /*
14780 ** Set the "type" of an allocation.
14781 */
14782 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
14783   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
14784     struct MemBlockHdr *pHdr;
14785     pHdr = sqlite3MemsysGetHeader(p);
14786     assert( pHdr->iForeGuard==FOREGUARD );
14787     pHdr->eType = eType;
14788   }
14789 }
14790
14791 /*
14792 ** Return TRUE if the mask of type in eType matches the type of the
14793 ** allocation p.  Also return true if p==NULL.
14794 **
14795 ** This routine is designed for use within an assert() statement, to
14796 ** verify the type of an allocation.  For example:
14797 **
14798 **     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
14799 */
14800 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
14801   int rc = 1;
14802   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
14803     struct MemBlockHdr *pHdr;
14804     pHdr = sqlite3MemsysGetHeader(p);
14805     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
14806     if( (pHdr->eType&eType)==0 ){
14807       rc = 0;
14808     }
14809   }
14810   return rc;
14811 }
14812
14813 /*
14814 ** Return TRUE if the mask of type in eType matches no bits of the type of the
14815 ** allocation p.  Also return true if p==NULL.
14816 **
14817 ** This routine is designed for use within an assert() statement, to
14818 ** verify the type of an allocation.  For example:
14819 **
14820 **     assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
14821 */
14822 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
14823   int rc = 1;
14824   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
14825     struct MemBlockHdr *pHdr;
14826     pHdr = sqlite3MemsysGetHeader(p);
14827     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
14828     if( (pHdr->eType&eType)!=0 ){
14829       rc = 0;
14830     }
14831   }
14832   return rc;
14833 }
14834
14835 /*
14836 ** Set the number of backtrace levels kept for each allocation.
14837 ** A value of zero turns off backtracing.  The number is always rounded
14838 ** up to a multiple of 2.
14839 */
14840 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
14841   if( depth<0 ){ depth = 0; }
14842   if( depth>20 ){ depth = 20; }
14843   depth = (depth+1)&0xfe;
14844   mem.nBacktrace = depth;
14845 }
14846
14847 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
14848   mem.xBacktrace = xBacktrace;
14849 }
14850
14851 /*
14852 ** Set the title string for subsequent allocations.
14853 */
14854 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
14855   unsigned int n = sqlite3Strlen30(zTitle) + 1;
14856   sqlite3_mutex_enter(mem.mutex);
14857   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
14858   memcpy(mem.zTitle, zTitle, n);
14859   mem.zTitle[n] = 0;
14860   mem.nTitle = ROUND8(n);
14861   sqlite3_mutex_leave(mem.mutex);
14862 }
14863
14864 SQLITE_PRIVATE void sqlite3MemdebugSync(){
14865   struct MemBlockHdr *pHdr;
14866   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
14867     void **pBt = (void**)pHdr;
14868     pBt -= pHdr->nBacktraceSlots;
14869     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
14870   }
14871 }
14872
14873 /*
14874 ** Open the file indicated and write a log of all unfreed memory 
14875 ** allocations into that log.
14876 */
14877 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
14878   FILE *out;
14879   struct MemBlockHdr *pHdr;
14880   void **pBt;
14881   int i;
14882   out = fopen(zFilename, "w");
14883   if( out==0 ){
14884     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
14885                     zFilename);
14886     return;
14887   }
14888   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
14889     char *z = (char*)pHdr;
14890     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
14891     fprintf(out, "**** %lld bytes at %p from %s ****\n", 
14892             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
14893     if( pHdr->nBacktrace ){
14894       fflush(out);
14895       pBt = (void**)pHdr;
14896       pBt -= pHdr->nBacktraceSlots;
14897       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
14898       fprintf(out, "\n");
14899     }
14900   }
14901   fprintf(out, "COUNTS:\n");
14902   for(i=0; i<NCSIZE-1; i++){
14903     if( mem.nAlloc[i] ){
14904       fprintf(out, "   %5d: %10d %10d %10d\n", 
14905             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
14906     }
14907   }
14908   if( mem.nAlloc[NCSIZE-1] ){
14909     fprintf(out, "   %5d: %10d %10d %10d\n",
14910              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
14911              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
14912   }
14913   fclose(out);
14914 }
14915
14916 /*
14917 ** Return the number of times sqlite3MemMalloc() has been called.
14918 */
14919 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
14920   int i;
14921   int nTotal = 0;
14922   for(i=0; i<NCSIZE; i++){
14923     nTotal += mem.nAlloc[i];
14924   }
14925   return nTotal;
14926 }
14927
14928
14929 #endif /* SQLITE_MEMDEBUG */
14930
14931 /************** End of mem2.c ************************************************/
14932 /************** Begin file mem3.c ********************************************/
14933 /*
14934 ** 2007 October 14
14935 **
14936 ** The author disclaims copyright to this source code.  In place of
14937 ** a legal notice, here is a blessing:
14938 **
14939 **    May you do good and not evil.
14940 **    May you find forgiveness for yourself and forgive others.
14941 **    May you share freely, never taking more than you give.
14942 **
14943 *************************************************************************
14944 ** This file contains the C functions that implement a memory
14945 ** allocation subsystem for use by SQLite. 
14946 **
14947 ** This version of the memory allocation subsystem omits all
14948 ** use of malloc(). The SQLite user supplies a block of memory
14949 ** before calling sqlite3_initialize() from which allocations
14950 ** are made and returned by the xMalloc() and xRealloc() 
14951 ** implementations. Once sqlite3_initialize() has been called,
14952 ** the amount of memory available to SQLite is fixed and cannot
14953 ** be changed.
14954 **
14955 ** This version of the memory allocation subsystem is included
14956 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
14957 */
14958
14959 /*
14960 ** This version of the memory allocator is only built into the library
14961 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
14962 ** mean that the library will use a memory-pool by default, just that
14963 ** it is available. The mempool allocator is activated by calling
14964 ** sqlite3_config().
14965 */
14966 #ifdef SQLITE_ENABLE_MEMSYS3
14967
14968 /*
14969 ** Maximum size (in Mem3Blocks) of a "small" chunk.
14970 */
14971 #define MX_SMALL 10
14972
14973
14974 /*
14975 ** Number of freelist hash slots
14976 */
14977 #define N_HASH  61
14978
14979 /*
14980 ** A memory allocation (also called a "chunk") consists of two or 
14981 ** more blocks where each block is 8 bytes.  The first 8 bytes are 
14982 ** a header that is not returned to the user.
14983 **
14984 ** A chunk is two or more blocks that is either checked out or
14985 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
14986 ** size of the allocation in blocks if the allocation is free.
14987 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
14988 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
14989 ** is true if the previous chunk is checked out and false if the
14990 ** previous chunk is free.  The u.hdr.prevSize field is the size of
14991 ** the previous chunk in blocks if the previous chunk is on the
14992 ** freelist. If the previous chunk is checked out, then
14993 ** u.hdr.prevSize can be part of the data for that chunk and should
14994 ** not be read or written.
14995 **
14996 ** We often identify a chunk by its index in mem3.aPool[].  When
14997 ** this is done, the chunk index refers to the second block of
14998 ** the chunk.  In this way, the first chunk has an index of 1.
14999 ** A chunk index of 0 means "no such chunk" and is the equivalent
15000 ** of a NULL pointer.
15001 **
15002 ** The second block of free chunks is of the form u.list.  The
15003 ** two fields form a double-linked list of chunks of related sizes.
15004 ** Pointers to the head of the list are stored in mem3.aiSmall[] 
15005 ** for smaller chunks and mem3.aiHash[] for larger chunks.
15006 **
15007 ** The second block of a chunk is user data if the chunk is checked 
15008 ** out.  If a chunk is checked out, the user data may extend into
15009 ** the u.hdr.prevSize value of the following chunk.
15010 */
15011 typedef struct Mem3Block Mem3Block;
15012 struct Mem3Block {
15013   union {
15014     struct {
15015       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
15016       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
15017     } hdr;
15018     struct {
15019       u32 next;       /* Index in mem3.aPool[] of next free chunk */
15020       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
15021     } list;
15022   } u;
15023 };
15024
15025 /*
15026 ** All of the static variables used by this module are collected
15027 ** into a single structure named "mem3".  This is to keep the
15028 ** static variables organized and to reduce namespace pollution
15029 ** when this module is combined with other in the amalgamation.
15030 */
15031 static SQLITE_WSD struct Mem3Global {
15032   /*
15033   ** Memory available for allocation. nPool is the size of the array
15034   ** (in Mem3Blocks) pointed to by aPool less 2.
15035   */
15036   u32 nPool;
15037   Mem3Block *aPool;
15038
15039   /*
15040   ** True if we are evaluating an out-of-memory callback.
15041   */
15042   int alarmBusy;
15043   
15044   /*
15045   ** Mutex to control access to the memory allocation subsystem.
15046   */
15047   sqlite3_mutex *mutex;
15048   
15049   /*
15050   ** The minimum amount of free space that we have seen.
15051   */
15052   u32 mnMaster;
15053
15054   /*
15055   ** iMaster is the index of the master chunk.  Most new allocations
15056   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
15057   ** of the current master.  iMaster is 0 if there is not master chunk.
15058   ** The master chunk is not in either the aiHash[] or aiSmall[].
15059   */
15060   u32 iMaster;
15061   u32 szMaster;
15062
15063   /*
15064   ** Array of lists of free blocks according to the block size 
15065   ** for smaller chunks, or a hash on the block size for larger
15066   ** chunks.
15067   */
15068   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
15069   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
15070 } mem3 = { 97535575 };
15071
15072 #define mem3 GLOBAL(struct Mem3Global, mem3)
15073
15074 /*
15075 ** Unlink the chunk at mem3.aPool[i] from list it is currently
15076 ** on.  *pRoot is the list that i is a member of.
15077 */
15078 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
15079   u32 next = mem3.aPool[i].u.list.next;
15080   u32 prev = mem3.aPool[i].u.list.prev;
15081   assert( sqlite3_mutex_held(mem3.mutex) );
15082   if( prev==0 ){
15083     *pRoot = next;
15084   }else{
15085     mem3.aPool[prev].u.list.next = next;
15086   }
15087   if( next ){
15088     mem3.aPool[next].u.list.prev = prev;
15089   }
15090   mem3.aPool[i].u.list.next = 0;
15091   mem3.aPool[i].u.list.prev = 0;
15092 }
15093
15094 /*
15095 ** Unlink the chunk at index i from 
15096 ** whatever list is currently a member of.
15097 */
15098 static void memsys3Unlink(u32 i){
15099   u32 size, hash;
15100   assert( sqlite3_mutex_held(mem3.mutex) );
15101   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
15102   assert( i>=1 );
15103   size = mem3.aPool[i-1].u.hdr.size4x/4;
15104   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
15105   assert( size>=2 );
15106   if( size <= MX_SMALL ){
15107     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
15108   }else{
15109     hash = size % N_HASH;
15110     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
15111   }
15112 }
15113
15114 /*
15115 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
15116 ** at *pRoot.
15117 */
15118 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
15119   assert( sqlite3_mutex_held(mem3.mutex) );
15120   mem3.aPool[i].u.list.next = *pRoot;
15121   mem3.aPool[i].u.list.prev = 0;
15122   if( *pRoot ){
15123     mem3.aPool[*pRoot].u.list.prev = i;
15124   }
15125   *pRoot = i;
15126 }
15127
15128 /*
15129 ** Link the chunk at index i into either the appropriate
15130 ** small chunk list, or into the large chunk hash table.
15131 */
15132 static void memsys3Link(u32 i){
15133   u32 size, hash;
15134   assert( sqlite3_mutex_held(mem3.mutex) );
15135   assert( i>=1 );
15136   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
15137   size = mem3.aPool[i-1].u.hdr.size4x/4;
15138   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
15139   assert( size>=2 );
15140   if( size <= MX_SMALL ){
15141     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
15142   }else{
15143     hash = size % N_HASH;
15144     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
15145   }
15146 }
15147
15148 /*
15149 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
15150 ** will already be held (obtained by code in malloc.c) if
15151 ** sqlite3GlobalConfig.bMemStat is true.
15152 */
15153 static void memsys3Enter(void){
15154   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
15155     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15156   }
15157   sqlite3_mutex_enter(mem3.mutex);
15158 }
15159 static void memsys3Leave(void){
15160   sqlite3_mutex_leave(mem3.mutex);
15161 }
15162
15163 /*
15164 ** Called when we are unable to satisfy an allocation of nBytes.
15165 */
15166 static void memsys3OutOfMemory(int nByte){
15167   if( !mem3.alarmBusy ){
15168     mem3.alarmBusy = 1;
15169     assert( sqlite3_mutex_held(mem3.mutex) );
15170     sqlite3_mutex_leave(mem3.mutex);
15171     sqlite3_release_memory(nByte);
15172     sqlite3_mutex_enter(mem3.mutex);
15173     mem3.alarmBusy = 0;
15174   }
15175 }
15176
15177
15178 /*
15179 ** Chunk i is a free chunk that has been unlinked.  Adjust its 
15180 ** size parameters for check-out and return a pointer to the 
15181 ** user portion of the chunk.
15182 */
15183 static void *memsys3Checkout(u32 i, u32 nBlock){
15184   u32 x;
15185   assert( sqlite3_mutex_held(mem3.mutex) );
15186   assert( i>=1 );
15187   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
15188   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
15189   x = mem3.aPool[i-1].u.hdr.size4x;
15190   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
15191   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
15192   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
15193   return &mem3.aPool[i];
15194 }
15195
15196 /*
15197 ** Carve a piece off of the end of the mem3.iMaster free chunk.
15198 ** Return a pointer to the new allocation.  Or, if the master chunk
15199 ** is not large enough, return 0.
15200 */
15201 static void *memsys3FromMaster(u32 nBlock){
15202   assert( sqlite3_mutex_held(mem3.mutex) );
15203   assert( mem3.szMaster>=nBlock );
15204   if( nBlock>=mem3.szMaster-1 ){
15205     /* Use the entire master */
15206     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
15207     mem3.iMaster = 0;
15208     mem3.szMaster = 0;
15209     mem3.mnMaster = 0;
15210     return p;
15211   }else{
15212     /* Split the master block.  Return the tail. */
15213     u32 newi, x;
15214     newi = mem3.iMaster + mem3.szMaster - nBlock;
15215     assert( newi > mem3.iMaster+1 );
15216     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
15217     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
15218     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
15219     mem3.szMaster -= nBlock;
15220     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
15221     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15222     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15223     if( mem3.szMaster < mem3.mnMaster ){
15224       mem3.mnMaster = mem3.szMaster;
15225     }
15226     return (void*)&mem3.aPool[newi];
15227   }
15228 }
15229
15230 /*
15231 ** *pRoot is the head of a list of free chunks of the same size
15232 ** or same size hash.  In other words, *pRoot is an entry in either
15233 ** mem3.aiSmall[] or mem3.aiHash[].  
15234 **
15235 ** This routine examines all entries on the given list and tries
15236 ** to coalesce each entries with adjacent free chunks.  
15237 **
15238 ** If it sees a chunk that is larger than mem3.iMaster, it replaces 
15239 ** the current mem3.iMaster with the new larger chunk.  In order for
15240 ** this mem3.iMaster replacement to work, the master chunk must be
15241 ** linked into the hash tables.  That is not the normal state of
15242 ** affairs, of course.  The calling routine must link the master
15243 ** chunk before invoking this routine, then must unlink the (possibly
15244 ** changed) master chunk once this routine has finished.
15245 */
15246 static void memsys3Merge(u32 *pRoot){
15247   u32 iNext, prev, size, i, x;
15248
15249   assert( sqlite3_mutex_held(mem3.mutex) );
15250   for(i=*pRoot; i>0; i=iNext){
15251     iNext = mem3.aPool[i].u.list.next;
15252     size = mem3.aPool[i-1].u.hdr.size4x;
15253     assert( (size&1)==0 );
15254     if( (size&2)==0 ){
15255       memsys3UnlinkFromList(i, pRoot);
15256       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
15257       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
15258       if( prev==iNext ){
15259         iNext = mem3.aPool[prev].u.list.next;
15260       }
15261       memsys3Unlink(prev);
15262       size = i + size/4 - prev;
15263       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
15264       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
15265       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
15266       memsys3Link(prev);
15267       i = prev;
15268     }else{
15269       size /= 4;
15270     }
15271     if( size>mem3.szMaster ){
15272       mem3.iMaster = i;
15273       mem3.szMaster = size;
15274     }
15275   }
15276 }
15277
15278 /*
15279 ** Return a block of memory of at least nBytes in size.
15280 ** Return NULL if unable.
15281 **
15282 ** This function assumes that the necessary mutexes, if any, are
15283 ** already held by the caller. Hence "Unsafe".
15284 */
15285 static void *memsys3MallocUnsafe(int nByte){
15286   u32 i;
15287   u32 nBlock;
15288   u32 toFree;
15289
15290   assert( sqlite3_mutex_held(mem3.mutex) );
15291   assert( sizeof(Mem3Block)==8 );
15292   if( nByte<=12 ){
15293     nBlock = 2;
15294   }else{
15295     nBlock = (nByte + 11)/8;
15296   }
15297   assert( nBlock>=2 );
15298
15299   /* STEP 1:
15300   ** Look for an entry of the correct size in either the small
15301   ** chunk table or in the large chunk hash table.  This is
15302   ** successful most of the time (about 9 times out of 10).
15303   */
15304   if( nBlock <= MX_SMALL ){
15305     i = mem3.aiSmall[nBlock-2];
15306     if( i>0 ){
15307       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
15308       return memsys3Checkout(i, nBlock);
15309     }
15310   }else{
15311     int hash = nBlock % N_HASH;
15312     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
15313       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
15314         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
15315         return memsys3Checkout(i, nBlock);
15316       }
15317     }
15318   }
15319
15320   /* STEP 2:
15321   ** Try to satisfy the allocation by carving a piece off of the end
15322   ** of the master chunk.  This step usually works if step 1 fails.
15323   */
15324   if( mem3.szMaster>=nBlock ){
15325     return memsys3FromMaster(nBlock);
15326   }
15327
15328
15329   /* STEP 3:  
15330   ** Loop through the entire memory pool.  Coalesce adjacent free
15331   ** chunks.  Recompute the master chunk as the largest free chunk.
15332   ** Then try again to satisfy the allocation by carving a piece off
15333   ** of the end of the master chunk.  This step happens very
15334   ** rarely (we hope!)
15335   */
15336   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
15337     memsys3OutOfMemory(toFree);
15338     if( mem3.iMaster ){
15339       memsys3Link(mem3.iMaster);
15340       mem3.iMaster = 0;
15341       mem3.szMaster = 0;
15342     }
15343     for(i=0; i<N_HASH; i++){
15344       memsys3Merge(&mem3.aiHash[i]);
15345     }
15346     for(i=0; i<MX_SMALL-1; i++){
15347       memsys3Merge(&mem3.aiSmall[i]);
15348     }
15349     if( mem3.szMaster ){
15350       memsys3Unlink(mem3.iMaster);
15351       if( mem3.szMaster>=nBlock ){
15352         return memsys3FromMaster(nBlock);
15353       }
15354     }
15355   }
15356
15357   /* If none of the above worked, then we fail. */
15358   return 0;
15359 }
15360
15361 /*
15362 ** Free an outstanding memory allocation.
15363 **
15364 ** This function assumes that the necessary mutexes, if any, are
15365 ** already held by the caller. Hence "Unsafe".
15366 */
15367 void memsys3FreeUnsafe(void *pOld){
15368   Mem3Block *p = (Mem3Block*)pOld;
15369   int i;
15370   u32 size, x;
15371   assert( sqlite3_mutex_held(mem3.mutex) );
15372   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
15373   i = p - mem3.aPool;
15374   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
15375   size = mem3.aPool[i-1].u.hdr.size4x/4;
15376   assert( i+size<=mem3.nPool+1 );
15377   mem3.aPool[i-1].u.hdr.size4x &= ~1;
15378   mem3.aPool[i+size-1].u.hdr.prevSize = size;
15379   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
15380   memsys3Link(i);
15381
15382   /* Try to expand the master using the newly freed chunk */
15383   if( mem3.iMaster ){
15384     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
15385       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
15386       mem3.iMaster -= size;
15387       mem3.szMaster += size;
15388       memsys3Unlink(mem3.iMaster);
15389       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15390       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15391       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
15392     }
15393     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15394     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
15395       memsys3Unlink(mem3.iMaster+mem3.szMaster);
15396       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
15397       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15398       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
15399     }
15400   }
15401 }
15402
15403 /*
15404 ** Return the size of an outstanding allocation, in bytes.  The
15405 ** size returned omits the 8-byte header overhead.  This only
15406 ** works for chunks that are currently checked out.
15407 */
15408 static int memsys3Size(void *p){
15409   Mem3Block *pBlock;
15410   if( p==0 ) return 0;
15411   pBlock = (Mem3Block*)p;
15412   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
15413   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
15414 }
15415
15416 /*
15417 ** Round up a request size to the next valid allocation size.
15418 */
15419 static int memsys3Roundup(int n){
15420   if( n<=12 ){
15421     return 12;
15422   }else{
15423     return ((n+11)&~7) - 4;
15424   }
15425 }
15426
15427 /*
15428 ** Allocate nBytes of memory.
15429 */
15430 static void *memsys3Malloc(int nBytes){
15431   sqlite3_int64 *p;
15432   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
15433   memsys3Enter();
15434   p = memsys3MallocUnsafe(nBytes);
15435   memsys3Leave();
15436   return (void*)p; 
15437 }
15438
15439 /*
15440 ** Free memory.
15441 */
15442 void memsys3Free(void *pPrior){
15443   assert( pPrior );
15444   memsys3Enter();
15445   memsys3FreeUnsafe(pPrior);
15446   memsys3Leave();
15447 }
15448
15449 /*
15450 ** Change the size of an existing memory allocation
15451 */
15452 void *memsys3Realloc(void *pPrior, int nBytes){
15453   int nOld;
15454   void *p;
15455   if( pPrior==0 ){
15456     return sqlite3_malloc(nBytes);
15457   }
15458   if( nBytes<=0 ){
15459     sqlite3_free(pPrior);
15460     return 0;
15461   }
15462   nOld = memsys3Size(pPrior);
15463   if( nBytes<=nOld && nBytes>=nOld-128 ){
15464     return pPrior;
15465   }
15466   memsys3Enter();
15467   p = memsys3MallocUnsafe(nBytes);
15468   if( p ){
15469     if( nOld<nBytes ){
15470       memcpy(p, pPrior, nOld);
15471     }else{
15472       memcpy(p, pPrior, nBytes);
15473     }
15474     memsys3FreeUnsafe(pPrior);
15475   }
15476   memsys3Leave();
15477   return p;
15478 }
15479
15480 /*
15481 ** Initialize this module.
15482 */
15483 static int memsys3Init(void *NotUsed){
15484   UNUSED_PARAMETER(NotUsed);
15485   if( !sqlite3GlobalConfig.pHeap ){
15486     return SQLITE_ERROR;
15487   }
15488
15489   /* Store a pointer to the memory block in global structure mem3. */
15490   assert( sizeof(Mem3Block)==8 );
15491   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
15492   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
15493
15494   /* Initialize the master block. */
15495   mem3.szMaster = mem3.nPool;
15496   mem3.mnMaster = mem3.szMaster;
15497   mem3.iMaster = 1;
15498   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
15499   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
15500   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
15501
15502   return SQLITE_OK;
15503 }
15504
15505 /*
15506 ** Deinitialize this module.
15507 */
15508 static void memsys3Shutdown(void *NotUsed){
15509   UNUSED_PARAMETER(NotUsed);
15510   mem3.mutex = 0;
15511   return;
15512 }
15513
15514
15515
15516 /*
15517 ** Open the file indicated and write a log of all unfreed memory 
15518 ** allocations into that log.
15519 */
15520 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
15521 #ifdef SQLITE_DEBUG
15522   FILE *out;
15523   u32 i, j;
15524   u32 size;
15525   if( zFilename==0 || zFilename[0]==0 ){
15526     out = stdout;
15527   }else{
15528     out = fopen(zFilename, "w");
15529     if( out==0 ){
15530       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
15531                       zFilename);
15532       return;
15533     }
15534   }
15535   memsys3Enter();
15536   fprintf(out, "CHUNKS:\n");
15537   for(i=1; i<=mem3.nPool; i+=size/4){
15538     size = mem3.aPool[i-1].u.hdr.size4x;
15539     if( size/4<=1 ){
15540       fprintf(out, "%p size error\n", &mem3.aPool[i]);
15541       assert( 0 );
15542       break;
15543     }
15544     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
15545       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
15546       assert( 0 );
15547       break;
15548     }
15549     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
15550       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
15551       assert( 0 );
15552       break;
15553     }
15554     if( size&1 ){
15555       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
15556     }else{
15557       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
15558                   i==mem3.iMaster ? " **master**" : "");
15559     }
15560   }
15561   for(i=0; i<MX_SMALL-1; i++){
15562     if( mem3.aiSmall[i]==0 ) continue;
15563     fprintf(out, "small(%2d):", i);
15564     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
15565       fprintf(out, " %p(%d)", &mem3.aPool[j],
15566               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
15567     }
15568     fprintf(out, "\n"); 
15569   }
15570   for(i=0; i<N_HASH; i++){
15571     if( mem3.aiHash[i]==0 ) continue;
15572     fprintf(out, "hash(%2d):", i);
15573     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
15574       fprintf(out, " %p(%d)", &mem3.aPool[j],
15575               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
15576     }
15577     fprintf(out, "\n"); 
15578   }
15579   fprintf(out, "master=%d\n", mem3.iMaster);
15580   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
15581   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
15582   sqlite3_mutex_leave(mem3.mutex);
15583   if( out==stdout ){
15584     fflush(stdout);
15585   }else{
15586     fclose(out);
15587   }
15588 #else
15589   UNUSED_PARAMETER(zFilename);
15590 #endif
15591 }
15592
15593 /*
15594 ** This routine is the only routine in this file with external 
15595 ** linkage.
15596 **
15597 ** Populate the low-level memory allocation function pointers in
15598 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
15599 ** arguments specify the block of memory to manage.
15600 **
15601 ** This routine is only called by sqlite3_config(), and therefore
15602 ** is not required to be threadsafe (it is not).
15603 */
15604 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
15605   static const sqlite3_mem_methods mempoolMethods = {
15606      memsys3Malloc,
15607      memsys3Free,
15608      memsys3Realloc,
15609      memsys3Size,
15610      memsys3Roundup,
15611      memsys3Init,
15612      memsys3Shutdown,
15613      0
15614   };
15615   return &mempoolMethods;
15616 }
15617
15618 #endif /* SQLITE_ENABLE_MEMSYS3 */
15619
15620 /************** End of mem3.c ************************************************/
15621 /************** Begin file mem5.c ********************************************/
15622 /*
15623 ** 2007 October 14
15624 **
15625 ** The author disclaims copyright to this source code.  In place of
15626 ** a legal notice, here is a blessing:
15627 **
15628 **    May you do good and not evil.
15629 **    May you find forgiveness for yourself and forgive others.
15630 **    May you share freely, never taking more than you give.
15631 **
15632 *************************************************************************
15633 ** This file contains the C functions that implement a memory
15634 ** allocation subsystem for use by SQLite. 
15635 **
15636 ** This version of the memory allocation subsystem omits all
15637 ** use of malloc(). The application gives SQLite a block of memory
15638 ** before calling sqlite3_initialize() from which allocations
15639 ** are made and returned by the xMalloc() and xRealloc() 
15640 ** implementations. Once sqlite3_initialize() has been called,
15641 ** the amount of memory available to SQLite is fixed and cannot
15642 ** be changed.
15643 **
15644 ** This version of the memory allocation subsystem is included
15645 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
15646 **
15647 ** This memory allocator uses the following algorithm:
15648 **
15649 **   1.  All memory allocations sizes are rounded up to a power of 2.
15650 **
15651 **   2.  If two adjacent free blocks are the halves of a larger block,
15652 **       then the two blocks are coalesed into the single larger block.
15653 **
15654 **   3.  New memory is allocated from the first available free block.
15655 **
15656 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
15657 ** Concerning Dynamic Storage Allocation". Journal of the Association for
15658 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
15659 ** 
15660 ** Let n be the size of the largest allocation divided by the minimum
15661 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
15662 ** be the maximum amount of memory ever outstanding at one time.  Let
15663 ** N be the total amount of memory available for allocation.  Robson
15664 ** proved that this memory allocator will never breakdown due to 
15665 ** fragmentation as long as the following constraint holds:
15666 **
15667 **      N >=  M*(1 + log2(n)/2) - n + 1
15668 **
15669 ** The sqlite3_status() logic tracks the maximum values of n and M so
15670 ** that an application can, at any time, verify this constraint.
15671 */
15672
15673 /*
15674 ** This version of the memory allocator is used only when 
15675 ** SQLITE_ENABLE_MEMSYS5 is defined.
15676 */
15677 #ifdef SQLITE_ENABLE_MEMSYS5
15678
15679 /*
15680 ** A minimum allocation is an instance of the following structure.
15681 ** Larger allocations are an array of these structures where the
15682 ** size of the array is a power of 2.
15683 **
15684 ** The size of this object must be a power of two.  That fact is
15685 ** verified in memsys5Init().
15686 */
15687 typedef struct Mem5Link Mem5Link;
15688 struct Mem5Link {
15689   int next;       /* Index of next free chunk */
15690   int prev;       /* Index of previous free chunk */
15691 };
15692
15693 /*
15694 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
15695 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
15696 ** it is not actually possible to reach this limit.
15697 */
15698 #define LOGMAX 30
15699
15700 /*
15701 ** Masks used for mem5.aCtrl[] elements.
15702 */
15703 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
15704 #define CTRL_FREE     0x20    /* True if not checked out */
15705
15706 /*
15707 ** All of the static variables used by this module are collected
15708 ** into a single structure named "mem5".  This is to keep the
15709 ** static variables organized and to reduce namespace pollution
15710 ** when this module is combined with other in the amalgamation.
15711 */
15712 static SQLITE_WSD struct Mem5Global {
15713   /*
15714   ** Memory available for allocation
15715   */
15716   int szAtom;      /* Smallest possible allocation in bytes */
15717   int nBlock;      /* Number of szAtom sized blocks in zPool */
15718   u8 *zPool;       /* Memory available to be allocated */
15719   
15720   /*
15721   ** Mutex to control access to the memory allocation subsystem.
15722   */
15723   sqlite3_mutex *mutex;
15724
15725   /*
15726   ** Performance statistics
15727   */
15728   u64 nAlloc;         /* Total number of calls to malloc */
15729   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
15730   u64 totalExcess;    /* Total internal fragmentation */
15731   u32 currentOut;     /* Current checkout, including internal fragmentation */
15732   u32 currentCount;   /* Current number of distinct checkouts */
15733   u32 maxOut;         /* Maximum instantaneous currentOut */
15734   u32 maxCount;       /* Maximum instantaneous currentCount */
15735   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
15736   
15737   /*
15738   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
15739   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
15740   ** and so forth.
15741   */
15742   int aiFreelist[LOGMAX+1];
15743
15744   /*
15745   ** Space for tracking which blocks are checked out and the size
15746   ** of each block.  One byte per block.
15747   */
15748   u8 *aCtrl;
15749
15750 } mem5 = { 0 };
15751
15752 /*
15753 ** Access the static variable through a macro for SQLITE_OMIT_WSD
15754 */
15755 #define mem5 GLOBAL(struct Mem5Global, mem5)
15756
15757 /*
15758 ** Assuming mem5.zPool is divided up into an array of Mem5Link
15759 ** structures, return a pointer to the idx-th such lik.
15760 */
15761 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
15762
15763 /*
15764 ** Unlink the chunk at mem5.aPool[i] from list it is currently
15765 ** on.  It should be found on mem5.aiFreelist[iLogsize].
15766 */
15767 static void memsys5Unlink(int i, int iLogsize){
15768   int next, prev;
15769   assert( i>=0 && i<mem5.nBlock );
15770   assert( iLogsize>=0 && iLogsize<=LOGMAX );
15771   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
15772
15773   next = MEM5LINK(i)->next;
15774   prev = MEM5LINK(i)->prev;
15775   if( prev<0 ){
15776     mem5.aiFreelist[iLogsize] = next;
15777   }else{
15778     MEM5LINK(prev)->next = next;
15779   }
15780   if( next>=0 ){
15781     MEM5LINK(next)->prev = prev;
15782   }
15783 }
15784
15785 /*
15786 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
15787 ** free list.
15788 */
15789 static void memsys5Link(int i, int iLogsize){
15790   int x;
15791   assert( sqlite3_mutex_held(mem5.mutex) );
15792   assert( i>=0 && i<mem5.nBlock );
15793   assert( iLogsize>=0 && iLogsize<=LOGMAX );
15794   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
15795
15796   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
15797   MEM5LINK(i)->prev = -1;
15798   if( x>=0 ){
15799     assert( x<mem5.nBlock );
15800     MEM5LINK(x)->prev = i;
15801   }
15802   mem5.aiFreelist[iLogsize] = i;
15803 }
15804
15805 /*
15806 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
15807 ** will already be held (obtained by code in malloc.c) if
15808 ** sqlite3GlobalConfig.bMemStat is true.
15809 */
15810 static void memsys5Enter(void){
15811   sqlite3_mutex_enter(mem5.mutex);
15812 }
15813 static void memsys5Leave(void){
15814   sqlite3_mutex_leave(mem5.mutex);
15815 }
15816
15817 /*
15818 ** Return the size of an outstanding allocation, in bytes.  The
15819 ** size returned omits the 8-byte header overhead.  This only
15820 ** works for chunks that are currently checked out.
15821 */
15822 static int memsys5Size(void *p){
15823   int iSize = 0;
15824   if( p ){
15825     int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
15826     assert( i>=0 && i<mem5.nBlock );
15827     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
15828   }
15829   return iSize;
15830 }
15831
15832 /*
15833 ** Find the first entry on the freelist iLogsize.  Unlink that
15834 ** entry and return its index. 
15835 */
15836 static int memsys5UnlinkFirst(int iLogsize){
15837   int i;
15838   int iFirst;
15839
15840   assert( iLogsize>=0 && iLogsize<=LOGMAX );
15841   i = iFirst = mem5.aiFreelist[iLogsize];
15842   assert( iFirst>=0 );
15843   while( i>0 ){
15844     if( i<iFirst ) iFirst = i;
15845     i = MEM5LINK(i)->next;
15846   }
15847   memsys5Unlink(iFirst, iLogsize);
15848   return iFirst;
15849 }
15850
15851 /*
15852 ** Return a block of memory of at least nBytes in size.
15853 ** Return NULL if unable.  Return NULL if nBytes==0.
15854 **
15855 ** The caller guarantees that nByte positive.
15856 **
15857 ** The caller has obtained a mutex prior to invoking this
15858 ** routine so there is never any chance that two or more
15859 ** threads can be in this routine at the same time.
15860 */
15861 static void *memsys5MallocUnsafe(int nByte){
15862   int i;           /* Index of a mem5.aPool[] slot */
15863   int iBin;        /* Index into mem5.aiFreelist[] */
15864   int iFullSz;     /* Size of allocation rounded up to power of 2 */
15865   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
15866
15867   /* nByte must be a positive */
15868   assert( nByte>0 );
15869
15870   /* Keep track of the maximum allocation request.  Even unfulfilled
15871   ** requests are counted */
15872   if( (u32)nByte>mem5.maxRequest ){
15873     mem5.maxRequest = nByte;
15874   }
15875
15876   /* Abort if the requested allocation size is larger than the largest
15877   ** power of two that we can represent using 32-bit signed integers.
15878   */
15879   if( nByte > 0x40000000 ){
15880     return 0;
15881   }
15882
15883   /* Round nByte up to the next valid power of two */
15884   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
15885
15886   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
15887   ** block.  If not, then split a block of the next larger power of
15888   ** two in order to create a new free block of size iLogsize.
15889   */
15890   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
15891   if( iBin>LOGMAX ){
15892     testcase( sqlite3GlobalConfig.xLog!=0 );
15893     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
15894     return 0;
15895   }
15896   i = memsys5UnlinkFirst(iBin);
15897   while( iBin>iLogsize ){
15898     int newSize;
15899
15900     iBin--;
15901     newSize = 1 << iBin;
15902     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
15903     memsys5Link(i+newSize, iBin);
15904   }
15905   mem5.aCtrl[i] = iLogsize;
15906
15907   /* Update allocator performance statistics. */
15908   mem5.nAlloc++;
15909   mem5.totalAlloc += iFullSz;
15910   mem5.totalExcess += iFullSz - nByte;
15911   mem5.currentCount++;
15912   mem5.currentOut += iFullSz;
15913   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
15914   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
15915
15916   /* Return a pointer to the allocated memory. */
15917   return (void*)&mem5.zPool[i*mem5.szAtom];
15918 }
15919
15920 /*
15921 ** Free an outstanding memory allocation.
15922 */
15923 static void memsys5FreeUnsafe(void *pOld){
15924   u32 size, iLogsize;
15925   int iBlock;
15926
15927   /* Set iBlock to the index of the block pointed to by pOld in 
15928   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
15929   */
15930   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
15931
15932   /* Check that the pointer pOld points to a valid, non-free block. */
15933   assert( iBlock>=0 && iBlock<mem5.nBlock );
15934   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
15935   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
15936
15937   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
15938   size = 1<<iLogsize;
15939   assert( iBlock+size-1<(u32)mem5.nBlock );
15940
15941   mem5.aCtrl[iBlock] |= CTRL_FREE;
15942   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
15943   assert( mem5.currentCount>0 );
15944   assert( mem5.currentOut>=(size*mem5.szAtom) );
15945   mem5.currentCount--;
15946   mem5.currentOut -= size*mem5.szAtom;
15947   assert( mem5.currentOut>0 || mem5.currentCount==0 );
15948   assert( mem5.currentCount>0 || mem5.currentOut==0 );
15949
15950   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
15951   while( ALWAYS(iLogsize<LOGMAX) ){
15952     int iBuddy;
15953     if( (iBlock>>iLogsize) & 1 ){
15954       iBuddy = iBlock - size;
15955     }else{
15956       iBuddy = iBlock + size;
15957     }
15958     assert( iBuddy>=0 );
15959     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
15960     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
15961     memsys5Unlink(iBuddy, iLogsize);
15962     iLogsize++;
15963     if( iBuddy<iBlock ){
15964       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
15965       mem5.aCtrl[iBlock] = 0;
15966       iBlock = iBuddy;
15967     }else{
15968       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
15969       mem5.aCtrl[iBuddy] = 0;
15970     }
15971     size *= 2;
15972   }
15973   memsys5Link(iBlock, iLogsize);
15974 }
15975
15976 /*
15977 ** Allocate nBytes of memory
15978 */
15979 static void *memsys5Malloc(int nBytes){
15980   sqlite3_int64 *p = 0;
15981   if( nBytes>0 ){
15982     memsys5Enter();
15983     p = memsys5MallocUnsafe(nBytes);
15984     memsys5Leave();
15985   }
15986   return (void*)p; 
15987 }
15988
15989 /*
15990 ** Free memory.
15991 **
15992 ** The outer layer memory allocator prevents this routine from
15993 ** being called with pPrior==0.
15994 */
15995 static void memsys5Free(void *pPrior){
15996   assert( pPrior!=0 );
15997   memsys5Enter();
15998   memsys5FreeUnsafe(pPrior);
15999   memsys5Leave();  
16000 }
16001
16002 /*
16003 ** Change the size of an existing memory allocation.
16004 **
16005 ** The outer layer memory allocator prevents this routine from
16006 ** being called with pPrior==0.  
16007 **
16008 ** nBytes is always a value obtained from a prior call to
16009 ** memsys5Round().  Hence nBytes is always a non-negative power
16010 ** of two.  If nBytes==0 that means that an oversize allocation
16011 ** (an allocation larger than 0x40000000) was requested and this
16012 ** routine should return 0 without freeing pPrior.
16013 */
16014 static void *memsys5Realloc(void *pPrior, int nBytes){
16015   int nOld;
16016   void *p;
16017   assert( pPrior!=0 );
16018   assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
16019   assert( nBytes>=0 );
16020   if( nBytes==0 ){
16021     return 0;
16022   }
16023   nOld = memsys5Size(pPrior);
16024   if( nBytes<=nOld ){
16025     return pPrior;
16026   }
16027   memsys5Enter();
16028   p = memsys5MallocUnsafe(nBytes);
16029   if( p ){
16030     memcpy(p, pPrior, nOld);
16031     memsys5FreeUnsafe(pPrior);
16032   }
16033   memsys5Leave();
16034   return p;
16035 }
16036
16037 /*
16038 ** Round up a request size to the next valid allocation size.  If
16039 ** the allocation is too large to be handled by this allocation system,
16040 ** return 0.
16041 **
16042 ** All allocations must be a power of two and must be expressed by a
16043 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
16044 ** or 1073741824 bytes.
16045 */
16046 static int memsys5Roundup(int n){
16047   int iFullSz;
16048   if( n > 0x40000000 ) return 0;
16049   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
16050   return iFullSz;
16051 }
16052
16053 /*
16054 ** Return the ceiling of the logarithm base 2 of iValue.
16055 **
16056 ** Examples:   memsys5Log(1) -> 0
16057 **             memsys5Log(2) -> 1
16058 **             memsys5Log(4) -> 2
16059 **             memsys5Log(5) -> 3
16060 **             memsys5Log(8) -> 3
16061 **             memsys5Log(9) -> 4
16062 */
16063 static int memsys5Log(int iValue){
16064   int iLog;
16065   for(iLog=0; (1<<iLog)<iValue; iLog++);
16066   return iLog;
16067 }
16068
16069 /*
16070 ** Initialize the memory allocator.
16071 **
16072 ** This routine is not threadsafe.  The caller must be holding a mutex
16073 ** to prevent multiple threads from entering at the same time.
16074 */
16075 static int memsys5Init(void *NotUsed){
16076   int ii;            /* Loop counter */
16077   int nByte;         /* Number of bytes of memory available to this allocator */
16078   u8 *zByte;         /* Memory usable by this allocator */
16079   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
16080   int iOffset;       /* An offset into mem5.aCtrl[] */
16081
16082   UNUSED_PARAMETER(NotUsed);
16083
16084   /* For the purposes of this routine, disable the mutex */
16085   mem5.mutex = 0;
16086
16087   /* The size of a Mem5Link object must be a power of two.  Verify that
16088   ** this is case.
16089   */
16090   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
16091
16092   nByte = sqlite3GlobalConfig.nHeap;
16093   zByte = (u8*)sqlite3GlobalConfig.pHeap;
16094   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
16095
16096   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
16097   mem5.szAtom = (1<<nMinLog);
16098   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
16099     mem5.szAtom = mem5.szAtom << 1;
16100   }
16101
16102   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
16103   mem5.zPool = zByte;
16104   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
16105
16106   for(ii=0; ii<=LOGMAX; ii++){
16107     mem5.aiFreelist[ii] = -1;
16108   }
16109
16110   iOffset = 0;
16111   for(ii=LOGMAX; ii>=0; ii--){
16112     int nAlloc = (1<<ii);
16113     if( (iOffset+nAlloc)<=mem5.nBlock ){
16114       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
16115       memsys5Link(iOffset, ii);
16116       iOffset += nAlloc;
16117     }
16118     assert((iOffset+nAlloc)>mem5.nBlock);
16119   }
16120
16121   /* If a mutex is required for normal operation, allocate one */
16122   if( sqlite3GlobalConfig.bMemstat==0 ){
16123     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16124   }
16125
16126   return SQLITE_OK;
16127 }
16128
16129 /*
16130 ** Deinitialize this module.
16131 */
16132 static void memsys5Shutdown(void *NotUsed){
16133   UNUSED_PARAMETER(NotUsed);
16134   mem5.mutex = 0;
16135   return;
16136 }
16137
16138 #ifdef SQLITE_TEST
16139 /*
16140 ** Open the file indicated and write a log of all unfreed memory 
16141 ** allocations into that log.
16142 */
16143 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
16144   FILE *out;
16145   int i, j, n;
16146   int nMinLog;
16147
16148   if( zFilename==0 || zFilename[0]==0 ){
16149     out = stdout;
16150   }else{
16151     out = fopen(zFilename, "w");
16152     if( out==0 ){
16153       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16154                       zFilename);
16155       return;
16156     }
16157   }
16158   memsys5Enter();
16159   nMinLog = memsys5Log(mem5.szAtom);
16160   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
16161     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
16162     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
16163   }
16164   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
16165   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
16166   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
16167   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
16168   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
16169   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
16170   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
16171   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
16172   memsys5Leave();
16173   if( out==stdout ){
16174     fflush(stdout);
16175   }else{
16176     fclose(out);
16177   }
16178 }
16179 #endif
16180
16181 /*
16182 ** This routine is the only routine in this file with external 
16183 ** linkage. It returns a pointer to a static sqlite3_mem_methods
16184 ** struct populated with the memsys5 methods.
16185 */
16186 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
16187   static const sqlite3_mem_methods memsys5Methods = {
16188      memsys5Malloc,
16189      memsys5Free,
16190      memsys5Realloc,
16191      memsys5Size,
16192      memsys5Roundup,
16193      memsys5Init,
16194      memsys5Shutdown,
16195      0
16196   };
16197   return &memsys5Methods;
16198 }
16199
16200 #endif /* SQLITE_ENABLE_MEMSYS5 */
16201
16202 /************** End of mem5.c ************************************************/
16203 /************** Begin file mutex.c *******************************************/
16204 /*
16205 ** 2007 August 14
16206 **
16207 ** The author disclaims copyright to this source code.  In place of
16208 ** a legal notice, here is a blessing:
16209 **
16210 **    May you do good and not evil.
16211 **    May you find forgiveness for yourself and forgive others.
16212 **    May you share freely, never taking more than you give.
16213 **
16214 *************************************************************************
16215 ** This file contains the C functions that implement mutexes.
16216 **
16217 ** This file contains code that is common across all mutex implementations.
16218 */
16219
16220 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
16221 /*
16222 ** For debugging purposes, record when the mutex subsystem is initialized
16223 ** and uninitialized so that we can assert() if there is an attempt to
16224 ** allocate a mutex while the system is uninitialized.
16225 */
16226 static SQLITE_WSD int mutexIsInit = 0;
16227 #endif /* SQLITE_DEBUG */
16228
16229
16230 #ifndef SQLITE_MUTEX_OMIT
16231 /*
16232 ** Initialize the mutex system.
16233 */
16234 SQLITE_PRIVATE int sqlite3MutexInit(void){ 
16235   int rc = SQLITE_OK;
16236   if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
16237     /* If the xMutexAlloc method has not been set, then the user did not
16238     ** install a mutex implementation via sqlite3_config() prior to 
16239     ** sqlite3_initialize() being called. This block copies pointers to
16240     ** the default implementation into the sqlite3GlobalConfig structure.
16241     */
16242     sqlite3_mutex_methods const *pFrom;
16243     sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
16244
16245     if( sqlite3GlobalConfig.bCoreMutex ){
16246       pFrom = sqlite3DefaultMutex();
16247     }else{
16248       pFrom = sqlite3NoopMutex();
16249     }
16250     memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
16251     memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
16252            sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
16253     pTo->xMutexAlloc = pFrom->xMutexAlloc;
16254   }
16255   rc = sqlite3GlobalConfig.mutex.xMutexInit();
16256
16257 #ifdef SQLITE_DEBUG
16258   GLOBAL(int, mutexIsInit) = 1;
16259 #endif
16260
16261   return rc;
16262 }
16263
16264 /*
16265 ** Shutdown the mutex system. This call frees resources allocated by
16266 ** sqlite3MutexInit().
16267 */
16268 SQLITE_PRIVATE int sqlite3MutexEnd(void){
16269   int rc = SQLITE_OK;
16270   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
16271     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
16272   }
16273
16274 #ifdef SQLITE_DEBUG
16275   GLOBAL(int, mutexIsInit) = 0;
16276 #endif
16277
16278   return rc;
16279 }
16280
16281 /*
16282 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
16283 */
16284 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
16285 #ifndef SQLITE_OMIT_AUTOINIT
16286   if( sqlite3_initialize() ) return 0;
16287 #endif
16288   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
16289 }
16290
16291 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
16292   if( !sqlite3GlobalConfig.bCoreMutex ){
16293     return 0;
16294   }
16295   assert( GLOBAL(int, mutexIsInit) );
16296   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
16297 }
16298
16299 /*
16300 ** Free a dynamic mutex.
16301 */
16302 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
16303   if( p ){
16304     sqlite3GlobalConfig.mutex.xMutexFree(p);
16305   }
16306 }
16307
16308 /*
16309 ** Obtain the mutex p. If some other thread already has the mutex, block
16310 ** until it can be obtained.
16311 */
16312 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
16313   if( p ){
16314     sqlite3GlobalConfig.mutex.xMutexEnter(p);
16315   }
16316 }
16317
16318 /*
16319 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
16320 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
16321 */
16322 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
16323   int rc = SQLITE_OK;
16324   if( p ){
16325     return sqlite3GlobalConfig.mutex.xMutexTry(p);
16326   }
16327   return rc;
16328 }
16329
16330 /*
16331 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
16332 ** entered by the same thread.  The behavior is undefined if the mutex 
16333 ** is not currently entered. If a NULL pointer is passed as an argument
16334 ** this function is a no-op.
16335 */
16336 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
16337   if( p ){
16338     sqlite3GlobalConfig.mutex.xMutexLeave(p);
16339   }
16340 }
16341
16342 #ifndef NDEBUG
16343 /*
16344 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16345 ** intended for use inside assert() statements.
16346 */
16347 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
16348   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
16349 }
16350 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
16351   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
16352 }
16353 #endif
16354
16355 #endif /* SQLITE_MUTEX_OMIT */
16356
16357 /************** End of mutex.c ***********************************************/
16358 /************** Begin file mutex_noop.c **************************************/
16359 /*
16360 ** 2008 October 07
16361 **
16362 ** The author disclaims copyright to this source code.  In place of
16363 ** a legal notice, here is a blessing:
16364 **
16365 **    May you do good and not evil.
16366 **    May you find forgiveness for yourself and forgive others.
16367 **    May you share freely, never taking more than you give.
16368 **
16369 *************************************************************************
16370 ** This file contains the C functions that implement mutexes.
16371 **
16372 ** This implementation in this file does not provide any mutual
16373 ** exclusion and is thus suitable for use only in applications
16374 ** that use SQLite in a single thread.  The routines defined
16375 ** here are place-holders.  Applications can substitute working
16376 ** mutex routines at start-time using the
16377 **
16378 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
16379 **
16380 ** interface.
16381 **
16382 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
16383 ** that does error checking on mutexes to make sure they are being
16384 ** called correctly.
16385 */
16386
16387 #ifndef SQLITE_MUTEX_OMIT
16388
16389 #ifndef SQLITE_DEBUG
16390 /*
16391 ** Stub routines for all mutex methods.
16392 **
16393 ** This routines provide no mutual exclusion or error checking.
16394 */
16395 static int noopMutexInit(void){ return SQLITE_OK; }
16396 static int noopMutexEnd(void){ return SQLITE_OK; }
16397 static sqlite3_mutex *noopMutexAlloc(int id){ 
16398   UNUSED_PARAMETER(id);
16399   return (sqlite3_mutex*)8; 
16400 }
16401 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16402 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16403 static int noopMutexTry(sqlite3_mutex *p){
16404   UNUSED_PARAMETER(p);
16405   return SQLITE_OK;
16406 }
16407 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16408
16409 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
16410   static const sqlite3_mutex_methods sMutex = {
16411     noopMutexInit,
16412     noopMutexEnd,
16413     noopMutexAlloc,
16414     noopMutexFree,
16415     noopMutexEnter,
16416     noopMutexTry,
16417     noopMutexLeave,
16418
16419     0,
16420     0,
16421   };
16422
16423   return &sMutex;
16424 }
16425 #endif /* !SQLITE_DEBUG */
16426
16427 #ifdef SQLITE_DEBUG
16428 /*
16429 ** In this implementation, error checking is provided for testing
16430 ** and debugging purposes.  The mutexes still do not provide any
16431 ** mutual exclusion.
16432 */
16433
16434 /*
16435 ** The mutex object
16436 */
16437 typedef struct sqlite3_debug_mutex {
16438   int id;     /* The mutex type */
16439   int cnt;    /* Number of entries without a matching leave */
16440 } sqlite3_debug_mutex;
16441
16442 /*
16443 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16444 ** intended for use inside assert() statements.
16445 */
16446 static int debugMutexHeld(sqlite3_mutex *pX){
16447   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16448   return p==0 || p->cnt>0;
16449 }
16450 static int debugMutexNotheld(sqlite3_mutex *pX){
16451   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16452   return p==0 || p->cnt==0;
16453 }
16454
16455 /*
16456 ** Initialize and deinitialize the mutex subsystem.
16457 */
16458 static int debugMutexInit(void){ return SQLITE_OK; }
16459 static int debugMutexEnd(void){ return SQLITE_OK; }
16460
16461 /*
16462 ** The sqlite3_mutex_alloc() routine allocates a new
16463 ** mutex and returns a pointer to it.  If it returns NULL
16464 ** that means that a mutex could not be allocated. 
16465 */
16466 static sqlite3_mutex *debugMutexAlloc(int id){
16467   static sqlite3_debug_mutex aStatic[6];
16468   sqlite3_debug_mutex *pNew = 0;
16469   switch( id ){
16470     case SQLITE_MUTEX_FAST:
16471     case SQLITE_MUTEX_RECURSIVE: {
16472       pNew = sqlite3Malloc(sizeof(*pNew));
16473       if( pNew ){
16474         pNew->id = id;
16475         pNew->cnt = 0;
16476       }
16477       break;
16478     }
16479     default: {
16480       assert( id-2 >= 0 );
16481       assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
16482       pNew = &aStatic[id-2];
16483       pNew->id = id;
16484       break;
16485     }
16486   }
16487   return (sqlite3_mutex*)pNew;
16488 }
16489
16490 /*
16491 ** This routine deallocates a previously allocated mutex.
16492 */
16493 static void debugMutexFree(sqlite3_mutex *pX){
16494   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16495   assert( p->cnt==0 );
16496   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16497   sqlite3_free(p);
16498 }
16499
16500 /*
16501 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16502 ** to enter a mutex.  If another thread is already within the mutex,
16503 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16504 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16505 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16506 ** be entered multiple times by the same thread.  In such cases the,
16507 ** mutex must be exited an equal number of times before another thread
16508 ** can enter.  If the same thread tries to enter any other kind of mutex
16509 ** more than once, the behavior is undefined.
16510 */
16511 static void debugMutexEnter(sqlite3_mutex *pX){
16512   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16513   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16514   p->cnt++;
16515 }
16516 static int debugMutexTry(sqlite3_mutex *pX){
16517   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16518   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16519   p->cnt++;
16520   return SQLITE_OK;
16521 }
16522
16523 /*
16524 ** The sqlite3_mutex_leave() routine exits a mutex that was
16525 ** previously entered by the same thread.  The behavior
16526 ** is undefined if the mutex is not currently entered or
16527 ** is not currently allocated.  SQLite will never do either.
16528 */
16529 static void debugMutexLeave(sqlite3_mutex *pX){
16530   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16531   assert( debugMutexHeld(pX) );
16532   p->cnt--;
16533   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16534 }
16535
16536 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
16537   static const sqlite3_mutex_methods sMutex = {
16538     debugMutexInit,
16539     debugMutexEnd,
16540     debugMutexAlloc,
16541     debugMutexFree,
16542     debugMutexEnter,
16543     debugMutexTry,
16544     debugMutexLeave,
16545
16546     debugMutexHeld,
16547     debugMutexNotheld
16548   };
16549
16550   return &sMutex;
16551 }
16552 #endif /* SQLITE_DEBUG */
16553
16554 /*
16555 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
16556 ** is used regardless of the run-time threadsafety setting.
16557 */
16558 #ifdef SQLITE_MUTEX_NOOP
16559 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
16560   return sqlite3NoopMutex();
16561 }
16562 #endif /* SQLITE_MUTEX_NOOP */
16563 #endif /* SQLITE_MUTEX_OMIT */
16564
16565 /************** End of mutex_noop.c ******************************************/
16566 /************** Begin file mutex_os2.c ***************************************/
16567 /*
16568 ** 2007 August 28
16569 **
16570 ** The author disclaims copyright to this source code.  In place of
16571 ** a legal notice, here is a blessing:
16572 **
16573 **    May you do good and not evil.
16574 **    May you find forgiveness for yourself and forgive others.
16575 **    May you share freely, never taking more than you give.
16576 **
16577 *************************************************************************
16578 ** This file contains the C functions that implement mutexes for OS/2
16579 */
16580
16581 /*
16582 ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
16583 ** See the mutex.h file for details.
16584 */
16585 #ifdef SQLITE_MUTEX_OS2
16586
16587 /********************** OS/2 Mutex Implementation **********************
16588 **
16589 ** This implementation of mutexes is built using the OS/2 API.
16590 */
16591
16592 /*
16593 ** The mutex object
16594 ** Each recursive mutex is an instance of the following structure.
16595 */
16596 struct sqlite3_mutex {
16597   HMTX mutex;       /* Mutex controlling the lock */
16598   int  id;          /* Mutex type */
16599   int  nRef;        /* Number of references */
16600   TID  owner;       /* Thread holding this mutex */
16601 };
16602
16603 #define OS2_MUTEX_INITIALIZER   0,0,0,0
16604
16605 /*
16606 ** Initialize and deinitialize the mutex subsystem.
16607 */
16608 static int os2MutexInit(void){ return SQLITE_OK; }
16609 static int os2MutexEnd(void){ return SQLITE_OK; }
16610
16611 /*
16612 ** The sqlite3_mutex_alloc() routine allocates a new
16613 ** mutex and returns a pointer to it.  If it returns NULL
16614 ** that means that a mutex could not be allocated. 
16615 ** SQLite will unwind its stack and return an error.  The argument
16616 ** to sqlite3_mutex_alloc() is one of these integer constants:
16617 **
16618 ** <ul>
16619 ** <li>  SQLITE_MUTEX_FAST               0
16620 ** <li>  SQLITE_MUTEX_RECURSIVE          1
16621 ** <li>  SQLITE_MUTEX_STATIC_MASTER      2
16622 ** <li>  SQLITE_MUTEX_STATIC_MEM         3
16623 ** <li>  SQLITE_MUTEX_STATIC_PRNG        4
16624 ** </ul>
16625 **
16626 ** The first two constants cause sqlite3_mutex_alloc() to create
16627 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
16628 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
16629 ** The mutex implementation does not need to make a distinction
16630 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
16631 ** not want to.  But SQLite will only request a recursive mutex in
16632 ** cases where it really needs one.  If a faster non-recursive mutex
16633 ** implementation is available on the host platform, the mutex subsystem
16634 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
16635 **
16636 ** The other allowed parameters to sqlite3_mutex_alloc() each return
16637 ** a pointer to a static preexisting mutex.  Three static mutexes are
16638 ** used by the current version of SQLite.  Future versions of SQLite
16639 ** may add additional static mutexes.  Static mutexes are for internal
16640 ** use by SQLite only.  Applications that use SQLite mutexes should
16641 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
16642 ** SQLITE_MUTEX_RECURSIVE.
16643 **
16644 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
16645 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
16646 ** returns a different mutex on every call.  But for the static
16647 ** mutex types, the same mutex is returned on every call that has
16648 ** the same type number.
16649 */
16650 static sqlite3_mutex *os2MutexAlloc(int iType){
16651   sqlite3_mutex *p = NULL;
16652   switch( iType ){
16653     case SQLITE_MUTEX_FAST:
16654     case SQLITE_MUTEX_RECURSIVE: {
16655       p = sqlite3MallocZero( sizeof(*p) );
16656       if( p ){
16657         p->id = iType;
16658         if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
16659           sqlite3_free( p );
16660           p = NULL;
16661         }
16662       }
16663       break;
16664     }
16665     default: {
16666       static volatile int isInit = 0;
16667       static sqlite3_mutex staticMutexes[] = {
16668         { OS2_MUTEX_INITIALIZER, },
16669         { OS2_MUTEX_INITIALIZER, },
16670         { OS2_MUTEX_INITIALIZER, },
16671         { OS2_MUTEX_INITIALIZER, },
16672         { OS2_MUTEX_INITIALIZER, },
16673         { OS2_MUTEX_INITIALIZER, },
16674       };
16675       if ( !isInit ){
16676         APIRET rc;
16677         PTIB ptib;
16678         PPIB ppib;
16679         HMTX mutex;
16680         char name[32];
16681         DosGetInfoBlocks( &ptib, &ppib );
16682         sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
16683                           ppib->pib_ulpid );
16684         while( !isInit ){
16685           mutex = 0;
16686           rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
16687           if( rc == NO_ERROR ){
16688             unsigned int i;
16689             if( !isInit ){
16690               for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
16691                 DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
16692               }
16693               isInit = 1;
16694             }
16695             DosCloseMutexSem( mutex );
16696           }else if( rc == ERROR_DUPLICATE_NAME ){
16697             DosSleep( 1 );
16698           }else{
16699             return p;
16700           }
16701         }
16702       }
16703       assert( iType-2 >= 0 );
16704       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
16705       p = &staticMutexes[iType-2];
16706       p->id = iType;
16707       break;
16708     }
16709   }
16710   return p;
16711 }
16712
16713
16714 /*
16715 ** This routine deallocates a previously allocated mutex.
16716 ** SQLite is careful to deallocate every mutex that it allocates.
16717 */
16718 static void os2MutexFree(sqlite3_mutex *p){
16719   if( p==0 ) return;
16720   assert( p->nRef==0 );
16721   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16722   DosCloseMutexSem( p->mutex );
16723   sqlite3_free( p );
16724 }
16725
16726 #ifdef SQLITE_DEBUG
16727 /*
16728 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16729 ** intended for use inside assert() statements.
16730 */
16731 static int os2MutexHeld(sqlite3_mutex *p){
16732   TID tid;
16733   PID pid;
16734   ULONG ulCount;
16735   PTIB ptib;
16736   if( p!=0 ) {
16737     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16738   } else {
16739     DosGetInfoBlocks(&ptib, NULL);
16740     tid = ptib->tib_ptib2->tib2_ultid;
16741   }
16742   return p==0 || (p->nRef!=0 && p->owner==tid);
16743 }
16744 static int os2MutexNotheld(sqlite3_mutex *p){
16745   TID tid;
16746   PID pid;
16747   ULONG ulCount;
16748   PTIB ptib;
16749   if( p!= 0 ) {
16750     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16751   } else {
16752     DosGetInfoBlocks(&ptib, NULL);
16753     tid = ptib->tib_ptib2->tib2_ultid;
16754   }
16755   return p==0 || p->nRef==0 || p->owner!=tid;
16756 }
16757 #endif
16758
16759 /*
16760 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16761 ** to enter a mutex.  If another thread is already within the mutex,
16762 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16763 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16764 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16765 ** be entered multiple times by the same thread.  In such cases the,
16766 ** mutex must be exited an equal number of times before another thread
16767 ** can enter.  If the same thread tries to enter any other kind of mutex
16768 ** more than once, the behavior is undefined.
16769 */
16770 static void os2MutexEnter(sqlite3_mutex *p){
16771   TID tid;
16772   PID holder1;
16773   ULONG holder2;
16774   if( p==0 ) return;
16775   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
16776   DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
16777   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
16778   p->owner = tid;
16779   p->nRef++;
16780 }
16781 static int os2MutexTry(sqlite3_mutex *p){
16782   int rc;
16783   TID tid;
16784   PID holder1;
16785   ULONG holder2;
16786   if( p==0 ) return SQLITE_OK;
16787   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
16788   if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
16789     DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
16790     p->owner = tid;
16791     p->nRef++;
16792     rc = SQLITE_OK;
16793   } else {
16794     rc = SQLITE_BUSY;
16795   }
16796
16797   return rc;
16798 }
16799
16800 /*
16801 ** The sqlite3_mutex_leave() routine exits a mutex that was
16802 ** previously entered by the same thread.  The behavior
16803 ** is undefined if the mutex is not currently entered or
16804 ** is not currently allocated.  SQLite will never do either.
16805 */
16806 static void os2MutexLeave(sqlite3_mutex *p){
16807   TID tid;
16808   PID holder1;
16809   ULONG holder2;
16810   if( p==0 ) return;
16811   assert( p->nRef>0 );
16812   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
16813   assert( p->owner==tid );
16814   p->nRef--;
16815   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
16816   DosReleaseMutexSem(p->mutex);
16817 }
16818
16819 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
16820   static const sqlite3_mutex_methods sMutex = {
16821     os2MutexInit,
16822     os2MutexEnd,
16823     os2MutexAlloc,
16824     os2MutexFree,
16825     os2MutexEnter,
16826     os2MutexTry,
16827     os2MutexLeave,
16828 #ifdef SQLITE_DEBUG
16829     os2MutexHeld,
16830     os2MutexNotheld
16831 #endif
16832   };
16833
16834   return &sMutex;
16835 }
16836 #endif /* SQLITE_MUTEX_OS2 */
16837
16838 /************** End of mutex_os2.c *******************************************/
16839 /************** Begin file mutex_unix.c **************************************/
16840 /*
16841 ** 2007 August 28
16842 **
16843 ** The author disclaims copyright to this source code.  In place of
16844 ** a legal notice, here is a blessing:
16845 **
16846 **    May you do good and not evil.
16847 **    May you find forgiveness for yourself and forgive others.
16848 **    May you share freely, never taking more than you give.
16849 **
16850 *************************************************************************
16851 ** This file contains the C functions that implement mutexes for pthreads
16852 */
16853
16854 /*
16855 ** The code in this file is only used if we are compiling threadsafe
16856 ** under unix with pthreads.
16857 **
16858 ** Note that this implementation requires a version of pthreads that
16859 ** supports recursive mutexes.
16860 */
16861 #ifdef SQLITE_MUTEX_PTHREADS
16862
16863 #include <pthread.h>
16864
16865 /*
16866 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
16867 ** are necessary under two condidtions:  (1) Debug builds and (2) using
16868 ** home-grown mutexes.  Encapsulate these conditions into a single #define.
16869 */
16870 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
16871 # define SQLITE_MUTEX_NREF 1
16872 #else
16873 # define SQLITE_MUTEX_NREF 0
16874 #endif
16875
16876 /*
16877 ** Each recursive mutex is an instance of the following structure.
16878 */
16879 struct sqlite3_mutex {
16880   pthread_mutex_t mutex;     /* Mutex controlling the lock */
16881 #if SQLITE_MUTEX_NREF
16882   int id;                    /* Mutex type */
16883   volatile int nRef;         /* Number of entrances */
16884   volatile pthread_t owner;  /* Thread that is within this mutex */
16885   int trace;                 /* True to trace changes */
16886 #endif
16887 };
16888 #if SQLITE_MUTEX_NREF
16889 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
16890 #else
16891 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
16892 #endif
16893
16894 /*
16895 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16896 ** intended for use only inside assert() statements.  On some platforms,
16897 ** there might be race conditions that can cause these routines to
16898 ** deliver incorrect results.  In particular, if pthread_equal() is
16899 ** not an atomic operation, then these routines might delivery
16900 ** incorrect results.  On most platforms, pthread_equal() is a 
16901 ** comparison of two integers and is therefore atomic.  But we are
16902 ** told that HPUX is not such a platform.  If so, then these routines
16903 ** will not always work correctly on HPUX.
16904 **
16905 ** On those platforms where pthread_equal() is not atomic, SQLite
16906 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
16907 ** make sure no assert() statements are evaluated and hence these
16908 ** routines are never called.
16909 */
16910 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
16911 static int pthreadMutexHeld(sqlite3_mutex *p){
16912   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
16913 }
16914 static int pthreadMutexNotheld(sqlite3_mutex *p){
16915   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
16916 }
16917 #endif
16918
16919 /*
16920 ** Initialize and deinitialize the mutex subsystem.
16921 */
16922 static int pthreadMutexInit(void){ return SQLITE_OK; }
16923 static int pthreadMutexEnd(void){ return SQLITE_OK; }
16924
16925 /*
16926 ** The sqlite3_mutex_alloc() routine allocates a new
16927 ** mutex and returns a pointer to it.  If it returns NULL
16928 ** that means that a mutex could not be allocated.  SQLite
16929 ** will unwind its stack and return an error.  The argument
16930 ** to sqlite3_mutex_alloc() is one of these integer constants:
16931 **
16932 ** <ul>
16933 ** <li>  SQLITE_MUTEX_FAST
16934 ** <li>  SQLITE_MUTEX_RECURSIVE
16935 ** <li>  SQLITE_MUTEX_STATIC_MASTER
16936 ** <li>  SQLITE_MUTEX_STATIC_MEM
16937 ** <li>  SQLITE_MUTEX_STATIC_MEM2
16938 ** <li>  SQLITE_MUTEX_STATIC_PRNG
16939 ** <li>  SQLITE_MUTEX_STATIC_LRU
16940 ** <li>  SQLITE_MUTEX_STATIC_PMEM
16941 ** </ul>
16942 **
16943 ** The first two constants cause sqlite3_mutex_alloc() to create
16944 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
16945 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
16946 ** The mutex implementation does not need to make a distinction
16947 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
16948 ** not want to.  But SQLite will only request a recursive mutex in
16949 ** cases where it really needs one.  If a faster non-recursive mutex
16950 ** implementation is available on the host platform, the mutex subsystem
16951 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
16952 **
16953 ** The other allowed parameters to sqlite3_mutex_alloc() each return
16954 ** a pointer to a static preexisting mutex.  Six static mutexes are
16955 ** used by the current version of SQLite.  Future versions of SQLite
16956 ** may add additional static mutexes.  Static mutexes are for internal
16957 ** use by SQLite only.  Applications that use SQLite mutexes should
16958 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
16959 ** SQLITE_MUTEX_RECURSIVE.
16960 **
16961 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
16962 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
16963 ** returns a different mutex on every call.  But for the static 
16964 ** mutex types, the same mutex is returned on every call that has
16965 ** the same type number.
16966 */
16967 static sqlite3_mutex *pthreadMutexAlloc(int iType){
16968   static sqlite3_mutex staticMutexes[] = {
16969     SQLITE3_MUTEX_INITIALIZER,
16970     SQLITE3_MUTEX_INITIALIZER,
16971     SQLITE3_MUTEX_INITIALIZER,
16972     SQLITE3_MUTEX_INITIALIZER,
16973     SQLITE3_MUTEX_INITIALIZER,
16974     SQLITE3_MUTEX_INITIALIZER
16975   };
16976   sqlite3_mutex *p;
16977   switch( iType ){
16978     case SQLITE_MUTEX_RECURSIVE: {
16979       p = sqlite3MallocZero( sizeof(*p) );
16980       if( p ){
16981 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
16982         /* If recursive mutexes are not available, we will have to
16983         ** build our own.  See below. */
16984         pthread_mutex_init(&p->mutex, 0);
16985 #else
16986         /* Use a recursive mutex if it is available */
16987         pthread_mutexattr_t recursiveAttr;
16988         pthread_mutexattr_init(&recursiveAttr);
16989         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
16990         pthread_mutex_init(&p->mutex, &recursiveAttr);
16991         pthread_mutexattr_destroy(&recursiveAttr);
16992 #endif
16993 #if SQLITE_MUTEX_NREF
16994         p->id = iType;
16995 #endif
16996       }
16997       break;
16998     }
16999     case SQLITE_MUTEX_FAST: {
17000       p = sqlite3MallocZero( sizeof(*p) );
17001       if( p ){
17002 #if SQLITE_MUTEX_NREF
17003         p->id = iType;
17004 #endif
17005         pthread_mutex_init(&p->mutex, 0);
17006       }
17007       break;
17008     }
17009     default: {
17010       assert( iType-2 >= 0 );
17011       assert( iType-2 < ArraySize(staticMutexes) );
17012       p = &staticMutexes[iType-2];
17013 #if SQLITE_MUTEX_NREF
17014       p->id = iType;
17015 #endif
17016       break;
17017     }
17018   }
17019   return p;
17020 }
17021
17022
17023 /*
17024 ** This routine deallocates a previously
17025 ** allocated mutex.  SQLite is careful to deallocate every
17026 ** mutex that it allocates.
17027 */
17028 static void pthreadMutexFree(sqlite3_mutex *p){
17029   assert( p->nRef==0 );
17030   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17031   pthread_mutex_destroy(&p->mutex);
17032   sqlite3_free(p);
17033 }
17034
17035 /*
17036 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17037 ** to enter a mutex.  If another thread is already within the mutex,
17038 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17039 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17040 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17041 ** be entered multiple times by the same thread.  In such cases the,
17042 ** mutex must be exited an equal number of times before another thread
17043 ** can enter.  If the same thread tries to enter any other kind of mutex
17044 ** more than once, the behavior is undefined.
17045 */
17046 static void pthreadMutexEnter(sqlite3_mutex *p){
17047   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
17048
17049 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17050   /* If recursive mutexes are not available, then we have to grow
17051   ** our own.  This implementation assumes that pthread_equal()
17052   ** is atomic - that it cannot be deceived into thinking self
17053   ** and p->owner are equal if p->owner changes between two values
17054   ** that are not equal to self while the comparison is taking place.
17055   ** This implementation also assumes a coherent cache - that 
17056   ** separate processes cannot read different values from the same
17057   ** address at the same time.  If either of these two conditions
17058   ** are not met, then the mutexes will fail and problems will result.
17059   */
17060   {
17061     pthread_t self = pthread_self();
17062     if( p->nRef>0 && pthread_equal(p->owner, self) ){
17063       p->nRef++;
17064     }else{
17065       pthread_mutex_lock(&p->mutex);
17066       assert( p->nRef==0 );
17067       p->owner = self;
17068       p->nRef = 1;
17069     }
17070   }
17071 #else
17072   /* Use the built-in recursive mutexes if they are available.
17073   */
17074   pthread_mutex_lock(&p->mutex);
17075 #if SQLITE_MUTEX_NREF
17076   assert( p->nRef>0 || p->owner==0 );
17077   p->owner = pthread_self();
17078   p->nRef++;
17079 #endif
17080 #endif
17081
17082 #ifdef SQLITE_DEBUG
17083   if( p->trace ){
17084     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17085   }
17086 #endif
17087 }
17088 static int pthreadMutexTry(sqlite3_mutex *p){
17089   int rc;
17090   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
17091
17092 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17093   /* If recursive mutexes are not available, then we have to grow
17094   ** our own.  This implementation assumes that pthread_equal()
17095   ** is atomic - that it cannot be deceived into thinking self
17096   ** and p->owner are equal if p->owner changes between two values
17097   ** that are not equal to self while the comparison is taking place.
17098   ** This implementation also assumes a coherent cache - that 
17099   ** separate processes cannot read different values from the same
17100   ** address at the same time.  If either of these two conditions
17101   ** are not met, then the mutexes will fail and problems will result.
17102   */
17103   {
17104     pthread_t self = pthread_self();
17105     if( p->nRef>0 && pthread_equal(p->owner, self) ){
17106       p->nRef++;
17107       rc = SQLITE_OK;
17108     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
17109       assert( p->nRef==0 );
17110       p->owner = self;
17111       p->nRef = 1;
17112       rc = SQLITE_OK;
17113     }else{
17114       rc = SQLITE_BUSY;
17115     }
17116   }
17117 #else
17118   /* Use the built-in recursive mutexes if they are available.
17119   */
17120   if( pthread_mutex_trylock(&p->mutex)==0 ){
17121 #if SQLITE_MUTEX_NREF
17122     p->owner = pthread_self();
17123     p->nRef++;
17124 #endif
17125     rc = SQLITE_OK;
17126   }else{
17127     rc = SQLITE_BUSY;
17128   }
17129 #endif
17130
17131 #ifdef SQLITE_DEBUG
17132   if( rc==SQLITE_OK && p->trace ){
17133     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17134   }
17135 #endif
17136   return rc;
17137 }
17138
17139 /*
17140 ** The sqlite3_mutex_leave() routine exits a mutex that was
17141 ** previously entered by the same thread.  The behavior
17142 ** is undefined if the mutex is not currently entered or
17143 ** is not currently allocated.  SQLite will never do either.
17144 */
17145 static void pthreadMutexLeave(sqlite3_mutex *p){
17146   assert( pthreadMutexHeld(p) );
17147 #if SQLITE_MUTEX_NREF
17148   p->nRef--;
17149   if( p->nRef==0 ) p->owner = 0;
17150 #endif
17151   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
17152
17153 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17154   if( p->nRef==0 ){
17155     pthread_mutex_unlock(&p->mutex);
17156   }
17157 #else
17158   pthread_mutex_unlock(&p->mutex);
17159 #endif
17160
17161 #ifdef SQLITE_DEBUG
17162   if( p->trace ){
17163     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17164   }
17165 #endif
17166 }
17167
17168 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17169   static const sqlite3_mutex_methods sMutex = {
17170     pthreadMutexInit,
17171     pthreadMutexEnd,
17172     pthreadMutexAlloc,
17173     pthreadMutexFree,
17174     pthreadMutexEnter,
17175     pthreadMutexTry,
17176     pthreadMutexLeave,
17177 #ifdef SQLITE_DEBUG
17178     pthreadMutexHeld,
17179     pthreadMutexNotheld
17180 #else
17181     0,
17182     0
17183 #endif
17184   };
17185
17186   return &sMutex;
17187 }
17188
17189 #endif /* SQLITE_MUTEX_PTHREAD */
17190
17191 /************** End of mutex_unix.c ******************************************/
17192 /************** Begin file mutex_w32.c ***************************************/
17193 /*
17194 ** 2007 August 14
17195 **
17196 ** The author disclaims copyright to this source code.  In place of
17197 ** a legal notice, here is a blessing:
17198 **
17199 **    May you do good and not evil.
17200 **    May you find forgiveness for yourself and forgive others.
17201 **    May you share freely, never taking more than you give.
17202 **
17203 *************************************************************************
17204 ** This file contains the C functions that implement mutexes for win32
17205 */
17206
17207 /*
17208 ** The code in this file is only used if we are compiling multithreaded
17209 ** on a win32 system.
17210 */
17211 #ifdef SQLITE_MUTEX_W32
17212
17213 /*
17214 ** Each recursive mutex is an instance of the following structure.
17215 */
17216 struct sqlite3_mutex {
17217   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
17218   int id;                    /* Mutex type */
17219 #ifdef SQLITE_DEBUG
17220   volatile int nRef;         /* Number of enterances */
17221   volatile DWORD owner;      /* Thread holding this mutex */
17222   int trace;                 /* True to trace changes */
17223 #endif
17224 };
17225 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
17226 #ifdef SQLITE_DEBUG
17227 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
17228 #else
17229 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
17230 #endif
17231
17232 /*
17233 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
17234 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
17235 **
17236 ** Here is an interesting observation:  Win95, Win98, and WinME lack
17237 ** the LockFileEx() API.  But we can still statically link against that
17238 ** API as long as we don't call it win running Win95/98/ME.  A call to
17239 ** this routine is used to determine if the host is Win95/98/ME or
17240 ** WinNT/2K/XP so that we will know whether or not we can safely call
17241 ** the LockFileEx() API.
17242 **
17243 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
17244 ** which is only available if your application was compiled with 
17245 ** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
17246 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef 
17247 ** this out as well.
17248 */
17249 #if 0
17250 #if SQLITE_OS_WINCE
17251 # define mutexIsNT()  (1)
17252 #else
17253   static int mutexIsNT(void){
17254     static int osType = 0;
17255     if( osType==0 ){
17256       OSVERSIONINFO sInfo;
17257       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
17258       GetVersionEx(&sInfo);
17259       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
17260     }
17261     return osType==2;
17262   }
17263 #endif /* SQLITE_OS_WINCE */
17264 #endif
17265
17266 #ifdef SQLITE_DEBUG
17267 /*
17268 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17269 ** intended for use only inside assert() statements.
17270 */
17271 static int winMutexHeld(sqlite3_mutex *p){
17272   return p->nRef!=0 && p->owner==GetCurrentThreadId();
17273 }
17274 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
17275   return p->nRef==0 || p->owner!=tid;
17276 }
17277 static int winMutexNotheld(sqlite3_mutex *p){
17278   DWORD tid = GetCurrentThreadId(); 
17279   return winMutexNotheld2(p, tid);
17280 }
17281 #endif
17282
17283
17284 /*
17285 ** Initialize and deinitialize the mutex subsystem.
17286 */
17287 static sqlite3_mutex winMutex_staticMutexes[6] = {
17288   SQLITE3_MUTEX_INITIALIZER,
17289   SQLITE3_MUTEX_INITIALIZER,
17290   SQLITE3_MUTEX_INITIALIZER,
17291   SQLITE3_MUTEX_INITIALIZER,
17292   SQLITE3_MUTEX_INITIALIZER,
17293   SQLITE3_MUTEX_INITIALIZER
17294 };
17295 static int winMutex_isInit = 0;
17296 /* As winMutexInit() and winMutexEnd() are called as part
17297 ** of the sqlite3_initialize and sqlite3_shutdown()
17298 ** processing, the "interlocked" magic is probably not
17299 ** strictly necessary.
17300 */
17301 static long winMutex_lock = 0;
17302
17303 static int winMutexInit(void){ 
17304   /* The first to increment to 1 does actual initialization */
17305   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
17306     int i;
17307     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
17308       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
17309     }
17310     winMutex_isInit = 1;
17311   }else{
17312     /* Someone else is in the process of initing the static mutexes */
17313     while( !winMutex_isInit ){
17314       Sleep(1);
17315     }
17316   }
17317   return SQLITE_OK; 
17318 }
17319
17320 static int winMutexEnd(void){ 
17321   /* The first to decrement to 0 does actual shutdown 
17322   ** (which should be the last to shutdown.) */
17323   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
17324     if( winMutex_isInit==1 ){
17325       int i;
17326       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
17327         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
17328       }
17329       winMutex_isInit = 0;
17330     }
17331   }
17332   return SQLITE_OK; 
17333 }
17334
17335 /*
17336 ** The sqlite3_mutex_alloc() routine allocates a new
17337 ** mutex and returns a pointer to it.  If it returns NULL
17338 ** that means that a mutex could not be allocated.  SQLite
17339 ** will unwind its stack and return an error.  The argument
17340 ** to sqlite3_mutex_alloc() is one of these integer constants:
17341 **
17342 ** <ul>
17343 ** <li>  SQLITE_MUTEX_FAST
17344 ** <li>  SQLITE_MUTEX_RECURSIVE
17345 ** <li>  SQLITE_MUTEX_STATIC_MASTER
17346 ** <li>  SQLITE_MUTEX_STATIC_MEM
17347 ** <li>  SQLITE_MUTEX_STATIC_MEM2
17348 ** <li>  SQLITE_MUTEX_STATIC_PRNG
17349 ** <li>  SQLITE_MUTEX_STATIC_LRU
17350 ** <li>  SQLITE_MUTEX_STATIC_PMEM
17351 ** </ul>
17352 **
17353 ** The first two constants cause sqlite3_mutex_alloc() to create
17354 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
17355 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
17356 ** The mutex implementation does not need to make a distinction
17357 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
17358 ** not want to.  But SQLite will only request a recursive mutex in
17359 ** cases where it really needs one.  If a faster non-recursive mutex
17360 ** implementation is available on the host platform, the mutex subsystem
17361 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
17362 **
17363 ** The other allowed parameters to sqlite3_mutex_alloc() each return
17364 ** a pointer to a static preexisting mutex.  Six static mutexes are
17365 ** used by the current version of SQLite.  Future versions of SQLite
17366 ** may add additional static mutexes.  Static mutexes are for internal
17367 ** use by SQLite only.  Applications that use SQLite mutexes should
17368 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
17369 ** SQLITE_MUTEX_RECURSIVE.
17370 **
17371 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
17372 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
17373 ** returns a different mutex on every call.  But for the static 
17374 ** mutex types, the same mutex is returned on every call that has
17375 ** the same type number.
17376 */
17377 static sqlite3_mutex *winMutexAlloc(int iType){
17378   sqlite3_mutex *p;
17379
17380   switch( iType ){
17381     case SQLITE_MUTEX_FAST:
17382     case SQLITE_MUTEX_RECURSIVE: {
17383       p = sqlite3MallocZero( sizeof(*p) );
17384       if( p ){  
17385 #ifdef SQLITE_DEBUG
17386         p->id = iType;
17387 #endif
17388         InitializeCriticalSection(&p->mutex);
17389       }
17390       break;
17391     }
17392     default: {
17393       assert( winMutex_isInit==1 );
17394       assert( iType-2 >= 0 );
17395       assert( iType-2 < ArraySize(winMutex_staticMutexes) );
17396       p = &winMutex_staticMutexes[iType-2];
17397 #ifdef SQLITE_DEBUG
17398       p->id = iType;
17399 #endif
17400       break;
17401     }
17402   }
17403   return p;
17404 }
17405
17406
17407 /*
17408 ** This routine deallocates a previously
17409 ** allocated mutex.  SQLite is careful to deallocate every
17410 ** mutex that it allocates.
17411 */
17412 static void winMutexFree(sqlite3_mutex *p){
17413   assert( p );
17414   assert( p->nRef==0 && p->owner==0 );
17415   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17416   DeleteCriticalSection(&p->mutex);
17417   sqlite3_free(p);
17418 }
17419
17420 /*
17421 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17422 ** to enter a mutex.  If another thread is already within the mutex,
17423 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17424 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17425 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17426 ** be entered multiple times by the same thread.  In such cases the,
17427 ** mutex must be exited an equal number of times before another thread
17428 ** can enter.  If the same thread tries to enter any other kind of mutex
17429 ** more than once, the behavior is undefined.
17430 */
17431 static void winMutexEnter(sqlite3_mutex *p){
17432 #ifdef SQLITE_DEBUG
17433   DWORD tid = GetCurrentThreadId(); 
17434   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
17435 #endif
17436   EnterCriticalSection(&p->mutex);
17437 #ifdef SQLITE_DEBUG
17438   assert( p->nRef>0 || p->owner==0 );
17439   p->owner = tid; 
17440   p->nRef++;
17441   if( p->trace ){
17442     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17443   }
17444 #endif
17445 }
17446 static int winMutexTry(sqlite3_mutex *p){
17447 #ifndef NDEBUG
17448   DWORD tid = GetCurrentThreadId(); 
17449 #endif
17450   int rc = SQLITE_BUSY;
17451   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
17452   /*
17453   ** The sqlite3_mutex_try() routine is very rarely used, and when it
17454   ** is used it is merely an optimization.  So it is OK for it to always
17455   ** fail.  
17456   **
17457   ** The TryEnterCriticalSection() interface is only available on WinNT.
17458   ** And some windows compilers complain if you try to use it without
17459   ** first doing some #defines that prevent SQLite from building on Win98.
17460   ** For that reason, we will omit this optimization for now.  See
17461   ** ticket #2685.
17462   */
17463 #if 0
17464   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
17465     p->owner = tid;
17466     p->nRef++;
17467     rc = SQLITE_OK;
17468   }
17469 #else
17470   UNUSED_PARAMETER(p);
17471 #endif
17472 #ifdef SQLITE_DEBUG
17473   if( rc==SQLITE_OK && p->trace ){
17474     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17475   }
17476 #endif
17477   return rc;
17478 }
17479
17480 /*
17481 ** The sqlite3_mutex_leave() routine exits a mutex that was
17482 ** previously entered by the same thread.  The behavior
17483 ** is undefined if the mutex is not currently entered or
17484 ** is not currently allocated.  SQLite will never do either.
17485 */
17486 static void winMutexLeave(sqlite3_mutex *p){
17487 #ifndef NDEBUG
17488   DWORD tid = GetCurrentThreadId();
17489   assert( p->nRef>0 );
17490   assert( p->owner==tid );
17491   p->nRef--;
17492   if( p->nRef==0 ) p->owner = 0;
17493   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
17494 #endif
17495   LeaveCriticalSection(&p->mutex);
17496 #ifdef SQLITE_DEBUG
17497   if( p->trace ){
17498     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17499   }
17500 #endif
17501 }
17502
17503 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17504   static const sqlite3_mutex_methods sMutex = {
17505     winMutexInit,
17506     winMutexEnd,
17507     winMutexAlloc,
17508     winMutexFree,
17509     winMutexEnter,
17510     winMutexTry,
17511     winMutexLeave,
17512 #ifdef SQLITE_DEBUG
17513     winMutexHeld,
17514     winMutexNotheld
17515 #else
17516     0,
17517     0
17518 #endif
17519   };
17520
17521   return &sMutex;
17522 }
17523 #endif /* SQLITE_MUTEX_W32 */
17524
17525 /************** End of mutex_w32.c *******************************************/
17526 /************** Begin file malloc.c ******************************************/
17527 /*
17528 ** 2001 September 15
17529 **
17530 ** The author disclaims copyright to this source code.  In place of
17531 ** a legal notice, here is a blessing:
17532 **
17533 **    May you do good and not evil.
17534 **    May you find forgiveness for yourself and forgive others.
17535 **    May you share freely, never taking more than you give.
17536 **
17537 *************************************************************************
17538 **
17539 ** Memory allocation functions used throughout sqlite.
17540 */
17541
17542 /*
17543 ** Attempt to release up to n bytes of non-essential memory currently
17544 ** held by SQLite. An example of non-essential memory is memory used to
17545 ** cache database pages that are not currently in use.
17546 */
17547 SQLITE_API int sqlite3_release_memory(int n){
17548 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17549   return sqlite3PcacheReleaseMemory(n);
17550 #else
17551   /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
17552   ** is a no-op returning zero if SQLite is not compiled with
17553   ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
17554   UNUSED_PARAMETER(n);
17555   return 0;
17556 #endif
17557 }
17558
17559 /*
17560 ** An instance of the following object records the location of
17561 ** each unused scratch buffer.
17562 */
17563 typedef struct ScratchFreeslot {
17564   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
17565 } ScratchFreeslot;
17566
17567 /*
17568 ** State information local to the memory allocation subsystem.
17569 */
17570 static SQLITE_WSD struct Mem0Global {
17571   sqlite3_mutex *mutex;         /* Mutex to serialize access */
17572
17573   /*
17574   ** The alarm callback and its arguments.  The mem0.mutex lock will
17575   ** be held while the callback is running.  Recursive calls into
17576   ** the memory subsystem are allowed, but no new callbacks will be
17577   ** issued.
17578   */
17579   sqlite3_int64 alarmThreshold;
17580   void (*alarmCallback)(void*, sqlite3_int64,int);
17581   void *alarmArg;
17582
17583   /*
17584   ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
17585   ** (so that a range test can be used to determine if an allocation
17586   ** being freed came from pScratch) and a pointer to the list of
17587   ** unused scratch allocations.
17588   */
17589   void *pScratchEnd;
17590   ScratchFreeslot *pScratchFree;
17591   u32 nScratchFree;
17592
17593   /*
17594   ** True if heap is nearly "full" where "full" is defined by the
17595   ** sqlite3_soft_heap_limit() setting.
17596   */
17597   int nearlyFull;
17598 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
17599
17600 #define mem0 GLOBAL(struct Mem0Global, mem0)
17601
17602 /*
17603 ** This routine runs when the memory allocator sees that the
17604 ** total memory allocation is about to exceed the soft heap
17605 ** limit.
17606 */
17607 static void softHeapLimitEnforcer(
17608   void *NotUsed, 
17609   sqlite3_int64 NotUsed2,
17610   int allocSize
17611 ){
17612   UNUSED_PARAMETER2(NotUsed, NotUsed2);
17613   sqlite3_release_memory(allocSize);
17614 }
17615
17616 /*
17617 ** Change the alarm callback
17618 */
17619 static int sqlite3MemoryAlarm(
17620   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17621   void *pArg,
17622   sqlite3_int64 iThreshold
17623 ){
17624   int nUsed;
17625   sqlite3_mutex_enter(mem0.mutex);
17626   mem0.alarmCallback = xCallback;
17627   mem0.alarmArg = pArg;
17628   mem0.alarmThreshold = iThreshold;
17629   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17630   mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
17631   sqlite3_mutex_leave(mem0.mutex);
17632   return SQLITE_OK;
17633 }
17634
17635 #ifndef SQLITE_OMIT_DEPRECATED
17636 /*
17637 ** Deprecated external interface.  Internal/core SQLite code
17638 ** should call sqlite3MemoryAlarm.
17639 */
17640 SQLITE_API int sqlite3_memory_alarm(
17641   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17642   void *pArg,
17643   sqlite3_int64 iThreshold
17644 ){
17645   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
17646 }
17647 #endif
17648
17649 /*
17650 ** Set the soft heap-size limit for the library. Passing a zero or 
17651 ** negative value indicates no limit.
17652 */
17653 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
17654   sqlite3_int64 priorLimit;
17655   sqlite3_int64 excess;
17656 #ifndef SQLITE_OMIT_AUTOINIT
17657   sqlite3_initialize();
17658 #endif
17659   sqlite3_mutex_enter(mem0.mutex);
17660   priorLimit = mem0.alarmThreshold;
17661   sqlite3_mutex_leave(mem0.mutex);
17662   if( n<0 ) return priorLimit;
17663   if( n>0 ){
17664     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
17665   }else{
17666     sqlite3MemoryAlarm(0, 0, 0);
17667   }
17668   excess = sqlite3_memory_used() - n;
17669   if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
17670   return priorLimit;
17671 }
17672 SQLITE_API void sqlite3_soft_heap_limit(int n){
17673   if( n<0 ) n = 0;
17674   sqlite3_soft_heap_limit64(n);
17675 }
17676
17677 /*
17678 ** Initialize the memory allocation subsystem.
17679 */
17680 SQLITE_PRIVATE int sqlite3MallocInit(void){
17681   if( sqlite3GlobalConfig.m.xMalloc==0 ){
17682     sqlite3MemSetDefault();
17683   }
17684   memset(&mem0, 0, sizeof(mem0));
17685   if( sqlite3GlobalConfig.bCoreMutex ){
17686     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17687   }
17688   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
17689       && sqlite3GlobalConfig.nScratch>0 ){
17690     int i, n, sz;
17691     ScratchFreeslot *pSlot;
17692     sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
17693     sqlite3GlobalConfig.szScratch = sz;
17694     pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
17695     n = sqlite3GlobalConfig.nScratch;
17696     mem0.pScratchFree = pSlot;
17697     mem0.nScratchFree = n;
17698     for(i=0; i<n-1; i++){
17699       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
17700       pSlot = pSlot->pNext;
17701     }
17702     pSlot->pNext = 0;
17703     mem0.pScratchEnd = (void*)&pSlot[1];
17704   }else{
17705     mem0.pScratchEnd = 0;
17706     sqlite3GlobalConfig.pScratch = 0;
17707     sqlite3GlobalConfig.szScratch = 0;
17708     sqlite3GlobalConfig.nScratch = 0;
17709   }
17710   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
17711       || sqlite3GlobalConfig.nPage<1 ){
17712     sqlite3GlobalConfig.pPage = 0;
17713     sqlite3GlobalConfig.szPage = 0;
17714     sqlite3GlobalConfig.nPage = 0;
17715   }
17716   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
17717 }
17718
17719 /*
17720 ** Return true if the heap is currently under memory pressure - in other
17721 ** words if the amount of heap used is close to the limit set by
17722 ** sqlite3_soft_heap_limit().
17723 */
17724 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
17725   return mem0.nearlyFull;
17726 }
17727
17728 /*
17729 ** Deinitialize the memory allocation subsystem.
17730 */
17731 SQLITE_PRIVATE void sqlite3MallocEnd(void){
17732   if( sqlite3GlobalConfig.m.xShutdown ){
17733     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
17734   }
17735   memset(&mem0, 0, sizeof(mem0));
17736 }
17737
17738 /*
17739 ** Return the amount of memory currently checked out.
17740 */
17741 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
17742   int n, mx;
17743   sqlite3_int64 res;
17744   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
17745   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
17746   return res;
17747 }
17748
17749 /*
17750 ** Return the maximum amount of memory that has ever been
17751 ** checked out since either the beginning of this process
17752 ** or since the most recent reset.
17753 */
17754 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
17755   int n, mx;
17756   sqlite3_int64 res;
17757   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
17758   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
17759   return res;
17760 }
17761
17762 /*
17763 ** Trigger the alarm 
17764 */
17765 static void sqlite3MallocAlarm(int nByte){
17766   void (*xCallback)(void*,sqlite3_int64,int);
17767   sqlite3_int64 nowUsed;
17768   void *pArg;
17769   if( mem0.alarmCallback==0 ) return;
17770   xCallback = mem0.alarmCallback;
17771   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17772   pArg = mem0.alarmArg;
17773   mem0.alarmCallback = 0;
17774   sqlite3_mutex_leave(mem0.mutex);
17775   xCallback(pArg, nowUsed, nByte);
17776   sqlite3_mutex_enter(mem0.mutex);
17777   mem0.alarmCallback = xCallback;
17778   mem0.alarmArg = pArg;
17779 }
17780
17781 /*
17782 ** Do a memory allocation with statistics and alarms.  Assume the
17783 ** lock is already held.
17784 */
17785 static int mallocWithAlarm(int n, void **pp){
17786   int nFull;
17787   void *p;
17788   assert( sqlite3_mutex_held(mem0.mutex) );
17789   nFull = sqlite3GlobalConfig.m.xRoundup(n);
17790   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
17791   if( mem0.alarmCallback!=0 ){
17792     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17793     if( nUsed+nFull >= mem0.alarmThreshold ){
17794       mem0.nearlyFull = 1;
17795       sqlite3MallocAlarm(nFull);
17796     }else{
17797       mem0.nearlyFull = 0;
17798     }
17799   }
17800   p = sqlite3GlobalConfig.m.xMalloc(nFull);
17801 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17802   if( p==0 && mem0.alarmCallback ){
17803     sqlite3MallocAlarm(nFull);
17804     p = sqlite3GlobalConfig.m.xMalloc(nFull);
17805   }
17806 #endif
17807   if( p ){
17808     nFull = sqlite3MallocSize(p);
17809     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
17810     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
17811   }
17812   *pp = p;
17813   return nFull;
17814 }
17815
17816 /*
17817 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
17818 ** assumes the memory subsystem has already been initialized.
17819 */
17820 SQLITE_PRIVATE void *sqlite3Malloc(int n){
17821   void *p;
17822   if( n<=0               /* IMP: R-65312-04917 */ 
17823    || n>=0x7fffff00
17824   ){
17825     /* A memory allocation of a number of bytes which is near the maximum
17826     ** signed integer value might cause an integer overflow inside of the
17827     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
17828     ** 255 bytes of overhead.  SQLite itself will never use anything near
17829     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
17830     p = 0;
17831   }else if( sqlite3GlobalConfig.bMemstat ){
17832     sqlite3_mutex_enter(mem0.mutex);
17833     mallocWithAlarm(n, &p);
17834     sqlite3_mutex_leave(mem0.mutex);
17835   }else{
17836     p = sqlite3GlobalConfig.m.xMalloc(n);
17837   }
17838   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
17839   return p;
17840 }
17841
17842 /*
17843 ** This version of the memory allocation is for use by the application.
17844 ** First make sure the memory subsystem is initialized, then do the
17845 ** allocation.
17846 */
17847 SQLITE_API void *sqlite3_malloc(int n){
17848 #ifndef SQLITE_OMIT_AUTOINIT
17849   if( sqlite3_initialize() ) return 0;
17850 #endif
17851   return sqlite3Malloc(n);
17852 }
17853
17854 /*
17855 ** Each thread may only have a single outstanding allocation from
17856 ** xScratchMalloc().  We verify this constraint in the single-threaded
17857 ** case by setting scratchAllocOut to 1 when an allocation
17858 ** is outstanding clearing it when the allocation is freed.
17859 */
17860 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17861 static int scratchAllocOut = 0;
17862 #endif
17863
17864
17865 /*
17866 ** Allocate memory that is to be used and released right away.
17867 ** This routine is similar to alloca() in that it is not intended
17868 ** for situations where the memory might be held long-term.  This
17869 ** routine is intended to get memory to old large transient data
17870 ** structures that would not normally fit on the stack of an
17871 ** embedded processor.
17872 */
17873 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
17874   void *p;
17875   assert( n>0 );
17876
17877   sqlite3_mutex_enter(mem0.mutex);
17878   if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
17879     p = mem0.pScratchFree;
17880     mem0.pScratchFree = mem0.pScratchFree->pNext;
17881     mem0.nScratchFree--;
17882     sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
17883     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
17884     sqlite3_mutex_leave(mem0.mutex);
17885   }else{
17886     if( sqlite3GlobalConfig.bMemstat ){
17887       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
17888       n = mallocWithAlarm(n, &p);
17889       if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
17890       sqlite3_mutex_leave(mem0.mutex);
17891     }else{
17892       sqlite3_mutex_leave(mem0.mutex);
17893       p = sqlite3GlobalConfig.m.xMalloc(n);
17894     }
17895     sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
17896   }
17897   assert( sqlite3_mutex_notheld(mem0.mutex) );
17898
17899
17900 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17901   /* Verify that no more than two scratch allocations per thread
17902   ** are outstanding at one time.  (This is only checked in the
17903   ** single-threaded case since checking in the multi-threaded case
17904   ** would be much more complicated.) */
17905   assert( scratchAllocOut<=1 );
17906   if( p ) scratchAllocOut++;
17907 #endif
17908
17909   return p;
17910 }
17911 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
17912   if( p ){
17913
17914 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17915     /* Verify that no more than two scratch allocation per thread
17916     ** is outstanding at one time.  (This is only checked in the
17917     ** single-threaded case since checking in the multi-threaded case
17918     ** would be much more complicated.) */
17919     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
17920     scratchAllocOut--;
17921 #endif
17922
17923     if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
17924       /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
17925       ScratchFreeslot *pSlot;
17926       pSlot = (ScratchFreeslot*)p;
17927       sqlite3_mutex_enter(mem0.mutex);
17928       pSlot->pNext = mem0.pScratchFree;
17929       mem0.pScratchFree = pSlot;
17930       mem0.nScratchFree++;
17931       assert( mem0.nScratchFree<=sqlite3GlobalConfig.nScratch );
17932       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
17933       sqlite3_mutex_leave(mem0.mutex);
17934     }else{
17935       /* Release memory back to the heap */
17936       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
17937       assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
17938       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
17939       if( sqlite3GlobalConfig.bMemstat ){
17940         int iSize = sqlite3MallocSize(p);
17941         sqlite3_mutex_enter(mem0.mutex);
17942         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
17943         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
17944         sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
17945         sqlite3GlobalConfig.m.xFree(p);
17946         sqlite3_mutex_leave(mem0.mutex);
17947       }else{
17948         sqlite3GlobalConfig.m.xFree(p);
17949       }
17950     }
17951   }
17952 }
17953
17954 /*
17955 ** TRUE if p is a lookaside memory allocation from db
17956 */
17957 #ifndef SQLITE_OMIT_LOOKASIDE
17958 static int isLookaside(sqlite3 *db, void *p){
17959   return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
17960 }
17961 #else
17962 #define isLookaside(A,B) 0
17963 #endif
17964
17965 /*
17966 ** Return the size of a memory allocation previously obtained from
17967 ** sqlite3Malloc() or sqlite3_malloc().
17968 */
17969 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
17970   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
17971   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
17972   return sqlite3GlobalConfig.m.xSize(p);
17973 }
17974 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
17975   assert( db==0 || sqlite3_mutex_held(db->mutex) );
17976   if( db && isLookaside(db, p) ){
17977     return db->lookaside.sz;
17978   }else{
17979     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
17980     assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
17981     assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
17982     return sqlite3GlobalConfig.m.xSize(p);
17983   }
17984 }
17985
17986 /*
17987 ** Free memory previously obtained from sqlite3Malloc().
17988 */
17989 SQLITE_API void sqlite3_free(void *p){
17990   if( p==0 ) return;  /* IMP: R-49053-54554 */
17991   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
17992   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
17993   if( sqlite3GlobalConfig.bMemstat ){
17994     sqlite3_mutex_enter(mem0.mutex);
17995     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
17996     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
17997     sqlite3GlobalConfig.m.xFree(p);
17998     sqlite3_mutex_leave(mem0.mutex);
17999   }else{
18000     sqlite3GlobalConfig.m.xFree(p);
18001   }
18002 }
18003
18004 /*
18005 ** Free memory that might be associated with a particular database
18006 ** connection.
18007 */
18008 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
18009   assert( db==0 || sqlite3_mutex_held(db->mutex) );
18010   if( db ){
18011     if( db->pnBytesFreed ){
18012       *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
18013       return;
18014     }
18015     if( isLookaside(db, p) ){
18016       LookasideSlot *pBuf = (LookasideSlot*)p;
18017       pBuf->pNext = db->lookaside.pFree;
18018       db->lookaside.pFree = pBuf;
18019       db->lookaside.nOut--;
18020       return;
18021     }
18022   }
18023   assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18024   assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18025   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
18026   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18027   sqlite3_free(p);
18028 }
18029
18030 /*
18031 ** Change the size of an existing memory allocation
18032 */
18033 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
18034   int nOld, nNew;
18035   void *pNew;
18036   if( pOld==0 ){
18037     return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
18038   }
18039   if( nBytes<=0 ){
18040     sqlite3_free(pOld); /* IMP: R-31593-10574 */
18041     return 0;
18042   }
18043   if( nBytes>=0x7fffff00 ){
18044     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
18045     return 0;
18046   }
18047   nOld = sqlite3MallocSize(pOld);
18048   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
18049   ** argument to xRealloc is always a value returned by a prior call to
18050   ** xRoundup. */
18051   nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
18052   if( nOld==nNew ){
18053     pNew = pOld;
18054   }else if( sqlite3GlobalConfig.bMemstat ){
18055     sqlite3_mutex_enter(mem0.mutex);
18056     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
18057     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >= 
18058           mem0.alarmThreshold ){
18059       sqlite3MallocAlarm(nNew-nOld);
18060     }
18061     assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
18062     assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
18063     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18064     if( pNew==0 && mem0.alarmCallback ){
18065       sqlite3MallocAlarm(nBytes);
18066       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18067     }
18068     if( pNew ){
18069       nNew = sqlite3MallocSize(pNew);
18070       sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
18071     }
18072     sqlite3_mutex_leave(mem0.mutex);
18073   }else{
18074     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18075   }
18076   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
18077   return pNew;
18078 }
18079
18080 /*
18081 ** The public interface to sqlite3Realloc.  Make sure that the memory
18082 ** subsystem is initialized prior to invoking sqliteRealloc.
18083 */
18084 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
18085 #ifndef SQLITE_OMIT_AUTOINIT
18086   if( sqlite3_initialize() ) return 0;
18087 #endif
18088   return sqlite3Realloc(pOld, n);
18089 }
18090
18091
18092 /*
18093 ** Allocate and zero memory.
18094 */ 
18095 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
18096   void *p = sqlite3Malloc(n);
18097   if( p ){
18098     memset(p, 0, n);
18099   }
18100   return p;
18101 }
18102
18103 /*
18104 ** Allocate and zero memory.  If the allocation fails, make
18105 ** the mallocFailed flag in the connection pointer.
18106 */
18107 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
18108   void *p = sqlite3DbMallocRaw(db, n);
18109   if( p ){
18110     memset(p, 0, n);
18111   }
18112   return p;
18113 }
18114
18115 /*
18116 ** Allocate and zero memory.  If the allocation fails, make
18117 ** the mallocFailed flag in the connection pointer.
18118 **
18119 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
18120 ** failure on the same database connection) then always return 0.
18121 ** Hence for a particular database connection, once malloc starts
18122 ** failing, it fails consistently until mallocFailed is reset.
18123 ** This is an important assumption.  There are many places in the
18124 ** code that do things like this:
18125 **
18126 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
18127 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
18128 **         if( b ) a[10] = 9;
18129 **
18130 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
18131 ** that all prior mallocs (ex: "a") worked too.
18132 */
18133 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
18134   void *p;
18135   assert( db==0 || sqlite3_mutex_held(db->mutex) );
18136   assert( db==0 || db->pnBytesFreed==0 );
18137 #ifndef SQLITE_OMIT_LOOKASIDE
18138   if( db ){
18139     LookasideSlot *pBuf;
18140     if( db->mallocFailed ){
18141       return 0;
18142     }
18143     if( db->lookaside.bEnabled ){
18144       if( n>db->lookaside.sz ){
18145         db->lookaside.anStat[1]++;
18146       }else if( (pBuf = db->lookaside.pFree)==0 ){
18147         db->lookaside.anStat[2]++;
18148       }else{
18149         db->lookaside.pFree = pBuf->pNext;
18150         db->lookaside.nOut++;
18151         db->lookaside.anStat[0]++;
18152         if( db->lookaside.nOut>db->lookaside.mxOut ){
18153           db->lookaside.mxOut = db->lookaside.nOut;
18154         }
18155         return (void*)pBuf;
18156       }
18157     }
18158   }
18159 #else
18160   if( db && db->mallocFailed ){
18161     return 0;
18162   }
18163 #endif
18164   p = sqlite3Malloc(n);
18165   if( !p && db ){
18166     db->mallocFailed = 1;
18167   }
18168   sqlite3MemdebugSetType(p, MEMTYPE_DB |
18169          ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
18170   return p;
18171 }
18172
18173 /*
18174 ** Resize the block of memory pointed to by p to n bytes. If the
18175 ** resize fails, set the mallocFailed flag in the connection object.
18176 */
18177 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
18178   void *pNew = 0;
18179   assert( db!=0 );
18180   assert( sqlite3_mutex_held(db->mutex) );
18181   if( db->mallocFailed==0 ){
18182     if( p==0 ){
18183       return sqlite3DbMallocRaw(db, n);
18184     }
18185     if( isLookaside(db, p) ){
18186       if( n<=db->lookaside.sz ){
18187         return p;
18188       }
18189       pNew = sqlite3DbMallocRaw(db, n);
18190       if( pNew ){
18191         memcpy(pNew, p, db->lookaside.sz);
18192         sqlite3DbFree(db, p);
18193       }
18194     }else{
18195       assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18196       assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18197       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18198       pNew = sqlite3_realloc(p, n);
18199       if( !pNew ){
18200         sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
18201         db->mallocFailed = 1;
18202       }
18203       sqlite3MemdebugSetType(pNew, MEMTYPE_DB | 
18204             (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
18205     }
18206   }
18207   return pNew;
18208 }
18209
18210 /*
18211 ** Attempt to reallocate p.  If the reallocation fails, then free p
18212 ** and set the mallocFailed flag in the database connection.
18213 */
18214 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
18215   void *pNew;
18216   pNew = sqlite3DbRealloc(db, p, n);
18217   if( !pNew ){
18218     sqlite3DbFree(db, p);
18219   }
18220   return pNew;
18221 }
18222
18223 /*
18224 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
18225 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
18226 ** is because when memory debugging is turned on, these two functions are 
18227 ** called via macros that record the current file and line number in the
18228 ** ThreadData structure.
18229 */
18230 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
18231   char *zNew;
18232   size_t n;
18233   if( z==0 ){
18234     return 0;
18235   }
18236   n = sqlite3Strlen30(z) + 1;
18237   assert( (n&0x7fffffff)==n );
18238   zNew = sqlite3DbMallocRaw(db, (int)n);
18239   if( zNew ){
18240     memcpy(zNew, z, n);
18241   }
18242   return zNew;
18243 }
18244 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
18245   char *zNew;
18246   if( z==0 ){
18247     return 0;
18248   }
18249   assert( (n&0x7fffffff)==n );
18250   zNew = sqlite3DbMallocRaw(db, n+1);
18251   if( zNew ){
18252     memcpy(zNew, z, n);
18253     zNew[n] = 0;
18254   }
18255   return zNew;
18256 }
18257
18258 /*
18259 ** Create a string from the zFromat argument and the va_list that follows.
18260 ** Store the string in memory obtained from sqliteMalloc() and make *pz
18261 ** point to that string.
18262 */
18263 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
18264   va_list ap;
18265   char *z;
18266
18267   va_start(ap, zFormat);
18268   z = sqlite3VMPrintf(db, zFormat, ap);
18269   va_end(ap);
18270   sqlite3DbFree(db, *pz);
18271   *pz = z;
18272 }
18273
18274
18275 /*
18276 ** This function must be called before exiting any API function (i.e. 
18277 ** returning control to the user) that has called sqlite3_malloc or
18278 ** sqlite3_realloc.
18279 **
18280 ** The returned value is normally a copy of the second argument to this
18281 ** function. However, if a malloc() failure has occurred since the previous
18282 ** invocation SQLITE_NOMEM is returned instead. 
18283 **
18284 ** If the first argument, db, is not NULL and a malloc() error has occurred,
18285 ** then the connection error-code (the value returned by sqlite3_errcode())
18286 ** is set to SQLITE_NOMEM.
18287 */
18288 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
18289   /* If the db handle is not NULL, then we must hold the connection handle
18290   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
18291   ** is unsafe, as is the call to sqlite3Error().
18292   */
18293   assert( !db || sqlite3_mutex_held(db->mutex) );
18294   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
18295     sqlite3Error(db, SQLITE_NOMEM, 0);
18296     db->mallocFailed = 0;
18297     rc = SQLITE_NOMEM;
18298   }
18299   return rc & (db ? db->errMask : 0xff);
18300 }
18301
18302 /************** End of malloc.c **********************************************/
18303 /************** Begin file printf.c ******************************************/
18304 /*
18305 ** The "printf" code that follows dates from the 1980's.  It is in
18306 ** the public domain.  The original comments are included here for
18307 ** completeness.  They are very out-of-date but might be useful as
18308 ** an historical reference.  Most of the "enhancements" have been backed
18309 ** out so that the functionality is now the same as standard printf().
18310 **
18311 **************************************************************************
18312 **
18313 ** The following modules is an enhanced replacement for the "printf" subroutines
18314 ** found in the standard C library.  The following enhancements are
18315 ** supported:
18316 **
18317 **      +  Additional functions.  The standard set of "printf" functions
18318 **         includes printf, fprintf, sprintf, vprintf, vfprintf, and
18319 **         vsprintf.  This module adds the following:
18320 **
18321 **           *  snprintf -- Works like sprintf, but has an extra argument
18322 **                          which is the size of the buffer written to.
18323 **
18324 **           *  mprintf --  Similar to sprintf.  Writes output to memory
18325 **                          obtained from malloc.
18326 **
18327 **           *  xprintf --  Calls a function to dispose of output.
18328 **
18329 **           *  nprintf --  No output, but returns the number of characters
18330 **                          that would have been output by printf.
18331 **
18332 **           *  A v- version (ex: vsnprintf) of every function is also
18333 **              supplied.
18334 **
18335 **      +  A few extensions to the formatting notation are supported:
18336 **
18337 **           *  The "=" flag (similar to "-") causes the output to be
18338 **              be centered in the appropriately sized field.
18339 **
18340 **           *  The %b field outputs an integer in binary notation.
18341 **
18342 **           *  The %c field now accepts a precision.  The character output
18343 **              is repeated by the number of times the precision specifies.
18344 **
18345 **           *  The %' field works like %c, but takes as its character the
18346 **              next character of the format string, instead of the next
18347 **              argument.  For example,  printf("%.78'-")  prints 78 minus
18348 **              signs, the same as  printf("%.78c",'-').
18349 **
18350 **      +  When compiled using GCC on a SPARC, this version of printf is
18351 **         faster than the library printf for SUN OS 4.1.
18352 **
18353 **      +  All functions are fully reentrant.
18354 **
18355 */
18356
18357 /*
18358 ** Conversion types fall into various categories as defined by the
18359 ** following enumeration.
18360 */
18361 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
18362 #define etFLOAT       2 /* Floating point.  %f */
18363 #define etEXP         3 /* Exponentional notation. %e and %E */
18364 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
18365 #define etSIZE        5 /* Return number of characters processed so far. %n */
18366 #define etSTRING      6 /* Strings. %s */
18367 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
18368 #define etPERCENT     8 /* Percent symbol. %% */
18369 #define etCHARX       9 /* Characters. %c */
18370 /* The rest are extensions, not normally found in printf() */
18371 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
18372 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
18373                           NULL pointers replaced by SQL NULL.  %Q */
18374 #define etTOKEN      12 /* a pointer to a Token structure */
18375 #define etSRCLIST    13 /* a pointer to a SrcList */
18376 #define etPOINTER    14 /* The %p conversion */
18377 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
18378 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
18379
18380 #define etINVALID     0 /* Any unrecognized conversion type */
18381
18382
18383 /*
18384 ** An "etByte" is an 8-bit unsigned value.
18385 */
18386 typedef unsigned char etByte;
18387
18388 /*
18389 ** Each builtin conversion character (ex: the 'd' in "%d") is described
18390 ** by an instance of the following structure
18391 */
18392 typedef struct et_info {   /* Information about each format field */
18393   char fmttype;            /* The format field code letter */
18394   etByte base;             /* The base for radix conversion */
18395   etByte flags;            /* One or more of FLAG_ constants below */
18396   etByte type;             /* Conversion paradigm */
18397   etByte charset;          /* Offset into aDigits[] of the digits string */
18398   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
18399 } et_info;
18400
18401 /*
18402 ** Allowed values for et_info.flags
18403 */
18404 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
18405 #define FLAG_INTERN  2     /* True if for internal use only */
18406 #define FLAG_STRING  4     /* Allow infinity precision */
18407
18408
18409 /*
18410 ** The following table is searched linearly, so it is good to put the
18411 ** most frequently used conversion types first.
18412 */
18413 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
18414 static const char aPrefix[] = "-x0\000X0";
18415 static const et_info fmtinfo[] = {
18416   {  'd', 10, 1, etRADIX,      0,  0 },
18417   {  's',  0, 4, etSTRING,     0,  0 },
18418   {  'g',  0, 1, etGENERIC,    30, 0 },
18419   {  'z',  0, 4, etDYNSTRING,  0,  0 },
18420   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
18421   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
18422   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
18423   {  'c',  0, 0, etCHARX,      0,  0 },
18424   {  'o',  8, 0, etRADIX,      0,  2 },
18425   {  'u', 10, 0, etRADIX,      0,  0 },
18426   {  'x', 16, 0, etRADIX,      16, 1 },
18427   {  'X', 16, 0, etRADIX,      0,  4 },
18428 #ifndef SQLITE_OMIT_FLOATING_POINT
18429   {  'f',  0, 1, etFLOAT,      0,  0 },
18430   {  'e',  0, 1, etEXP,        30, 0 },
18431   {  'E',  0, 1, etEXP,        14, 0 },
18432   {  'G',  0, 1, etGENERIC,    14, 0 },
18433 #endif
18434   {  'i', 10, 1, etRADIX,      0,  0 },
18435   {  'n',  0, 0, etSIZE,       0,  0 },
18436   {  '%',  0, 0, etPERCENT,    0,  0 },
18437   {  'p', 16, 0, etPOINTER,    0,  1 },
18438
18439 /* All the rest have the FLAG_INTERN bit set and are thus for internal
18440 ** use only */
18441   {  'T',  0, 2, etTOKEN,      0,  0 },
18442   {  'S',  0, 2, etSRCLIST,    0,  0 },
18443   {  'r', 10, 3, etORDINAL,    0,  0 },
18444 };
18445
18446 /*
18447 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
18448 ** conversions will work.
18449 */
18450 #ifndef SQLITE_OMIT_FLOATING_POINT
18451 /*
18452 ** "*val" is a double such that 0.1 <= *val < 10.0
18453 ** Return the ascii code for the leading digit of *val, then
18454 ** multiply "*val" by 10.0 to renormalize.
18455 **
18456 ** Example:
18457 **     input:     *val = 3.14159
18458 **     output:    *val = 1.4159    function return = '3'
18459 **
18460 ** The counter *cnt is incremented each time.  After counter exceeds
18461 ** 16 (the number of significant digits in a 64-bit float) '0' is
18462 ** always returned.
18463 */
18464 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
18465   int digit;
18466   LONGDOUBLE_TYPE d;
18467   if( (*cnt)++ >= 16 ) return '0';
18468   digit = (int)*val;
18469   d = digit;
18470   digit += '0';
18471   *val = (*val - d)*10.0;
18472   return (char)digit;
18473 }
18474 #endif /* SQLITE_OMIT_FLOATING_POINT */
18475
18476 /*
18477 ** Append N space characters to the given string buffer.
18478 */
18479 static void appendSpace(StrAccum *pAccum, int N){
18480   static const char zSpaces[] = "                             ";
18481   while( N>=(int)sizeof(zSpaces)-1 ){
18482     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
18483     N -= sizeof(zSpaces)-1;
18484   }
18485   if( N>0 ){
18486     sqlite3StrAccumAppend(pAccum, zSpaces, N);
18487   }
18488 }
18489
18490 /*
18491 ** On machines with a small stack size, you can redefine the
18492 ** SQLITE_PRINT_BUF_SIZE to be less than 350.
18493 */
18494 #ifndef SQLITE_PRINT_BUF_SIZE
18495 # if defined(SQLITE_SMALL_STACK)
18496 #   define SQLITE_PRINT_BUF_SIZE 50
18497 # else
18498 #   define SQLITE_PRINT_BUF_SIZE 350
18499 # endif
18500 #endif
18501 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
18502
18503 /*
18504 ** The root program.  All variations call this core.
18505 **
18506 ** INPUTS:
18507 **   func   This is a pointer to a function taking three arguments
18508 **            1. A pointer to anything.  Same as the "arg" parameter.
18509 **            2. A pointer to the list of characters to be output
18510 **               (Note, this list is NOT null terminated.)
18511 **            3. An integer number of characters to be output.
18512 **               (Note: This number might be zero.)
18513 **
18514 **   arg    This is the pointer to anything which will be passed as the
18515 **          first argument to "func".  Use it for whatever you like.
18516 **
18517 **   fmt    This is the format string, as in the usual print.
18518 **
18519 **   ap     This is a pointer to a list of arguments.  Same as in
18520 **          vfprint.
18521 **
18522 ** OUTPUTS:
18523 **          The return value is the total number of characters sent to
18524 **          the function "func".  Returns -1 on a error.
18525 **
18526 ** Note that the order in which automatic variables are declared below
18527 ** seems to make a big difference in determining how fast this beast
18528 ** will run.
18529 */
18530 SQLITE_PRIVATE void sqlite3VXPrintf(
18531   StrAccum *pAccum,                  /* Accumulate results here */
18532   int useExtended,                   /* Allow extended %-conversions */
18533   const char *fmt,                   /* Format string */
18534   va_list ap                         /* arguments */
18535 ){
18536   int c;                     /* Next character in the format string */
18537   char *bufpt;               /* Pointer to the conversion buffer */
18538   int precision;             /* Precision of the current field */
18539   int length;                /* Length of the field */
18540   int idx;                   /* A general purpose loop counter */
18541   int width;                 /* Width of the current field */
18542   etByte flag_leftjustify;   /* True if "-" flag is present */
18543   etByte flag_plussign;      /* True if "+" flag is present */
18544   etByte flag_blanksign;     /* True if " " flag is present */
18545   etByte flag_alternateform; /* True if "#" flag is present */
18546   etByte flag_altform2;      /* True if "!" flag is present */
18547   etByte flag_zeropad;       /* True if field width constant starts with zero */
18548   etByte flag_long;          /* True if "l" flag is present */
18549   etByte flag_longlong;      /* True if the "ll" flag is present */
18550   etByte done;               /* Loop termination flag */
18551   sqlite_uint64 longvalue;   /* Value for integer types */
18552   LONGDOUBLE_TYPE realvalue; /* Value for real types */
18553   const et_info *infop;      /* Pointer to the appropriate info structure */
18554   char buf[etBUFSIZE];       /* Conversion buffer */
18555   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
18556   etByte xtype = 0;          /* Conversion paradigm */
18557   char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
18558 #ifndef SQLITE_OMIT_FLOATING_POINT
18559   int  exp, e2;              /* exponent of real numbers */
18560   double rounder;            /* Used for rounding floating point values */
18561   etByte flag_dp;            /* True if decimal point should be shown */
18562   etByte flag_rtz;           /* True if trailing zeros should be removed */
18563   etByte flag_exp;           /* True to force display of the exponent */
18564   int nsd;                   /* Number of significant digits returned */
18565 #endif
18566
18567   length = 0;
18568   bufpt = 0;
18569   for(; (c=(*fmt))!=0; ++fmt){
18570     if( c!='%' ){
18571       int amt;
18572       bufpt = (char *)fmt;
18573       amt = 1;
18574       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
18575       sqlite3StrAccumAppend(pAccum, bufpt, amt);
18576       if( c==0 ) break;
18577     }
18578     if( (c=(*++fmt))==0 ){
18579       sqlite3StrAccumAppend(pAccum, "%", 1);
18580       break;
18581     }
18582     /* Find out what flags are present */
18583     flag_leftjustify = flag_plussign = flag_blanksign = 
18584      flag_alternateform = flag_altform2 = flag_zeropad = 0;
18585     done = 0;
18586     do{
18587       switch( c ){
18588         case '-':   flag_leftjustify = 1;     break;
18589         case '+':   flag_plussign = 1;        break;
18590         case ' ':   flag_blanksign = 1;       break;
18591         case '#':   flag_alternateform = 1;   break;
18592         case '!':   flag_altform2 = 1;        break;
18593         case '0':   flag_zeropad = 1;         break;
18594         default:    done = 1;                 break;
18595       }
18596     }while( !done && (c=(*++fmt))!=0 );
18597     /* Get the field width */
18598     width = 0;
18599     if( c=='*' ){
18600       width = va_arg(ap,int);
18601       if( width<0 ){
18602         flag_leftjustify = 1;
18603         width = -width;
18604       }
18605       c = *++fmt;
18606     }else{
18607       while( c>='0' && c<='9' ){
18608         width = width*10 + c - '0';
18609         c = *++fmt;
18610       }
18611     }
18612     if( width > etBUFSIZE-10 ){
18613       width = etBUFSIZE-10;
18614     }
18615     /* Get the precision */
18616     if( c=='.' ){
18617       precision = 0;
18618       c = *++fmt;
18619       if( c=='*' ){
18620         precision = va_arg(ap,int);
18621         if( precision<0 ) precision = -precision;
18622         c = *++fmt;
18623       }else{
18624         while( c>='0' && c<='9' ){
18625           precision = precision*10 + c - '0';
18626           c = *++fmt;
18627         }
18628       }
18629     }else{
18630       precision = -1;
18631     }
18632     /* Get the conversion type modifier */
18633     if( c=='l' ){
18634       flag_long = 1;
18635       c = *++fmt;
18636       if( c=='l' ){
18637         flag_longlong = 1;
18638         c = *++fmt;
18639       }else{
18640         flag_longlong = 0;
18641       }
18642     }else{
18643       flag_long = flag_longlong = 0;
18644     }
18645     /* Fetch the info entry for the field */
18646     infop = &fmtinfo[0];
18647     xtype = etINVALID;
18648     for(idx=0; idx<ArraySize(fmtinfo); idx++){
18649       if( c==fmtinfo[idx].fmttype ){
18650         infop = &fmtinfo[idx];
18651         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
18652           xtype = infop->type;
18653         }else{
18654           return;
18655         }
18656         break;
18657       }
18658     }
18659     zExtra = 0;
18660
18661
18662     /* Limit the precision to prevent overflowing buf[] during conversion */
18663     if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
18664       precision = etBUFSIZE-40;
18665     }
18666
18667     /*
18668     ** At this point, variables are initialized as follows:
18669     **
18670     **   flag_alternateform          TRUE if a '#' is present.
18671     **   flag_altform2               TRUE if a '!' is present.
18672     **   flag_plussign               TRUE if a '+' is present.
18673     **   flag_leftjustify            TRUE if a '-' is present or if the
18674     **                               field width was negative.
18675     **   flag_zeropad                TRUE if the width began with 0.
18676     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
18677     **                               the conversion character.
18678     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
18679     **                               the conversion character.
18680     **   flag_blanksign              TRUE if a ' ' is present.
18681     **   width                       The specified field width.  This is
18682     **                               always non-negative.  Zero is the default.
18683     **   precision                   The specified precision.  The default
18684     **                               is -1.
18685     **   xtype                       The class of the conversion.
18686     **   infop                       Pointer to the appropriate info struct.
18687     */
18688     switch( xtype ){
18689       case etPOINTER:
18690         flag_longlong = sizeof(char*)==sizeof(i64);
18691         flag_long = sizeof(char*)==sizeof(long int);
18692         /* Fall through into the next case */
18693       case etORDINAL:
18694       case etRADIX:
18695         if( infop->flags & FLAG_SIGNED ){
18696           i64 v;
18697           if( flag_longlong ){
18698             v = va_arg(ap,i64);
18699           }else if( flag_long ){
18700             v = va_arg(ap,long int);
18701           }else{
18702             v = va_arg(ap,int);
18703           }
18704           if( v<0 ){
18705             longvalue = -v;
18706             prefix = '-';
18707           }else{
18708             longvalue = v;
18709             if( flag_plussign )        prefix = '+';
18710             else if( flag_blanksign )  prefix = ' ';
18711             else                       prefix = 0;
18712           }
18713         }else{
18714           if( flag_longlong ){
18715             longvalue = va_arg(ap,u64);
18716           }else if( flag_long ){
18717             longvalue = va_arg(ap,unsigned long int);
18718           }else{
18719             longvalue = va_arg(ap,unsigned int);
18720           }
18721           prefix = 0;
18722         }
18723         if( longvalue==0 ) flag_alternateform = 0;
18724         if( flag_zeropad && precision<width-(prefix!=0) ){
18725           precision = width-(prefix!=0);
18726         }
18727         bufpt = &buf[etBUFSIZE-1];
18728         if( xtype==etORDINAL ){
18729           static const char zOrd[] = "thstndrd";
18730           int x = (int)(longvalue % 10);
18731           if( x>=4 || (longvalue/10)%10==1 ){
18732             x = 0;
18733           }
18734           buf[etBUFSIZE-3] = zOrd[x*2];
18735           buf[etBUFSIZE-2] = zOrd[x*2+1];
18736           bufpt -= 2;
18737         }
18738         {
18739           register const char *cset;      /* Use registers for speed */
18740           register int base;
18741           cset = &aDigits[infop->charset];
18742           base = infop->base;
18743           do{                                           /* Convert to ascii */
18744             *(--bufpt) = cset[longvalue%base];
18745             longvalue = longvalue/base;
18746           }while( longvalue>0 );
18747         }
18748         length = (int)(&buf[etBUFSIZE-1]-bufpt);
18749         for(idx=precision-length; idx>0; idx--){
18750           *(--bufpt) = '0';                             /* Zero pad */
18751         }
18752         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
18753         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
18754           const char *pre;
18755           char x;
18756           pre = &aPrefix[infop->prefix];
18757           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
18758         }
18759         length = (int)(&buf[etBUFSIZE-1]-bufpt);
18760         break;
18761       case etFLOAT:
18762       case etEXP:
18763       case etGENERIC:
18764         realvalue = va_arg(ap,double);
18765 #ifdef SQLITE_OMIT_FLOATING_POINT
18766         length = 0;
18767 #else
18768         if( precision<0 ) precision = 6;         /* Set default precision */
18769         if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
18770         if( realvalue<0.0 ){
18771           realvalue = -realvalue;
18772           prefix = '-';
18773         }else{
18774           if( flag_plussign )          prefix = '+';
18775           else if( flag_blanksign )    prefix = ' ';
18776           else                         prefix = 0;
18777         }
18778         if( xtype==etGENERIC && precision>0 ) precision--;
18779 #if 0
18780         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
18781         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
18782 #else
18783         /* It makes more sense to use 0.5 */
18784         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
18785 #endif
18786         if( xtype==etFLOAT ) realvalue += rounder;
18787         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
18788         exp = 0;
18789         if( sqlite3IsNaN((double)realvalue) ){
18790           bufpt = "NaN";
18791           length = 3;
18792           break;
18793         }
18794         if( realvalue>0.0 ){
18795           while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
18796           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
18797           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
18798           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
18799           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
18800           if( exp>350 ){
18801             if( prefix=='-' ){
18802               bufpt = "-Inf";
18803             }else if( prefix=='+' ){
18804               bufpt = "+Inf";
18805             }else{
18806               bufpt = "Inf";
18807             }
18808             length = sqlite3Strlen30(bufpt);
18809             break;
18810           }
18811         }
18812         bufpt = buf;
18813         /*
18814         ** If the field type is etGENERIC, then convert to either etEXP
18815         ** or etFLOAT, as appropriate.
18816         */
18817         flag_exp = xtype==etEXP;
18818         if( xtype!=etFLOAT ){
18819           realvalue += rounder;
18820           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
18821         }
18822         if( xtype==etGENERIC ){
18823           flag_rtz = !flag_alternateform;
18824           if( exp<-4 || exp>precision ){
18825             xtype = etEXP;
18826           }else{
18827             precision = precision - exp;
18828             xtype = etFLOAT;
18829           }
18830         }else{
18831           flag_rtz = 0;
18832         }
18833         if( xtype==etEXP ){
18834           e2 = 0;
18835         }else{
18836           e2 = exp;
18837         }
18838         nsd = 0;
18839         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
18840         /* The sign in front of the number */
18841         if( prefix ){
18842           *(bufpt++) = prefix;
18843         }
18844         /* Digits prior to the decimal point */
18845         if( e2<0 ){
18846           *(bufpt++) = '0';
18847         }else{
18848           for(; e2>=0; e2--){
18849             *(bufpt++) = et_getdigit(&realvalue,&nsd);
18850           }
18851         }
18852         /* The decimal point */
18853         if( flag_dp ){
18854           *(bufpt++) = '.';
18855         }
18856         /* "0" digits after the decimal point but before the first
18857         ** significant digit of the number */
18858         for(e2++; e2<0; precision--, e2++){
18859           assert( precision>0 );
18860           *(bufpt++) = '0';
18861         }
18862         /* Significant digits after the decimal point */
18863         while( (precision--)>0 ){
18864           *(bufpt++) = et_getdigit(&realvalue,&nsd);
18865         }
18866         /* Remove trailing zeros and the "." if no digits follow the "." */
18867         if( flag_rtz && flag_dp ){
18868           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
18869           assert( bufpt>buf );
18870           if( bufpt[-1]=='.' ){
18871             if( flag_altform2 ){
18872               *(bufpt++) = '0';
18873             }else{
18874               *(--bufpt) = 0;
18875             }
18876           }
18877         }
18878         /* Add the "eNNN" suffix */
18879         if( flag_exp || xtype==etEXP ){
18880           *(bufpt++) = aDigits[infop->charset];
18881           if( exp<0 ){
18882             *(bufpt++) = '-'; exp = -exp;
18883           }else{
18884             *(bufpt++) = '+';
18885           }
18886           if( exp>=100 ){
18887             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
18888             exp %= 100;
18889           }
18890           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
18891           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
18892         }
18893         *bufpt = 0;
18894
18895         /* The converted number is in buf[] and zero terminated. Output it.
18896         ** Note that the number is in the usual order, not reversed as with
18897         ** integer conversions. */
18898         length = (int)(bufpt-buf);
18899         bufpt = buf;
18900
18901         /* Special case:  Add leading zeros if the flag_zeropad flag is
18902         ** set and we are not left justified */
18903         if( flag_zeropad && !flag_leftjustify && length < width){
18904           int i;
18905           int nPad = width - length;
18906           for(i=width; i>=nPad; i--){
18907             bufpt[i] = bufpt[i-nPad];
18908           }
18909           i = prefix!=0;
18910           while( nPad-- ) bufpt[i++] = '0';
18911           length = width;
18912         }
18913 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
18914         break;
18915       case etSIZE:
18916         *(va_arg(ap,int*)) = pAccum->nChar;
18917         length = width = 0;
18918         break;
18919       case etPERCENT:
18920         buf[0] = '%';
18921         bufpt = buf;
18922         length = 1;
18923         break;
18924       case etCHARX:
18925         c = va_arg(ap,int);
18926         buf[0] = (char)c;
18927         if( precision>=0 ){
18928           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
18929           length = precision;
18930         }else{
18931           length =1;
18932         }
18933         bufpt = buf;
18934         break;
18935       case etSTRING:
18936       case etDYNSTRING:
18937         bufpt = va_arg(ap,char*);
18938         if( bufpt==0 ){
18939           bufpt = "";
18940         }else if( xtype==etDYNSTRING ){
18941           zExtra = bufpt;
18942         }
18943         if( precision>=0 ){
18944           for(length=0; length<precision && bufpt[length]; length++){}
18945         }else{
18946           length = sqlite3Strlen30(bufpt);
18947         }
18948         break;
18949       case etSQLESCAPE:
18950       case etSQLESCAPE2:
18951       case etSQLESCAPE3: {
18952         int i, j, k, n, isnull;
18953         int needQuote;
18954         char ch;
18955         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
18956         char *escarg = va_arg(ap,char*);
18957         isnull = escarg==0;
18958         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
18959         k = precision;
18960         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
18961           if( ch==q )  n++;
18962         }
18963         needQuote = !isnull && xtype==etSQLESCAPE2;
18964         n += i + 1 + needQuote*2;
18965         if( n>etBUFSIZE ){
18966           bufpt = zExtra = sqlite3Malloc( n );
18967           if( bufpt==0 ){
18968             pAccum->mallocFailed = 1;
18969             return;
18970           }
18971         }else{
18972           bufpt = buf;
18973         }
18974         j = 0;
18975         if( needQuote ) bufpt[j++] = q;
18976         k = i;
18977         for(i=0; i<k; i++){
18978           bufpt[j++] = ch = escarg[i];
18979           if( ch==q ) bufpt[j++] = ch;
18980         }
18981         if( needQuote ) bufpt[j++] = q;
18982         bufpt[j] = 0;
18983         length = j;
18984         /* The precision in %q and %Q means how many input characters to
18985         ** consume, not the length of the output...
18986         ** if( precision>=0 && precision<length ) length = precision; */
18987         break;
18988       }
18989       case etTOKEN: {
18990         Token *pToken = va_arg(ap, Token*);
18991         if( pToken ){
18992           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
18993         }
18994         length = width = 0;
18995         break;
18996       }
18997       case etSRCLIST: {
18998         SrcList *pSrc = va_arg(ap, SrcList*);
18999         int k = va_arg(ap, int);
19000         struct SrcList_item *pItem = &pSrc->a[k];
19001         assert( k>=0 && k<pSrc->nSrc );
19002         if( pItem->zDatabase ){
19003           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
19004           sqlite3StrAccumAppend(pAccum, ".", 1);
19005         }
19006         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
19007         length = width = 0;
19008         break;
19009       }
19010       default: {
19011         assert( xtype==etINVALID );
19012         return;
19013       }
19014     }/* End switch over the format type */
19015     /*
19016     ** The text of the conversion is pointed to by "bufpt" and is
19017     ** "length" characters long.  The field width is "width".  Do
19018     ** the output.
19019     */
19020     if( !flag_leftjustify ){
19021       register int nspace;
19022       nspace = width-length;
19023       if( nspace>0 ){
19024         appendSpace(pAccum, nspace);
19025       }
19026     }
19027     if( length>0 ){
19028       sqlite3StrAccumAppend(pAccum, bufpt, length);
19029     }
19030     if( flag_leftjustify ){
19031       register int nspace;
19032       nspace = width-length;
19033       if( nspace>0 ){
19034         appendSpace(pAccum, nspace);
19035       }
19036     }
19037     if( zExtra ){
19038       sqlite3_free(zExtra);
19039     }
19040   }/* End for loop over the format string */
19041 } /* End of function */
19042
19043 /*
19044 ** Append N bytes of text from z to the StrAccum object.
19045 */
19046 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
19047   assert( z!=0 || N==0 );
19048   if( p->tooBig | p->mallocFailed ){
19049     testcase(p->tooBig);
19050     testcase(p->mallocFailed);
19051     return;
19052   }
19053   if( N<0 ){
19054     N = sqlite3Strlen30(z);
19055   }
19056   if( N==0 || NEVER(z==0) ){
19057     return;
19058   }
19059   if( p->nChar+N >= p->nAlloc ){
19060     char *zNew;
19061     if( !p->useMalloc ){
19062       p->tooBig = 1;
19063       N = p->nAlloc - p->nChar - 1;
19064       if( N<=0 ){
19065         return;
19066       }
19067     }else{
19068       char *zOld = (p->zText==p->zBase ? 0 : p->zText);
19069       i64 szNew = p->nChar;
19070       szNew += N + 1;
19071       if( szNew > p->mxAlloc ){
19072         sqlite3StrAccumReset(p);
19073         p->tooBig = 1;
19074         return;
19075       }else{
19076         p->nAlloc = (int)szNew;
19077       }
19078       if( p->useMalloc==1 ){
19079         zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
19080       }else{
19081         zNew = sqlite3_realloc(zOld, p->nAlloc);
19082       }
19083       if( zNew ){
19084         if( zOld==0 ) memcpy(zNew, p->zText, p->nChar);
19085         p->zText = zNew;
19086       }else{
19087         p->mallocFailed = 1;
19088         sqlite3StrAccumReset(p);
19089         return;
19090       }
19091     }
19092   }
19093   memcpy(&p->zText[p->nChar], z, N);
19094   p->nChar += N;
19095 }
19096
19097 /*
19098 ** Finish off a string by making sure it is zero-terminated.
19099 ** Return a pointer to the resulting string.  Return a NULL
19100 ** pointer if any kind of error was encountered.
19101 */
19102 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
19103   if( p->zText ){
19104     p->zText[p->nChar] = 0;
19105     if( p->useMalloc && p->zText==p->zBase ){
19106       if( p->useMalloc==1 ){
19107         p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
19108       }else{
19109         p->zText = sqlite3_malloc(p->nChar+1);
19110       }
19111       if( p->zText ){
19112         memcpy(p->zText, p->zBase, p->nChar+1);
19113       }else{
19114         p->mallocFailed = 1;
19115       }
19116     }
19117   }
19118   return p->zText;
19119 }
19120
19121 /*
19122 ** Reset an StrAccum string.  Reclaim all malloced memory.
19123 */
19124 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
19125   if( p->zText!=p->zBase ){
19126     if( p->useMalloc==1 ){
19127       sqlite3DbFree(p->db, p->zText);
19128     }else{
19129       sqlite3_free(p->zText);
19130     }
19131   }
19132   p->zText = 0;
19133 }
19134
19135 /*
19136 ** Initialize a string accumulator
19137 */
19138 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
19139   p->zText = p->zBase = zBase;
19140   p->db = 0;
19141   p->nChar = 0;
19142   p->nAlloc = n;
19143   p->mxAlloc = mx;
19144   p->useMalloc = 1;
19145   p->tooBig = 0;
19146   p->mallocFailed = 0;
19147 }
19148
19149 /*
19150 ** Print into memory obtained from sqliteMalloc().  Use the internal
19151 ** %-conversion extensions.
19152 */
19153 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
19154   char *z;
19155   char zBase[SQLITE_PRINT_BUF_SIZE];
19156   StrAccum acc;
19157   assert( db!=0 );
19158   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
19159                       db->aLimit[SQLITE_LIMIT_LENGTH]);
19160   acc.db = db;
19161   sqlite3VXPrintf(&acc, 1, zFormat, ap);
19162   z = sqlite3StrAccumFinish(&acc);
19163   if( acc.mallocFailed ){
19164     db->mallocFailed = 1;
19165   }
19166   return z;
19167 }
19168
19169 /*
19170 ** Print into memory obtained from sqliteMalloc().  Use the internal
19171 ** %-conversion extensions.
19172 */
19173 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
19174   va_list ap;
19175   char *z;
19176   va_start(ap, zFormat);
19177   z = sqlite3VMPrintf(db, zFormat, ap);
19178   va_end(ap);
19179   return z;
19180 }
19181
19182 /*
19183 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
19184 ** the string and before returnning.  This routine is intended to be used
19185 ** to modify an existing string.  For example:
19186 **
19187 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
19188 **
19189 */
19190 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
19191   va_list ap;
19192   char *z;
19193   va_start(ap, zFormat);
19194   z = sqlite3VMPrintf(db, zFormat, ap);
19195   va_end(ap);
19196   sqlite3DbFree(db, zStr);
19197   return z;
19198 }
19199
19200 /*
19201 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
19202 ** %-conversion extensions.
19203 */
19204 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
19205   char *z;
19206   char zBase[SQLITE_PRINT_BUF_SIZE];
19207   StrAccum acc;
19208 #ifndef SQLITE_OMIT_AUTOINIT
19209   if( sqlite3_initialize() ) return 0;
19210 #endif
19211   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
19212   acc.useMalloc = 2;
19213   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19214   z = sqlite3StrAccumFinish(&acc);
19215   return z;
19216 }
19217
19218 /*
19219 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
19220 ** %-conversion extensions.
19221 */
19222 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
19223   va_list ap;
19224   char *z;
19225 #ifndef SQLITE_OMIT_AUTOINIT
19226   if( sqlite3_initialize() ) return 0;
19227 #endif
19228   va_start(ap, zFormat);
19229   z = sqlite3_vmprintf(zFormat, ap);
19230   va_end(ap);
19231   return z;
19232 }
19233
19234 /*
19235 ** sqlite3_snprintf() works like snprintf() except that it ignores the
19236 ** current locale settings.  This is important for SQLite because we
19237 ** are not able to use a "," as the decimal point in place of "." as
19238 ** specified by some locales.
19239 **
19240 ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
19241 ** from the snprintf() standard.  Unfortunately, it is too late to change
19242 ** this without breaking compatibility, so we just have to live with the
19243 ** mistake.
19244 **
19245 ** sqlite3_vsnprintf() is the varargs version.
19246 */
19247 SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
19248   StrAccum acc;
19249   if( n<=0 ) return zBuf;
19250   sqlite3StrAccumInit(&acc, zBuf, n, 0);
19251   acc.useMalloc = 0;
19252   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19253   return sqlite3StrAccumFinish(&acc);
19254 }
19255 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
19256   char *z;
19257   va_list ap;
19258   va_start(ap,zFormat);
19259   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
19260   va_end(ap);
19261   return z;
19262 }
19263
19264 /*
19265 ** This is the routine that actually formats the sqlite3_log() message.
19266 ** We house it in a separate routine from sqlite3_log() to avoid using
19267 ** stack space on small-stack systems when logging is disabled.
19268 **
19269 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
19270 ** allocate memory because it might be called while the memory allocator
19271 ** mutex is held.
19272 */
19273 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
19274   StrAccum acc;                          /* String accumulator */
19275   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
19276
19277   sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
19278   acc.useMalloc = 0;
19279   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19280   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
19281                            sqlite3StrAccumFinish(&acc));
19282 }
19283
19284 /*
19285 ** Format and write a message to the log if logging is enabled.
19286 */
19287 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
19288   va_list ap;                             /* Vararg list */
19289   if( sqlite3GlobalConfig.xLog ){
19290     va_start(ap, zFormat);
19291     renderLogMsg(iErrCode, zFormat, ap);
19292     va_end(ap);
19293   }
19294 }
19295
19296 #if defined(SQLITE_DEBUG)
19297 /*
19298 ** A version of printf() that understands %lld.  Used for debugging.
19299 ** The printf() built into some versions of windows does not understand %lld
19300 ** and segfaults if you give it a long long int.
19301 */
19302 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
19303   va_list ap;
19304   StrAccum acc;
19305   char zBuf[500];
19306   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
19307   acc.useMalloc = 0;
19308   va_start(ap,zFormat);
19309   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19310   va_end(ap);
19311   sqlite3StrAccumFinish(&acc);
19312   fprintf(stdout,"%s", zBuf);
19313   fflush(stdout);
19314 }
19315 #endif
19316
19317 #ifndef SQLITE_OMIT_TRACE
19318 /*
19319 ** variable-argument wrapper around sqlite3VXPrintf().
19320 */
19321 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
19322   va_list ap;
19323   va_start(ap,zFormat);
19324   sqlite3VXPrintf(p, 1, zFormat, ap);
19325   va_end(ap);
19326 }
19327 #endif
19328
19329 /************** End of printf.c **********************************************/
19330 /************** Begin file random.c ******************************************/
19331 /*
19332 ** 2001 September 15
19333 **
19334 ** The author disclaims copyright to this source code.  In place of
19335 ** a legal notice, here is a blessing:
19336 **
19337 **    May you do good and not evil.
19338 **    May you find forgiveness for yourself and forgive others.
19339 **    May you share freely, never taking more than you give.
19340 **
19341 *************************************************************************
19342 ** This file contains code to implement a pseudo-random number
19343 ** generator (PRNG) for SQLite.
19344 **
19345 ** Random numbers are used by some of the database backends in order
19346 ** to generate random integer keys for tables or random filenames.
19347 */
19348
19349
19350 /* All threads share a single random number generator.
19351 ** This structure is the current state of the generator.
19352 */
19353 static SQLITE_WSD struct sqlite3PrngType {
19354   unsigned char isInit;          /* True if initialized */
19355   unsigned char i, j;            /* State variables */
19356   unsigned char s[256];          /* State variables */
19357 } sqlite3Prng;
19358
19359 /*
19360 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
19361 ** must be held while executing this routine.
19362 **
19363 ** Why not just use a library random generator like lrand48() for this?
19364 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
19365 ** good source of random numbers.  The lrand48() library function may
19366 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
19367 ** subtle problems on some systems that could cause problems.  It is hard
19368 ** to know.  To minimize the risk of problems due to bad lrand48()
19369 ** implementations, SQLite uses this random number generator based
19370 ** on RC4, which we know works very well.
19371 **
19372 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
19373 ** randomness any more.  But we will leave this code in all the same.
19374 */
19375 static u8 randomByte(void){
19376   unsigned char t;
19377
19378
19379   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
19380   ** state vector.  If writable static data is unsupported on the target,
19381   ** we have to locate the state vector at run-time.  In the more common
19382   ** case where writable static data is supported, wsdPrng can refer directly
19383   ** to the "sqlite3Prng" state vector declared above.
19384   */
19385 #ifdef SQLITE_OMIT_WSD
19386   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
19387 # define wsdPrng p[0]
19388 #else
19389 # define wsdPrng sqlite3Prng
19390 #endif
19391
19392
19393   /* Initialize the state of the random number generator once,
19394   ** the first time this routine is called.  The seed value does
19395   ** not need to contain a lot of randomness since we are not
19396   ** trying to do secure encryption or anything like that...
19397   **
19398   ** Nothing in this file or anywhere else in SQLite does any kind of
19399   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
19400   ** number generator) not as an encryption device.
19401   */
19402   if( !wsdPrng.isInit ){
19403     int i;
19404     char k[256];
19405     wsdPrng.j = 0;
19406     wsdPrng.i = 0;
19407     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
19408     for(i=0; i<256; i++){
19409       wsdPrng.s[i] = (u8)i;
19410     }
19411     for(i=0; i<256; i++){
19412       wsdPrng.j += wsdPrng.s[i] + k[i];
19413       t = wsdPrng.s[wsdPrng.j];
19414       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
19415       wsdPrng.s[i] = t;
19416     }
19417     wsdPrng.isInit = 1;
19418   }
19419
19420   /* Generate and return single random byte
19421   */
19422   wsdPrng.i++;
19423   t = wsdPrng.s[wsdPrng.i];
19424   wsdPrng.j += t;
19425   wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
19426   wsdPrng.s[wsdPrng.j] = t;
19427   t += wsdPrng.s[wsdPrng.i];
19428   return wsdPrng.s[t];
19429 }
19430
19431 /*
19432 ** Return N random bytes.
19433 */
19434 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
19435   unsigned char *zBuf = pBuf;
19436 #if SQLITE_THREADSAFE
19437   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
19438 #endif
19439   sqlite3_mutex_enter(mutex);
19440   while( N-- ){
19441     *(zBuf++) = randomByte();
19442   }
19443   sqlite3_mutex_leave(mutex);
19444 }
19445
19446 #ifndef SQLITE_OMIT_BUILTIN_TEST
19447 /*
19448 ** For testing purposes, we sometimes want to preserve the state of
19449 ** PRNG and restore the PRNG to its saved state at a later time, or
19450 ** to reset the PRNG to its initial state.  These routines accomplish
19451 ** those tasks.
19452 **
19453 ** The sqlite3_test_control() interface calls these routines to
19454 ** control the PRNG.
19455 */
19456 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
19457 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
19458   memcpy(
19459     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
19460     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
19461     sizeof(sqlite3Prng)
19462   );
19463 }
19464 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
19465   memcpy(
19466     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
19467     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
19468     sizeof(sqlite3Prng)
19469   );
19470 }
19471 SQLITE_PRIVATE void sqlite3PrngResetState(void){
19472   GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
19473 }
19474 #endif /* SQLITE_OMIT_BUILTIN_TEST */
19475
19476 /************** End of random.c **********************************************/
19477 /************** Begin file utf.c *********************************************/
19478 /*
19479 ** 2004 April 13
19480 **
19481 ** The author disclaims copyright to this source code.  In place of
19482 ** a legal notice, here is a blessing:
19483 **
19484 **    May you do good and not evil.
19485 **    May you find forgiveness for yourself and forgive others.
19486 **    May you share freely, never taking more than you give.
19487 **
19488 *************************************************************************
19489 ** This file contains routines used to translate between UTF-8, 
19490 ** UTF-16, UTF-16BE, and UTF-16LE.
19491 **
19492 ** Notes on UTF-8:
19493 **
19494 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
19495 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
19496 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
19497 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
19498 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
19499 **
19500 **
19501 ** Notes on UTF-16:  (with wwww+1==uuuuu)
19502 **
19503 **      Word-0               Word-1          Value
19504 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
19505 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
19506 **
19507 **
19508 ** BOM or Byte Order Mark:
19509 **     0xff 0xfe   little-endian utf-16 follows
19510 **     0xfe 0xff   big-endian utf-16 follows
19511 **
19512 */
19513
19514 #ifndef SQLITE_AMALGAMATION
19515 /*
19516 ** The following constant value is used by the SQLITE_BIGENDIAN and
19517 ** SQLITE_LITTLEENDIAN macros.
19518 */
19519 SQLITE_PRIVATE const int sqlite3one = 1;
19520 #endif /* SQLITE_AMALGAMATION */
19521
19522 /*
19523 ** This lookup table is used to help decode the first byte of
19524 ** a multi-byte UTF8 character.
19525 */
19526 static const unsigned char sqlite3Utf8Trans1[] = {
19527   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
19528   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
19529   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
19530   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
19531   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
19532   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
19533   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
19534   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
19535 };
19536
19537
19538 #define WRITE_UTF8(zOut, c) {                          \
19539   if( c<0x00080 ){                                     \
19540     *zOut++ = (u8)(c&0xFF);                            \
19541   }                                                    \
19542   else if( c<0x00800 ){                                \
19543     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
19544     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
19545   }                                                    \
19546   else if( c<0x10000 ){                                \
19547     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
19548     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
19549     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
19550   }else{                                               \
19551     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
19552     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
19553     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
19554     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
19555   }                                                    \
19556 }
19557
19558 #define WRITE_UTF16LE(zOut, c) {                                    \
19559   if( c<=0xFFFF ){                                                  \
19560     *zOut++ = (u8)(c&0x00FF);                                       \
19561     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
19562   }else{                                                            \
19563     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
19564     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
19565     *zOut++ = (u8)(c&0x00FF);                                       \
19566     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
19567   }                                                                 \
19568 }
19569
19570 #define WRITE_UTF16BE(zOut, c) {                                    \
19571   if( c<=0xFFFF ){                                                  \
19572     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
19573     *zOut++ = (u8)(c&0x00FF);                                       \
19574   }else{                                                            \
19575     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
19576     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
19577     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
19578     *zOut++ = (u8)(c&0x00FF);                                       \
19579   }                                                                 \
19580 }
19581
19582 #define READ_UTF16LE(zIn, TERM, c){                                   \
19583   c = (*zIn++);                                                       \
19584   c += ((*zIn++)<<8);                                                 \
19585   if( c>=0xD800 && c<0xE000 && TERM ){                                \
19586     int c2 = (*zIn++);                                                \
19587     c2 += ((*zIn++)<<8);                                              \
19588     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
19589   }                                                                   \
19590 }
19591
19592 #define READ_UTF16BE(zIn, TERM, c){                                   \
19593   c = ((*zIn++)<<8);                                                  \
19594   c += (*zIn++);                                                      \
19595   if( c>=0xD800 && c<0xE000 && TERM ){                                \
19596     int c2 = ((*zIn++)<<8);                                           \
19597     c2 += (*zIn++);                                                   \
19598     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
19599   }                                                                   \
19600 }
19601
19602 /*
19603 ** Translate a single UTF-8 character.  Return the unicode value.
19604 **
19605 ** During translation, assume that the byte that zTerm points
19606 ** is a 0x00.
19607 **
19608 ** Write a pointer to the next unread byte back into *pzNext.
19609 **
19610 ** Notes On Invalid UTF-8:
19611 **
19612 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
19613 **     be encoded as a multi-byte character.  Any multi-byte character that
19614 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
19615 **
19616 **  *  This routine never allows a UTF16 surrogate value to be encoded.
19617 **     If a multi-byte character attempts to encode a value between
19618 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
19619 **
19620 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
19621 **     byte of a character are interpreted as single-byte characters
19622 **     and rendered as themselves even though they are technically
19623 **     invalid characters.
19624 **
19625 **  *  This routine accepts an infinite number of different UTF8 encodings
19626 **     for unicode values 0x80 and greater.  It do not change over-length
19627 **     encodings to 0xfffd as some systems recommend.
19628 */
19629 #define READ_UTF8(zIn, zTerm, c)                           \
19630   c = *(zIn++);                                            \
19631   if( c>=0xc0 ){                                           \
19632     c = sqlite3Utf8Trans1[c-0xc0];                         \
19633     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
19634       c = (c<<6) + (0x3f & *(zIn++));                      \
19635     }                                                      \
19636     if( c<0x80                                             \
19637         || (c&0xFFFFF800)==0xD800                          \
19638         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
19639   }
19640 SQLITE_PRIVATE int sqlite3Utf8Read(
19641   const unsigned char *zIn,       /* First byte of UTF-8 character */
19642   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
19643 ){
19644   int c;
19645
19646   /* Same as READ_UTF8() above but without the zTerm parameter.
19647   ** For this routine, we assume the UTF8 string is always zero-terminated.
19648   */
19649   c = *(zIn++);
19650   if( c>=0xc0 ){
19651     c = sqlite3Utf8Trans1[c-0xc0];
19652     while( (*zIn & 0xc0)==0x80 ){
19653       c = (c<<6) + (0x3f & *(zIn++));
19654     }
19655     if( c<0x80
19656         || (c&0xFFFFF800)==0xD800
19657         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
19658   }
19659   *pzNext = zIn;
19660   return c;
19661 }
19662
19663
19664
19665
19666 /*
19667 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
19668 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
19669 */ 
19670 /* #define TRANSLATE_TRACE 1 */
19671
19672 #ifndef SQLITE_OMIT_UTF16
19673 /*
19674 ** This routine transforms the internal text encoding used by pMem to
19675 ** desiredEnc. It is an error if the string is already of the desired
19676 ** encoding, or if *pMem does not contain a string value.
19677 */
19678 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
19679   int len;                    /* Maximum length of output string in bytes */
19680   unsigned char *zOut;                  /* Output buffer */
19681   unsigned char *zIn;                   /* Input iterator */
19682   unsigned char *zTerm;                 /* End of input */
19683   unsigned char *z;                     /* Output iterator */
19684   unsigned int c;
19685
19686   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
19687   assert( pMem->flags&MEM_Str );
19688   assert( pMem->enc!=desiredEnc );
19689   assert( pMem->enc!=0 );
19690   assert( pMem->n>=0 );
19691
19692 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
19693   {
19694     char zBuf[100];
19695     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
19696     fprintf(stderr, "INPUT:  %s\n", zBuf);
19697   }
19698 #endif
19699
19700   /* If the translation is between UTF-16 little and big endian, then 
19701   ** all that is required is to swap the byte order. This case is handled
19702   ** differently from the others.
19703   */
19704   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
19705     u8 temp;
19706     int rc;
19707     rc = sqlite3VdbeMemMakeWriteable(pMem);
19708     if( rc!=SQLITE_OK ){
19709       assert( rc==SQLITE_NOMEM );
19710       return SQLITE_NOMEM;
19711     }
19712     zIn = (u8*)pMem->z;
19713     zTerm = &zIn[pMem->n&~1];
19714     while( zIn<zTerm ){
19715       temp = *zIn;
19716       *zIn = *(zIn+1);
19717       zIn++;
19718       *zIn++ = temp;
19719     }
19720     pMem->enc = desiredEnc;
19721     goto translate_out;
19722   }
19723
19724   /* Set len to the maximum number of bytes required in the output buffer. */
19725   if( desiredEnc==SQLITE_UTF8 ){
19726     /* When converting from UTF-16, the maximum growth results from
19727     ** translating a 2-byte character to a 4-byte UTF-8 character.
19728     ** A single byte is required for the output string
19729     ** nul-terminator.
19730     */
19731     pMem->n &= ~1;
19732     len = pMem->n * 2 + 1;
19733   }else{
19734     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
19735     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
19736     ** character. Two bytes are required in the output buffer for the
19737     ** nul-terminator.
19738     */
19739     len = pMem->n * 2 + 2;
19740   }
19741
19742   /* Set zIn to point at the start of the input buffer and zTerm to point 1
19743   ** byte past the end.
19744   **
19745   ** Variable zOut is set to point at the output buffer, space obtained
19746   ** from sqlite3_malloc().
19747   */
19748   zIn = (u8*)pMem->z;
19749   zTerm = &zIn[pMem->n];
19750   zOut = sqlite3DbMallocRaw(pMem->db, len);
19751   if( !zOut ){
19752     return SQLITE_NOMEM;
19753   }
19754   z = zOut;
19755
19756   if( pMem->enc==SQLITE_UTF8 ){
19757     if( desiredEnc==SQLITE_UTF16LE ){
19758       /* UTF-8 -> UTF-16 Little-endian */
19759       while( zIn<zTerm ){
19760         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
19761         READ_UTF8(zIn, zTerm, c);
19762         WRITE_UTF16LE(z, c);
19763       }
19764     }else{
19765       assert( desiredEnc==SQLITE_UTF16BE );
19766       /* UTF-8 -> UTF-16 Big-endian */
19767       while( zIn<zTerm ){
19768         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
19769         READ_UTF8(zIn, zTerm, c);
19770         WRITE_UTF16BE(z, c);
19771       }
19772     }
19773     pMem->n = (int)(z - zOut);
19774     *z++ = 0;
19775   }else{
19776     assert( desiredEnc==SQLITE_UTF8 );
19777     if( pMem->enc==SQLITE_UTF16LE ){
19778       /* UTF-16 Little-endian -> UTF-8 */
19779       while( zIn<zTerm ){
19780         READ_UTF16LE(zIn, zIn<zTerm, c); 
19781         WRITE_UTF8(z, c);
19782       }
19783     }else{
19784       /* UTF-16 Big-endian -> UTF-8 */
19785       while( zIn<zTerm ){
19786         READ_UTF16BE(zIn, zIn<zTerm, c); 
19787         WRITE_UTF8(z, c);
19788       }
19789     }
19790     pMem->n = (int)(z - zOut);
19791   }
19792   *z = 0;
19793   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
19794
19795   sqlite3VdbeMemRelease(pMem);
19796   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
19797   pMem->enc = desiredEnc;
19798   pMem->flags |= (MEM_Term|MEM_Dyn);
19799   pMem->z = (char*)zOut;
19800   pMem->zMalloc = pMem->z;
19801
19802 translate_out:
19803 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
19804   {
19805     char zBuf[100];
19806     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
19807     fprintf(stderr, "OUTPUT: %s\n", zBuf);
19808   }
19809 #endif
19810   return SQLITE_OK;
19811 }
19812
19813 /*
19814 ** This routine checks for a byte-order mark at the beginning of the 
19815 ** UTF-16 string stored in *pMem. If one is present, it is removed and
19816 ** the encoding of the Mem adjusted. This routine does not do any
19817 ** byte-swapping, it just sets Mem.enc appropriately.
19818 **
19819 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
19820 ** changed by this function.
19821 */
19822 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
19823   int rc = SQLITE_OK;
19824   u8 bom = 0;
19825
19826   assert( pMem->n>=0 );
19827   if( pMem->n>1 ){
19828     u8 b1 = *(u8 *)pMem->z;
19829     u8 b2 = *(((u8 *)pMem->z) + 1);
19830     if( b1==0xFE && b2==0xFF ){
19831       bom = SQLITE_UTF16BE;
19832     }
19833     if( b1==0xFF && b2==0xFE ){
19834       bom = SQLITE_UTF16LE;
19835     }
19836   }
19837   
19838   if( bom ){
19839     rc = sqlite3VdbeMemMakeWriteable(pMem);
19840     if( rc==SQLITE_OK ){
19841       pMem->n -= 2;
19842       memmove(pMem->z, &pMem->z[2], pMem->n);
19843       pMem->z[pMem->n] = '\0';
19844       pMem->z[pMem->n+1] = '\0';
19845       pMem->flags |= MEM_Term;
19846       pMem->enc = bom;
19847     }
19848   }
19849   return rc;
19850 }
19851 #endif /* SQLITE_OMIT_UTF16 */
19852
19853 /*
19854 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
19855 ** return the number of unicode characters in pZ up to (but not including)
19856 ** the first 0x00 byte. If nByte is not less than zero, return the
19857 ** number of unicode characters in the first nByte of pZ (or up to 
19858 ** the first 0x00, whichever comes first).
19859 */
19860 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
19861   int r = 0;
19862   const u8 *z = (const u8*)zIn;
19863   const u8 *zTerm;
19864   if( nByte>=0 ){
19865     zTerm = &z[nByte];
19866   }else{
19867     zTerm = (const u8*)(-1);
19868   }
19869   assert( z<=zTerm );
19870   while( *z!=0 && z<zTerm ){
19871     SQLITE_SKIP_UTF8(z);
19872     r++;
19873   }
19874   return r;
19875 }
19876
19877 /* This test function is not currently used by the automated test-suite. 
19878 ** Hence it is only available in debug builds.
19879 */
19880 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
19881 /*
19882 ** Translate UTF-8 to UTF-8.
19883 **
19884 ** This has the effect of making sure that the string is well-formed
19885 ** UTF-8.  Miscoded characters are removed.
19886 **
19887 ** The translation is done in-place (since it is impossible for the
19888 ** correct UTF-8 encoding to be longer than a malformed encoding).
19889 */
19890 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
19891   unsigned char *zOut = zIn;
19892   unsigned char *zStart = zIn;
19893   u32 c;
19894
19895   while( zIn[0] ){
19896     c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
19897     if( c!=0xfffd ){
19898       WRITE_UTF8(zOut, c);
19899     }
19900   }
19901   *zOut = 0;
19902   return (int)(zOut - zStart);
19903 }
19904 #endif
19905
19906 #ifndef SQLITE_OMIT_UTF16
19907 /*
19908 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
19909 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
19910 ** be freed by the calling function.
19911 **
19912 ** NULL is returned if there is an allocation error.
19913 */
19914 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
19915   Mem m;
19916   memset(&m, 0, sizeof(m));
19917   m.db = db;
19918   sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
19919   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
19920   if( db->mallocFailed ){
19921     sqlite3VdbeMemRelease(&m);
19922     m.z = 0;
19923   }
19924   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
19925   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
19926   assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
19927   assert( m.z || db->mallocFailed );
19928   return m.z;
19929 }
19930
19931 /*
19932 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
19933 ** enc. A pointer to the new string is returned, and the value of *pnOut
19934 ** is set to the length of the returned string in bytes. The call should
19935 ** arrange to call sqlite3DbFree() on the returned pointer when it is
19936 ** no longer required.
19937 ** 
19938 ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
19939 ** flag set.
19940 */
19941 #ifdef SQLITE_ENABLE_STAT2
19942 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
19943   Mem m;
19944   memset(&m, 0, sizeof(m));
19945   m.db = db;
19946   sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
19947   if( sqlite3VdbeMemTranslate(&m, enc) ){
19948     assert( db->mallocFailed );
19949     return 0;
19950   }
19951   assert( m.z==m.zMalloc );
19952   *pnOut = m.n;
19953   return m.z;
19954 }
19955 #endif
19956
19957 /*
19958 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
19959 ** Return the number of bytes in the first nChar unicode characters
19960 ** in pZ.  nChar must be non-negative.
19961 */
19962 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
19963   int c;
19964   unsigned char const *z = zIn;
19965   int n = 0;
19966   
19967   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
19968     while( n<nChar ){
19969       READ_UTF16BE(z, 1, c);
19970       n++;
19971     }
19972   }else{
19973     while( n<nChar ){
19974       READ_UTF16LE(z, 1, c);
19975       n++;
19976     }
19977   }
19978   return (int)(z-(unsigned char const *)zIn);
19979 }
19980
19981 #if defined(SQLITE_TEST)
19982 /*
19983 ** This routine is called from the TCL test function "translate_selftest".
19984 ** It checks that the primitives for serializing and deserializing
19985 ** characters in each encoding are inverses of each other.
19986 */
19987 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
19988   unsigned int i, t;
19989   unsigned char zBuf[20];
19990   unsigned char *z;
19991   int n;
19992   unsigned int c;
19993
19994   for(i=0; i<0x00110000; i++){
19995     z = zBuf;
19996     WRITE_UTF8(z, i);
19997     n = (int)(z-zBuf);
19998     assert( n>0 && n<=4 );
19999     z[0] = 0;
20000     z = zBuf;
20001     c = sqlite3Utf8Read(z, (const u8**)&z);
20002     t = i;
20003     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
20004     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
20005     assert( c==t );
20006     assert( (z-zBuf)==n );
20007   }
20008   for(i=0; i<0x00110000; i++){
20009     if( i>=0xD800 && i<0xE000 ) continue;
20010     z = zBuf;
20011     WRITE_UTF16LE(z, i);
20012     n = (int)(z-zBuf);
20013     assert( n>0 && n<=4 );
20014     z[0] = 0;
20015     z = zBuf;
20016     READ_UTF16LE(z, 1, c);
20017     assert( c==i );
20018     assert( (z-zBuf)==n );
20019   }
20020   for(i=0; i<0x00110000; i++){
20021     if( i>=0xD800 && i<0xE000 ) continue;
20022     z = zBuf;
20023     WRITE_UTF16BE(z, i);
20024     n = (int)(z-zBuf);
20025     assert( n>0 && n<=4 );
20026     z[0] = 0;
20027     z = zBuf;
20028     READ_UTF16BE(z, 1, c);
20029     assert( c==i );
20030     assert( (z-zBuf)==n );
20031   }
20032 }
20033 #endif /* SQLITE_TEST */
20034 #endif /* SQLITE_OMIT_UTF16 */
20035
20036 /************** End of utf.c *************************************************/
20037 /************** Begin file util.c ********************************************/
20038 /*
20039 ** 2001 September 15
20040 **
20041 ** The author disclaims copyright to this source code.  In place of
20042 ** a legal notice, here is a blessing:
20043 **
20044 **    May you do good and not evil.
20045 **    May you find forgiveness for yourself and forgive others.
20046 **    May you share freely, never taking more than you give.
20047 **
20048 *************************************************************************
20049 ** Utility functions used throughout sqlite.
20050 **
20051 ** This file contains functions for allocating memory, comparing
20052 ** strings, and stuff like that.
20053 **
20054 */
20055 #ifdef SQLITE_HAVE_ISNAN
20056 # include <math.h>
20057 #endif
20058
20059 /*
20060 ** Routine needed to support the testcase() macro.
20061 */
20062 #ifdef SQLITE_COVERAGE_TEST
20063 SQLITE_PRIVATE void sqlite3Coverage(int x){
20064   static int dummy = 0;
20065   dummy += x;
20066 }
20067 #endif
20068
20069 #ifndef SQLITE_OMIT_FLOATING_POINT
20070 /*
20071 ** Return true if the floating point value is Not a Number (NaN).
20072 **
20073 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
20074 ** Otherwise, we have our own implementation that works on most systems.
20075 */
20076 SQLITE_PRIVATE int sqlite3IsNaN(double x){
20077   int rc;   /* The value return */
20078 #if !defined(SQLITE_HAVE_ISNAN)
20079   /*
20080   ** Systems that support the isnan() library function should probably
20081   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
20082   ** found that many systems do not have a working isnan() function so
20083   ** this implementation is provided as an alternative.
20084   **
20085   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
20086   ** On the other hand, the use of -ffast-math comes with the following
20087   ** warning:
20088   **
20089   **      This option [-ffast-math] should never be turned on by any
20090   **      -O option since it can result in incorrect output for programs
20091   **      which depend on an exact implementation of IEEE or ISO 
20092   **      rules/specifications for math functions.
20093   **
20094   ** Under MSVC, this NaN test may fail if compiled with a floating-
20095   ** point precision mode other than /fp:precise.  From the MSDN 
20096   ** documentation:
20097   **
20098   **      The compiler [with /fp:precise] will properly handle comparisons 
20099   **      involving NaN. For example, x != x evaluates to true if x is NaN 
20100   **      ...
20101   */
20102 #ifdef __FAST_MATH__
20103 # error SQLite will not work correctly with the -ffast-math option of GCC.
20104 #endif
20105   volatile double y = x;
20106   volatile double z = y;
20107   rc = (y!=z);
20108 #else  /* if defined(SQLITE_HAVE_ISNAN) */
20109   rc = isnan(x);
20110 #endif /* SQLITE_HAVE_ISNAN */
20111   testcase( rc );
20112   return rc;
20113 }
20114 #endif /* SQLITE_OMIT_FLOATING_POINT */
20115
20116 /*
20117 ** Compute a string length that is limited to what can be stored in
20118 ** lower 30 bits of a 32-bit signed integer.
20119 **
20120 ** The value returned will never be negative.  Nor will it ever be greater
20121 ** than the actual length of the string.  For very long strings (greater
20122 ** than 1GiB) the value returned might be less than the true string length.
20123 */
20124 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
20125   const char *z2 = z;
20126   if( z==0 ) return 0;
20127   while( *z2 ){ z2++; }
20128   return 0x3fffffff & (int)(z2 - z);
20129 }
20130
20131 /*
20132 ** Set the most recent error code and error string for the sqlite
20133 ** handle "db". The error code is set to "err_code".
20134 **
20135 ** If it is not NULL, string zFormat specifies the format of the
20136 ** error string in the style of the printf functions: The following
20137 ** format characters are allowed:
20138 **
20139 **      %s      Insert a string
20140 **      %z      A string that should be freed after use
20141 **      %d      Insert an integer
20142 **      %T      Insert a token
20143 **      %S      Insert the first element of a SrcList
20144 **
20145 ** zFormat and any string tokens that follow it are assumed to be
20146 ** encoded in UTF-8.
20147 **
20148 ** To clear the most recent error for sqlite handle "db", sqlite3Error
20149 ** should be called with err_code set to SQLITE_OK and zFormat set
20150 ** to NULL.
20151 */
20152 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
20153   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
20154     db->errCode = err_code;
20155     if( zFormat ){
20156       char *z;
20157       va_list ap;
20158       va_start(ap, zFormat);
20159       z = sqlite3VMPrintf(db, zFormat, ap);
20160       va_end(ap);
20161       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
20162     }else{
20163       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
20164     }
20165   }
20166 }
20167
20168 /*
20169 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
20170 ** The following formatting characters are allowed:
20171 **
20172 **      %s      Insert a string
20173 **      %z      A string that should be freed after use
20174 **      %d      Insert an integer
20175 **      %T      Insert a token
20176 **      %S      Insert the first element of a SrcList
20177 **
20178 ** This function should be used to report any error that occurs whilst
20179 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
20180 ** last thing the sqlite3_prepare() function does is copy the error
20181 ** stored by this function into the database handle using sqlite3Error().
20182 ** Function sqlite3Error() should be used during statement execution
20183 ** (sqlite3_step() etc.).
20184 */
20185 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
20186   char *zMsg;
20187   va_list ap;
20188   sqlite3 *db = pParse->db;
20189   va_start(ap, zFormat);
20190   zMsg = sqlite3VMPrintf(db, zFormat, ap);
20191   va_end(ap);
20192   if( db->suppressErr ){
20193     sqlite3DbFree(db, zMsg);
20194   }else{
20195     pParse->nErr++;
20196     sqlite3DbFree(db, pParse->zErrMsg);
20197     pParse->zErrMsg = zMsg;
20198     pParse->rc = SQLITE_ERROR;
20199   }
20200 }
20201
20202 /*
20203 ** Convert an SQL-style quoted string into a normal string by removing
20204 ** the quote characters.  The conversion is done in-place.  If the
20205 ** input does not begin with a quote character, then this routine
20206 ** is a no-op.
20207 **
20208 ** The input string must be zero-terminated.  A new zero-terminator
20209 ** is added to the dequoted string.
20210 **
20211 ** The return value is -1 if no dequoting occurs or the length of the
20212 ** dequoted string, exclusive of the zero terminator, if dequoting does
20213 ** occur.
20214 **
20215 ** 2002-Feb-14: This routine is extended to remove MS-Access style
20216 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
20217 ** "a-b-c".
20218 */
20219 SQLITE_PRIVATE int sqlite3Dequote(char *z){
20220   char quote;
20221   int i, j;
20222   if( z==0 ) return -1;
20223   quote = z[0];
20224   switch( quote ){
20225     case '\'':  break;
20226     case '"':   break;
20227     case '`':   break;                /* For MySQL compatibility */
20228     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
20229     default:    return -1;
20230   }
20231   for(i=1, j=0; ALWAYS(z[i]); i++){
20232     if( z[i]==quote ){
20233       if( z[i+1]==quote ){
20234         z[j++] = quote;
20235         i++;
20236       }else{
20237         break;
20238       }
20239     }else{
20240       z[j++] = z[i];
20241     }
20242   }
20243   z[j] = 0;
20244   return j;
20245 }
20246
20247 /* Convenient short-hand */
20248 #define UpperToLower sqlite3UpperToLower
20249
20250 /*
20251 ** Some systems have stricmp().  Others have strcasecmp().  Because
20252 ** there is no consistency, we will define our own.
20253 **
20254 ** IMPLEMENTATION-OF: R-20522-24639 The sqlite3_strnicmp() API allows
20255 ** applications and extensions to compare the contents of two buffers
20256 ** containing UTF-8 strings in a case-independent fashion, using the same
20257 ** definition of case independence that SQLite uses internally when
20258 ** comparing identifiers.
20259 */
20260 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
20261   register unsigned char *a, *b;
20262   a = (unsigned char *)zLeft;
20263   b = (unsigned char *)zRight;
20264   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
20265   return UpperToLower[*a] - UpperToLower[*b];
20266 }
20267 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
20268   register unsigned char *a, *b;
20269   a = (unsigned char *)zLeft;
20270   b = (unsigned char *)zRight;
20271   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
20272   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
20273 }
20274
20275 /*
20276 ** The string z[] is an text representation of a real number.
20277 ** Convert this string to a double and write it into *pResult.
20278 **
20279 ** The string z[] is length bytes in length (bytes, not characters) and
20280 ** uses the encoding enc.  The string is not necessarily zero-terminated.
20281 **
20282 ** Return TRUE if the result is a valid real number (or integer) and FALSE
20283 ** if the string is empty or contains extraneous text.  Valid numbers
20284 ** are in one of these formats:
20285 **
20286 **    [+-]digits[E[+-]digits]
20287 **    [+-]digits.[digits][E[+-]digits]
20288 **    [+-].digits[E[+-]digits]
20289 **
20290 ** Leading and trailing whitespace is ignored for the purpose of determining
20291 ** validity.
20292 **
20293 ** If some prefix of the input string is a valid number, this routine
20294 ** returns FALSE but it still converts the prefix and writes the result
20295 ** into *pResult.
20296 */
20297 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
20298 #ifndef SQLITE_OMIT_FLOATING_POINT
20299   int incr = (enc==SQLITE_UTF8?1:2);
20300   const char *zEnd = z + length;
20301   /* sign * significand * (10 ^ (esign * exponent)) */
20302   int sign = 1;    /* sign of significand */
20303   i64 s = 0;       /* significand */
20304   int d = 0;       /* adjust exponent for shifting decimal point */
20305   int esign = 1;   /* sign of exponent */
20306   int e = 0;       /* exponent */
20307   int eValid = 1;  /* True exponent is either not used or is well-formed */
20308   double result;
20309   int nDigits = 0;
20310
20311   *pResult = 0.0;   /* Default return value, in case of an error */
20312
20313   if( enc==SQLITE_UTF16BE ) z++;
20314
20315   /* skip leading spaces */
20316   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
20317   if( z>=zEnd ) return 0;
20318
20319   /* get sign of significand */
20320   if( *z=='-' ){
20321     sign = -1;
20322     z+=incr;
20323   }else if( *z=='+' ){
20324     z+=incr;
20325   }
20326
20327   /* skip leading zeroes */
20328   while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
20329
20330   /* copy max significant digits to significand */
20331   while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
20332     s = s*10 + (*z - '0');
20333     z+=incr, nDigits++;
20334   }
20335
20336   /* skip non-significant significand digits
20337   ** (increase exponent by d to shift decimal left) */
20338   while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
20339   if( z>=zEnd ) goto do_atof_calc;
20340
20341   /* if decimal point is present */
20342   if( *z=='.' ){
20343     z+=incr;
20344     /* copy digits from after decimal to significand
20345     ** (decrease exponent by d to shift decimal right) */
20346     while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
20347       s = s*10 + (*z - '0');
20348       z+=incr, nDigits++, d--;
20349     }
20350     /* skip non-significant digits */
20351     while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
20352   }
20353   if( z>=zEnd ) goto do_atof_calc;
20354
20355   /* if exponent is present */
20356   if( *z=='e' || *z=='E' ){
20357     z+=incr;
20358     eValid = 0;
20359     if( z>=zEnd ) goto do_atof_calc;
20360     /* get sign of exponent */
20361     if( *z=='-' ){
20362       esign = -1;
20363       z+=incr;
20364     }else if( *z=='+' ){
20365       z+=incr;
20366     }
20367     /* copy digits to exponent */
20368     while( z<zEnd && sqlite3Isdigit(*z) ){
20369       e = e*10 + (*z - '0');
20370       z+=incr;
20371       eValid = 1;
20372     }
20373   }
20374
20375   /* skip trailing spaces */
20376   if( nDigits && eValid ){
20377     while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
20378   }
20379
20380 do_atof_calc:
20381   /* adjust exponent by d, and update sign */
20382   e = (e*esign) + d;
20383   if( e<0 ) {
20384     esign = -1;
20385     e *= -1;
20386   } else {
20387     esign = 1;
20388   }
20389
20390   /* if 0 significand */
20391   if( !s ) {
20392     /* In the IEEE 754 standard, zero is signed.
20393     ** Add the sign if we've seen at least one digit */
20394     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
20395   } else {
20396     /* attempt to reduce exponent */
20397     if( esign>0 ){
20398       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
20399     }else{
20400       while( !(s%10) && e>0 ) e--,s/=10;
20401     }
20402
20403     /* adjust the sign of significand */
20404     s = sign<0 ? -s : s;
20405
20406     /* if exponent, scale significand as appropriate
20407     ** and store in result. */
20408     if( e ){
20409       double scale = 1.0;
20410       /* attempt to handle extremely small/large numbers better */
20411       if( e>307 && e<342 ){
20412         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
20413         if( esign<0 ){
20414           result = s / scale;
20415           result /= 1.0e+308;
20416         }else{
20417           result = s * scale;
20418           result *= 1.0e+308;
20419         }
20420       }else{
20421         /* 1.0e+22 is the largest power of 10 than can be 
20422         ** represented exactly. */
20423         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
20424         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
20425         if( esign<0 ){
20426           result = s / scale;
20427         }else{
20428           result = s * scale;
20429         }
20430       }
20431     } else {
20432       result = (double)s;
20433     }
20434   }
20435
20436   /* store the result */
20437   *pResult = result;
20438
20439   /* return true if number and no extra non-whitespace chracters after */
20440   return z>=zEnd && nDigits>0 && eValid;
20441 #else
20442   return !sqlite3Atoi64(z, pResult, length, enc);
20443 #endif /* SQLITE_OMIT_FLOATING_POINT */
20444 }
20445
20446 /*
20447 ** Compare the 19-character string zNum against the text representation
20448 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
20449 ** if zNum is less than, equal to, or greater than the string.
20450 ** Note that zNum must contain exactly 19 characters.
20451 **
20452 ** Unlike memcmp() this routine is guaranteed to return the difference
20453 ** in the values of the last digit if the only difference is in the
20454 ** last digit.  So, for example,
20455 **
20456 **      compare2pow63("9223372036854775800", 1)
20457 **
20458 ** will return -8.
20459 */
20460 static int compare2pow63(const char *zNum, int incr){
20461   int c = 0;
20462   int i;
20463                     /* 012345678901234567 */
20464   const char *pow63 = "922337203685477580";
20465   for(i=0; c==0 && i<18; i++){
20466     c = (zNum[i*incr]-pow63[i])*10;
20467   }
20468   if( c==0 ){
20469     c = zNum[18*incr] - '8';
20470     testcase( c==(-1) );
20471     testcase( c==0 );
20472     testcase( c==(+1) );
20473   }
20474   return c;
20475 }
20476
20477
20478 /*
20479 ** Convert zNum to a 64-bit signed integer and write
20480 ** the value of the integer into *pNum.
20481 ** If zNum is exactly 9223372036854665808, return 2.
20482 ** This is a special case as the context will determine
20483 ** if it is too big (used as a negative).
20484 ** If zNum is not an integer or is an integer that 
20485 ** is too large to be expressed with 64 bits,
20486 ** then return 1.  Otherwise return 0.
20487 **
20488 ** length is the number of bytes in the string (bytes, not characters).
20489 ** The string is not necessarily zero-terminated.  The encoding is
20490 ** given by enc.
20491 */
20492 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
20493   int incr = (enc==SQLITE_UTF8?1:2);
20494   i64 v = 0;
20495   int neg = 0; /* assume positive */
20496   int i;
20497   int c = 0;
20498   const char *zStart;
20499   const char *zEnd = zNum + length;
20500   if( enc==SQLITE_UTF16BE ) zNum++;
20501   while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
20502   if( zNum>=zEnd ) goto do_atoi_calc;
20503   if( *zNum=='-' ){
20504     neg = 1;
20505     zNum+=incr;
20506   }else if( *zNum=='+' ){
20507     zNum+=incr;
20508   }
20509 do_atoi_calc:
20510   zStart = zNum;
20511   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
20512   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
20513     v = v*10 + c - '0';
20514   }
20515   *pNum = neg ? -v : v;
20516   testcase( i==18 );
20517   testcase( i==19 );
20518   testcase( i==20 );
20519   if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr ){
20520     /* zNum is empty or contains non-numeric text or is longer
20521     ** than 19 digits (thus guaranteeing that it is too large) */
20522     return 1;
20523   }else if( i<19*incr ){
20524     /* Less than 19 digits, so we know that it fits in 64 bits */
20525     return 0;
20526   }else{
20527     /* 19-digit numbers must be no larger than 9223372036854775807 if positive
20528     ** or 9223372036854775808 if negative.  Note that 9223372036854665808
20529     ** is 2^63. Return 1 if to large */
20530     c=compare2pow63(zNum, incr);
20531     if( c==0 && neg==0 ) return 2; /* too big, exactly 9223372036854665808 */
20532     return c<neg ? 0 : 1;
20533   }
20534 }
20535
20536 /*
20537 ** If zNum represents an integer that will fit in 32-bits, then set
20538 ** *pValue to that integer and return true.  Otherwise return false.
20539 **
20540 ** Any non-numeric characters that following zNum are ignored.
20541 ** This is different from sqlite3Atoi64() which requires the
20542 ** input number to be zero-terminated.
20543 */
20544 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
20545   sqlite_int64 v = 0;
20546   int i, c;
20547   int neg = 0;
20548   if( zNum[0]=='-' ){
20549     neg = 1;
20550     zNum++;
20551   }else if( zNum[0]=='+' ){
20552     zNum++;
20553   }
20554   while( zNum[0]=='0' ) zNum++;
20555   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
20556     v = v*10 + c;
20557   }
20558
20559   /* The longest decimal representation of a 32 bit integer is 10 digits:
20560   **
20561   **             1234567890
20562   **     2^31 -> 2147483648
20563   */
20564   testcase( i==10 );
20565   if( i>10 ){
20566     return 0;
20567   }
20568   testcase( v-neg==2147483647 );
20569   if( v-neg>2147483647 ){
20570     return 0;
20571   }
20572   if( neg ){
20573     v = -v;
20574   }
20575   *pValue = (int)v;
20576   return 1;
20577 }
20578
20579 /*
20580 ** Return a 32-bit integer value extracted from a string.  If the
20581 ** string is not an integer, just return 0.
20582 */
20583 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
20584   int x = 0;
20585   if( z ) sqlite3GetInt32(z, &x);
20586   return x;
20587 }
20588
20589 /*
20590 ** The variable-length integer encoding is as follows:
20591 **
20592 ** KEY:
20593 **         A = 0xxxxxxx    7 bits of data and one flag bit
20594 **         B = 1xxxxxxx    7 bits of data and one flag bit
20595 **         C = xxxxxxxx    8 bits of data
20596 **
20597 **  7 bits - A
20598 ** 14 bits - BA
20599 ** 21 bits - BBA
20600 ** 28 bits - BBBA
20601 ** 35 bits - BBBBA
20602 ** 42 bits - BBBBBA
20603 ** 49 bits - BBBBBBA
20604 ** 56 bits - BBBBBBBA
20605 ** 64 bits - BBBBBBBBC
20606 */
20607
20608 /*
20609 ** Write a 64-bit variable-length integer to memory starting at p[0].
20610 ** The length of data write will be between 1 and 9 bytes.  The number
20611 ** of bytes written is returned.
20612 **
20613 ** A variable-length integer consists of the lower 7 bits of each byte
20614 ** for all bytes that have the 8th bit set and one byte with the 8th
20615 ** bit clear.  Except, if we get to the 9th byte, it stores the full
20616 ** 8 bits and is the last byte.
20617 */
20618 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
20619   int i, j, n;
20620   u8 buf[10];
20621   if( v & (((u64)0xff000000)<<32) ){
20622     p[8] = (u8)v;
20623     v >>= 8;
20624     for(i=7; i>=0; i--){
20625       p[i] = (u8)((v & 0x7f) | 0x80);
20626       v >>= 7;
20627     }
20628     return 9;
20629   }    
20630   n = 0;
20631   do{
20632     buf[n++] = (u8)((v & 0x7f) | 0x80);
20633     v >>= 7;
20634   }while( v!=0 );
20635   buf[0] &= 0x7f;
20636   assert( n<=9 );
20637   for(i=0, j=n-1; j>=0; j--, i++){
20638     p[i] = buf[j];
20639   }
20640   return n;
20641 }
20642
20643 /*
20644 ** This routine is a faster version of sqlite3PutVarint() that only
20645 ** works for 32-bit positive integers and which is optimized for
20646 ** the common case of small integers.  A MACRO version, putVarint32,
20647 ** is provided which inlines the single-byte case.  All code should use
20648 ** the MACRO version as this function assumes the single-byte case has
20649 ** already been handled.
20650 */
20651 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
20652 #ifndef putVarint32
20653   if( (v & ~0x7f)==0 ){
20654     p[0] = v;
20655     return 1;
20656   }
20657 #endif
20658   if( (v & ~0x3fff)==0 ){
20659     p[0] = (u8)((v>>7) | 0x80);
20660     p[1] = (u8)(v & 0x7f);
20661     return 2;
20662   }
20663   return sqlite3PutVarint(p, v);
20664 }
20665
20666 /*
20667 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
20668 ** are defined here rather than simply putting the constant expressions
20669 ** inline in order to work around bugs in the RVT compiler.
20670 **
20671 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
20672 **
20673 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
20674 */
20675 #define SLOT_2_0     0x001fc07f
20676 #define SLOT_4_2_0   0xf01fc07f
20677
20678
20679 /*
20680 ** Read a 64-bit variable-length integer from memory starting at p[0].
20681 ** Return the number of bytes read.  The value is stored in *v.
20682 */
20683 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
20684   u32 a,b,s;
20685
20686   a = *p;
20687   /* a: p0 (unmasked) */
20688   if (!(a&0x80))
20689   {
20690     *v = a;
20691     return 1;
20692   }
20693
20694   p++;
20695   b = *p;
20696   /* b: p1 (unmasked) */
20697   if (!(b&0x80))
20698   {
20699     a &= 0x7f;
20700     a = a<<7;
20701     a |= b;
20702     *v = a;
20703     return 2;
20704   }
20705
20706   /* Verify that constants are precomputed correctly */
20707   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
20708   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
20709
20710   p++;
20711   a = a<<14;
20712   a |= *p;
20713   /* a: p0<<14 | p2 (unmasked) */
20714   if (!(a&0x80))
20715   {
20716     a &= SLOT_2_0;
20717     b &= 0x7f;
20718     b = b<<7;
20719     a |= b;
20720     *v = a;
20721     return 3;
20722   }
20723
20724   /* CSE1 from below */
20725   a &= SLOT_2_0;
20726   p++;
20727   b = b<<14;
20728   b |= *p;
20729   /* b: p1<<14 | p3 (unmasked) */
20730   if (!(b&0x80))
20731   {
20732     b &= SLOT_2_0;
20733     /* moved CSE1 up */
20734     /* a &= (0x7f<<14)|(0x7f); */
20735     a = a<<7;
20736     a |= b;
20737     *v = a;
20738     return 4;
20739   }
20740
20741   /* a: p0<<14 | p2 (masked) */
20742   /* b: p1<<14 | p3 (unmasked) */
20743   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20744   /* moved CSE1 up */
20745   /* a &= (0x7f<<14)|(0x7f); */
20746   b &= SLOT_2_0;
20747   s = a;
20748   /* s: p0<<14 | p2 (masked) */
20749
20750   p++;
20751   a = a<<14;
20752   a |= *p;
20753   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
20754   if (!(a&0x80))
20755   {
20756     /* we can skip these cause they were (effectively) done above in calc'ing s */
20757     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
20758     /* b &= (0x7f<<14)|(0x7f); */
20759     b = b<<7;
20760     a |= b;
20761     s = s>>18;
20762     *v = ((u64)s)<<32 | a;
20763     return 5;
20764   }
20765
20766   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20767   s = s<<7;
20768   s |= b;
20769   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20770
20771   p++;
20772   b = b<<14;
20773   b |= *p;
20774   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
20775   if (!(b&0x80))
20776   {
20777     /* we can skip this cause it was (effectively) done above in calc'ing s */
20778     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
20779     a &= SLOT_2_0;
20780     a = a<<7;
20781     a |= b;
20782     s = s>>18;
20783     *v = ((u64)s)<<32 | a;
20784     return 6;
20785   }
20786
20787   p++;
20788   a = a<<14;
20789   a |= *p;
20790   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
20791   if (!(a&0x80))
20792   {
20793     a &= SLOT_4_2_0;
20794     b &= SLOT_2_0;
20795     b = b<<7;
20796     a |= b;
20797     s = s>>11;
20798     *v = ((u64)s)<<32 | a;
20799     return 7;
20800   }
20801
20802   /* CSE2 from below */
20803   a &= SLOT_2_0;
20804   p++;
20805   b = b<<14;
20806   b |= *p;
20807   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
20808   if (!(b&0x80))
20809   {
20810     b &= SLOT_4_2_0;
20811     /* moved CSE2 up */
20812     /* a &= (0x7f<<14)|(0x7f); */
20813     a = a<<7;
20814     a |= b;
20815     s = s>>4;
20816     *v = ((u64)s)<<32 | a;
20817     return 8;
20818   }
20819
20820   p++;
20821   a = a<<15;
20822   a |= *p;
20823   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
20824
20825   /* moved CSE2 up */
20826   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
20827   b &= SLOT_2_0;
20828   b = b<<8;
20829   a |= b;
20830
20831   s = s<<4;
20832   b = p[-4];
20833   b &= 0x7f;
20834   b = b>>3;
20835   s |= b;
20836
20837   *v = ((u64)s)<<32 | a;
20838
20839   return 9;
20840 }
20841
20842 /*
20843 ** Read a 32-bit variable-length integer from memory starting at p[0].
20844 ** Return the number of bytes read.  The value is stored in *v.
20845 **
20846 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
20847 ** integer, then set *v to 0xffffffff.
20848 **
20849 ** A MACRO version, getVarint32, is provided which inlines the 
20850 ** single-byte case.  All code should use the MACRO version as 
20851 ** this function assumes the single-byte case has already been handled.
20852 */
20853 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
20854   u32 a,b;
20855
20856   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
20857   ** by the getVarin32() macro */
20858   a = *p;
20859   /* a: p0 (unmasked) */
20860 #ifndef getVarint32
20861   if (!(a&0x80))
20862   {
20863     /* Values between 0 and 127 */
20864     *v = a;
20865     return 1;
20866   }
20867 #endif
20868
20869   /* The 2-byte case */
20870   p++;
20871   b = *p;
20872   /* b: p1 (unmasked) */
20873   if (!(b&0x80))
20874   {
20875     /* Values between 128 and 16383 */
20876     a &= 0x7f;
20877     a = a<<7;
20878     *v = a | b;
20879     return 2;
20880   }
20881
20882   /* The 3-byte case */
20883   p++;
20884   a = a<<14;
20885   a |= *p;
20886   /* a: p0<<14 | p2 (unmasked) */
20887   if (!(a&0x80))
20888   {
20889     /* Values between 16384 and 2097151 */
20890     a &= (0x7f<<14)|(0x7f);
20891     b &= 0x7f;
20892     b = b<<7;
20893     *v = a | b;
20894     return 3;
20895   }
20896
20897   /* A 32-bit varint is used to store size information in btrees.
20898   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
20899   ** A 3-byte varint is sufficient, for example, to record the size
20900   ** of a 1048569-byte BLOB or string.
20901   **
20902   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
20903   ** rare larger cases can be handled by the slower 64-bit varint
20904   ** routine.
20905   */
20906 #if 1
20907   {
20908     u64 v64;
20909     u8 n;
20910
20911     p -= 2;
20912     n = sqlite3GetVarint(p, &v64);
20913     assert( n>3 && n<=9 );
20914     if( (v64 & SQLITE_MAX_U32)!=v64 ){
20915       *v = 0xffffffff;
20916     }else{
20917       *v = (u32)v64;
20918     }
20919     return n;
20920   }
20921
20922 #else
20923   /* For following code (kept for historical record only) shows an
20924   ** unrolling for the 3- and 4-byte varint cases.  This code is
20925   ** slightly faster, but it is also larger and much harder to test.
20926   */
20927   p++;
20928   b = b<<14;
20929   b |= *p;
20930   /* b: p1<<14 | p3 (unmasked) */
20931   if (!(b&0x80))
20932   {
20933     /* Values between 2097152 and 268435455 */
20934     b &= (0x7f<<14)|(0x7f);
20935     a &= (0x7f<<14)|(0x7f);
20936     a = a<<7;
20937     *v = a | b;
20938     return 4;
20939   }
20940
20941   p++;
20942   a = a<<14;
20943   a |= *p;
20944   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
20945   if (!(a&0x80))
20946   {
20947     /* Values  between 268435456 and 34359738367 */
20948     a &= SLOT_4_2_0;
20949     b &= SLOT_4_2_0;
20950     b = b<<7;
20951     *v = a | b;
20952     return 5;
20953   }
20954
20955   /* We can only reach this point when reading a corrupt database
20956   ** file.  In that case we are not in any hurry.  Use the (relatively
20957   ** slow) general-purpose sqlite3GetVarint() routine to extract the
20958   ** value. */
20959   {
20960     u64 v64;
20961     u8 n;
20962
20963     p -= 4;
20964     n = sqlite3GetVarint(p, &v64);
20965     assert( n>5 && n<=9 );
20966     *v = (u32)v64;
20967     return n;
20968   }
20969 #endif
20970 }
20971
20972 /*
20973 ** Return the number of bytes that will be needed to store the given
20974 ** 64-bit integer.
20975 */
20976 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
20977   int i = 0;
20978   do{
20979     i++;
20980     v >>= 7;
20981   }while( v!=0 && ALWAYS(i<9) );
20982   return i;
20983 }
20984
20985
20986 /*
20987 ** Read or write a four-byte big-endian integer value.
20988 */
20989 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
20990   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
20991 }
20992 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
20993   p[0] = (u8)(v>>24);
20994   p[1] = (u8)(v>>16);
20995   p[2] = (u8)(v>>8);
20996   p[3] = (u8)v;
20997 }
20998
20999
21000
21001 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
21002 /*
21003 ** Translate a single byte of Hex into an integer.
21004 ** This routine only works if h really is a valid hexadecimal
21005 ** character:  0..9a..fA..F
21006 */
21007 static u8 hexToInt(int h){
21008   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
21009 #ifdef SQLITE_ASCII
21010   h += 9*(1&(h>>6));
21011 #endif
21012 #ifdef SQLITE_EBCDIC
21013   h += 9*(1&~(h>>4));
21014 #endif
21015   return (u8)(h & 0xf);
21016 }
21017 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
21018
21019 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
21020 /*
21021 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
21022 ** value.  Return a pointer to its binary value.  Space to hold the
21023 ** binary value has been obtained from malloc and must be freed by
21024 ** the calling routine.
21025 */
21026 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
21027   char *zBlob;
21028   int i;
21029
21030   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
21031   n--;
21032   if( zBlob ){
21033     for(i=0; i<n; i+=2){
21034       zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
21035     }
21036     zBlob[i/2] = 0;
21037   }
21038   return zBlob;
21039 }
21040 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
21041
21042 /*
21043 ** Log an error that is an API call on a connection pointer that should
21044 ** not have been used.  The "type" of connection pointer is given as the
21045 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
21046 */
21047 static void logBadConnection(const char *zType){
21048   sqlite3_log(SQLITE_MISUSE, 
21049      "API call with %s database connection pointer",
21050      zType
21051   );
21052 }
21053
21054 /*
21055 ** Check to make sure we have a valid db pointer.  This test is not
21056 ** foolproof but it does provide some measure of protection against
21057 ** misuse of the interface such as passing in db pointers that are
21058 ** NULL or which have been previously closed.  If this routine returns
21059 ** 1 it means that the db pointer is valid and 0 if it should not be
21060 ** dereferenced for any reason.  The calling function should invoke
21061 ** SQLITE_MISUSE immediately.
21062 **
21063 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
21064 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
21065 ** open properly and is not fit for general use but which can be
21066 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
21067 */
21068 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
21069   u32 magic;
21070   if( db==0 ){
21071     logBadConnection("NULL");
21072     return 0;
21073   }
21074   magic = db->magic;
21075   if( magic!=SQLITE_MAGIC_OPEN ){
21076     if( sqlite3SafetyCheckSickOrOk(db) ){
21077       testcase( sqlite3GlobalConfig.xLog!=0 );
21078       logBadConnection("unopened");
21079     }
21080     return 0;
21081   }else{
21082     return 1;
21083   }
21084 }
21085 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
21086   u32 magic;
21087   magic = db->magic;
21088   if( magic!=SQLITE_MAGIC_SICK &&
21089       magic!=SQLITE_MAGIC_OPEN &&
21090       magic!=SQLITE_MAGIC_BUSY ){
21091     testcase( sqlite3GlobalConfig.xLog!=0 );
21092     logBadConnection("invalid");
21093     return 0;
21094   }else{
21095     return 1;
21096   }
21097 }
21098
21099 /************** End of util.c ************************************************/
21100 /************** Begin file hash.c ********************************************/
21101 /*
21102 ** 2001 September 22
21103 **
21104 ** The author disclaims copyright to this source code.  In place of
21105 ** a legal notice, here is a blessing:
21106 **
21107 **    May you do good and not evil.
21108 **    May you find forgiveness for yourself and forgive others.
21109 **    May you share freely, never taking more than you give.
21110 **
21111 *************************************************************************
21112 ** This is the implementation of generic hash-tables
21113 ** used in SQLite.
21114 */
21115
21116 /* Turn bulk memory into a hash table object by initializing the
21117 ** fields of the Hash structure.
21118 **
21119 ** "pNew" is a pointer to the hash table that is to be initialized.
21120 */
21121 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
21122   assert( pNew!=0 );
21123   pNew->first = 0;
21124   pNew->count = 0;
21125   pNew->htsize = 0;
21126   pNew->ht = 0;
21127 }
21128
21129 /* Remove all entries from a hash table.  Reclaim all memory.
21130 ** Call this routine to delete a hash table or to reset a hash table
21131 ** to the empty state.
21132 */
21133 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
21134   HashElem *elem;         /* For looping over all elements of the table */
21135
21136   assert( pH!=0 );
21137   elem = pH->first;
21138   pH->first = 0;
21139   sqlite3_free(pH->ht);
21140   pH->ht = 0;
21141   pH->htsize = 0;
21142   while( elem ){
21143     HashElem *next_elem = elem->next;
21144     sqlite3_free(elem);
21145     elem = next_elem;
21146   }
21147   pH->count = 0;
21148 }
21149
21150 /*
21151 ** The hashing function.
21152 */
21153 static unsigned int strHash(const char *z, int nKey){
21154   int h = 0;
21155   assert( nKey>=0 );
21156   while( nKey > 0  ){
21157     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
21158     nKey--;
21159   }
21160   return h;
21161 }
21162
21163
21164 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
21165 ** insert pNew into the pEntry hash bucket.
21166 */
21167 static void insertElement(
21168   Hash *pH,              /* The complete hash table */
21169   struct _ht *pEntry,    /* The entry into which pNew is inserted */
21170   HashElem *pNew         /* The element to be inserted */
21171 ){
21172   HashElem *pHead;       /* First element already in pEntry */
21173   if( pEntry ){
21174     pHead = pEntry->count ? pEntry->chain : 0;
21175     pEntry->count++;
21176     pEntry->chain = pNew;
21177   }else{
21178     pHead = 0;
21179   }
21180   if( pHead ){
21181     pNew->next = pHead;
21182     pNew->prev = pHead->prev;
21183     if( pHead->prev ){ pHead->prev->next = pNew; }
21184     else             { pH->first = pNew; }
21185     pHead->prev = pNew;
21186   }else{
21187     pNew->next = pH->first;
21188     if( pH->first ){ pH->first->prev = pNew; }
21189     pNew->prev = 0;
21190     pH->first = pNew;
21191   }
21192 }
21193
21194
21195 /* Resize the hash table so that it cantains "new_size" buckets.
21196 **
21197 ** The hash table might fail to resize if sqlite3_malloc() fails or
21198 ** if the new size is the same as the prior size.
21199 ** Return TRUE if the resize occurs and false if not.
21200 */
21201 static int rehash(Hash *pH, unsigned int new_size){
21202   struct _ht *new_ht;            /* The new hash table */
21203   HashElem *elem, *next_elem;    /* For looping over existing elements */
21204
21205 #if SQLITE_MALLOC_SOFT_LIMIT>0
21206   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
21207     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
21208   }
21209   if( new_size==pH->htsize ) return 0;
21210 #endif
21211
21212   /* The inability to allocates space for a larger hash table is
21213   ** a performance hit but it is not a fatal error.  So mark the
21214   ** allocation as a benign.
21215   */
21216   sqlite3BeginBenignMalloc();
21217   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
21218   sqlite3EndBenignMalloc();
21219
21220   if( new_ht==0 ) return 0;
21221   sqlite3_free(pH->ht);
21222   pH->ht = new_ht;
21223   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
21224   memset(new_ht, 0, new_size*sizeof(struct _ht));
21225   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
21226     unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
21227     next_elem = elem->next;
21228     insertElement(pH, &new_ht[h], elem);
21229   }
21230   return 1;
21231 }
21232
21233 /* This function (for internal use only) locates an element in an
21234 ** hash table that matches the given key.  The hash for this key has
21235 ** already been computed and is passed as the 4th parameter.
21236 */
21237 static HashElem *findElementGivenHash(
21238   const Hash *pH,     /* The pH to be searched */
21239   const char *pKey,   /* The key we are searching for */
21240   int nKey,           /* Bytes in key (not counting zero terminator) */
21241   unsigned int h      /* The hash for this key. */
21242 ){
21243   HashElem *elem;                /* Used to loop thru the element list */
21244   int count;                     /* Number of elements left to test */
21245
21246   if( pH->ht ){
21247     struct _ht *pEntry = &pH->ht[h];
21248     elem = pEntry->chain;
21249     count = pEntry->count;
21250   }else{
21251     elem = pH->first;
21252     count = pH->count;
21253   }
21254   while( count-- && ALWAYS(elem) ){
21255     if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){ 
21256       return elem;
21257     }
21258     elem = elem->next;
21259   }
21260   return 0;
21261 }
21262
21263 /* Remove a single entry from the hash table given a pointer to that
21264 ** element and a hash on the element's key.
21265 */
21266 static void removeElementGivenHash(
21267   Hash *pH,         /* The pH containing "elem" */
21268   HashElem* elem,   /* The element to be removed from the pH */
21269   unsigned int h    /* Hash value for the element */
21270 ){
21271   struct _ht *pEntry;
21272   if( elem->prev ){
21273     elem->prev->next = elem->next; 
21274   }else{
21275     pH->first = elem->next;
21276   }
21277   if( elem->next ){
21278     elem->next->prev = elem->prev;
21279   }
21280   if( pH->ht ){
21281     pEntry = &pH->ht[h];
21282     if( pEntry->chain==elem ){
21283       pEntry->chain = elem->next;
21284     }
21285     pEntry->count--;
21286     assert( pEntry->count>=0 );
21287   }
21288   sqlite3_free( elem );
21289   pH->count--;
21290   if( pH->count<=0 ){
21291     assert( pH->first==0 );
21292     assert( pH->count==0 );
21293     sqlite3HashClear(pH);
21294   }
21295 }
21296
21297 /* Attempt to locate an element of the hash table pH with a key
21298 ** that matches pKey,nKey.  Return the data for this element if it is
21299 ** found, or NULL if there is no match.
21300 */
21301 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
21302   HashElem *elem;    /* The element that matches key */
21303   unsigned int h;    /* A hash on key */
21304
21305   assert( pH!=0 );
21306   assert( pKey!=0 );
21307   assert( nKey>=0 );
21308   if( pH->ht ){
21309     h = strHash(pKey, nKey) % pH->htsize;
21310   }else{
21311     h = 0;
21312   }
21313   elem = findElementGivenHash(pH, pKey, nKey, h);
21314   return elem ? elem->data : 0;
21315 }
21316
21317 /* Insert an element into the hash table pH.  The key is pKey,nKey
21318 ** and the data is "data".
21319 **
21320 ** If no element exists with a matching key, then a new
21321 ** element is created and NULL is returned.
21322 **
21323 ** If another element already exists with the same key, then the
21324 ** new data replaces the old data and the old data is returned.
21325 ** The key is not copied in this instance.  If a malloc fails, then
21326 ** the new data is returned and the hash table is unchanged.
21327 **
21328 ** If the "data" parameter to this function is NULL, then the
21329 ** element corresponding to "key" is removed from the hash table.
21330 */
21331 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
21332   unsigned int h;       /* the hash of the key modulo hash table size */
21333   HashElem *elem;       /* Used to loop thru the element list */
21334   HashElem *new_elem;   /* New element added to the pH */
21335
21336   assert( pH!=0 );
21337   assert( pKey!=0 );
21338   assert( nKey>=0 );
21339   if( pH->htsize ){
21340     h = strHash(pKey, nKey) % pH->htsize;
21341   }else{
21342     h = 0;
21343   }
21344   elem = findElementGivenHash(pH,pKey,nKey,h);
21345   if( elem ){
21346     void *old_data = elem->data;
21347     if( data==0 ){
21348       removeElementGivenHash(pH,elem,h);
21349     }else{
21350       elem->data = data;
21351       elem->pKey = pKey;
21352       assert(nKey==elem->nKey);
21353     }
21354     return old_data;
21355   }
21356   if( data==0 ) return 0;
21357   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
21358   if( new_elem==0 ) return data;
21359   new_elem->pKey = pKey;
21360   new_elem->nKey = nKey;
21361   new_elem->data = data;
21362   pH->count++;
21363   if( pH->count>=10 && pH->count > 2*pH->htsize ){
21364     if( rehash(pH, pH->count*2) ){
21365       assert( pH->htsize>0 );
21366       h = strHash(pKey, nKey) % pH->htsize;
21367     }
21368   }
21369   if( pH->ht ){
21370     insertElement(pH, &pH->ht[h], new_elem);
21371   }else{
21372     insertElement(pH, 0, new_elem);
21373   }
21374   return 0;
21375 }
21376
21377 /************** End of hash.c ************************************************/
21378 /************** Begin file opcodes.c *****************************************/
21379 /* Automatically generated.  Do not edit */
21380 /* See the mkopcodec.awk script for details. */
21381 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
21382 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
21383  static const char *const azName[] = { "?",
21384      /*   1 */ "Goto",
21385      /*   2 */ "Gosub",
21386      /*   3 */ "Return",
21387      /*   4 */ "Yield",
21388      /*   5 */ "HaltIfNull",
21389      /*   6 */ "Halt",
21390      /*   7 */ "Integer",
21391      /*   8 */ "Int64",
21392      /*   9 */ "String",
21393      /*  10 */ "Null",
21394      /*  11 */ "Blob",
21395      /*  12 */ "Variable",
21396      /*  13 */ "Move",
21397      /*  14 */ "Copy",
21398      /*  15 */ "SCopy",
21399      /*  16 */ "ResultRow",
21400      /*  17 */ "CollSeq",
21401      /*  18 */ "Function",
21402      /*  19 */ "Not",
21403      /*  20 */ "AddImm",
21404      /*  21 */ "MustBeInt",
21405      /*  22 */ "RealAffinity",
21406      /*  23 */ "Permutation",
21407      /*  24 */ "Compare",
21408      /*  25 */ "Jump",
21409      /*  26 */ "If",
21410      /*  27 */ "IfNot",
21411      /*  28 */ "Column",
21412      /*  29 */ "Affinity",
21413      /*  30 */ "MakeRecord",
21414      /*  31 */ "Count",
21415      /*  32 */ "Savepoint",
21416      /*  33 */ "AutoCommit",
21417      /*  34 */ "Transaction",
21418      /*  35 */ "ReadCookie",
21419      /*  36 */ "SetCookie",
21420      /*  37 */ "VerifyCookie",
21421      /*  38 */ "OpenRead",
21422      /*  39 */ "OpenWrite",
21423      /*  40 */ "OpenAutoindex",
21424      /*  41 */ "OpenEphemeral",
21425      /*  42 */ "OpenPseudo",
21426      /*  43 */ "Close",
21427      /*  44 */ "SeekLt",
21428      /*  45 */ "SeekLe",
21429      /*  46 */ "SeekGe",
21430      /*  47 */ "SeekGt",
21431      /*  48 */ "Seek",
21432      /*  49 */ "NotFound",
21433      /*  50 */ "Found",
21434      /*  51 */ "IsUnique",
21435      /*  52 */ "NotExists",
21436      /*  53 */ "Sequence",
21437      /*  54 */ "NewRowid",
21438      /*  55 */ "Insert",
21439      /*  56 */ "InsertInt",
21440      /*  57 */ "Delete",
21441      /*  58 */ "ResetCount",
21442      /*  59 */ "RowKey",
21443      /*  60 */ "RowData",
21444      /*  61 */ "Rowid",
21445      /*  62 */ "NullRow",
21446      /*  63 */ "Last",
21447      /*  64 */ "Sort",
21448      /*  65 */ "Rewind",
21449      /*  66 */ "Prev",
21450      /*  67 */ "Next",
21451      /*  68 */ "Or",
21452      /*  69 */ "And",
21453      /*  70 */ "IdxInsert",
21454      /*  71 */ "IdxDelete",
21455      /*  72 */ "IdxRowid",
21456      /*  73 */ "IsNull",
21457      /*  74 */ "NotNull",
21458      /*  75 */ "Ne",
21459      /*  76 */ "Eq",
21460      /*  77 */ "Gt",
21461      /*  78 */ "Le",
21462      /*  79 */ "Lt",
21463      /*  80 */ "Ge",
21464      /*  81 */ "IdxLT",
21465      /*  82 */ "BitAnd",
21466      /*  83 */ "BitOr",
21467      /*  84 */ "ShiftLeft",
21468      /*  85 */ "ShiftRight",
21469      /*  86 */ "Add",
21470      /*  87 */ "Subtract",
21471      /*  88 */ "Multiply",
21472      /*  89 */ "Divide",
21473      /*  90 */ "Remainder",
21474      /*  91 */ "Concat",
21475      /*  92 */ "IdxGE",
21476      /*  93 */ "BitNot",
21477      /*  94 */ "String8",
21478      /*  95 */ "Destroy",
21479      /*  96 */ "Clear",
21480      /*  97 */ "CreateIndex",
21481      /*  98 */ "CreateTable",
21482      /*  99 */ "ParseSchema",
21483      /* 100 */ "LoadAnalysis",
21484      /* 101 */ "DropTable",
21485      /* 102 */ "DropIndex",
21486      /* 103 */ "DropTrigger",
21487      /* 104 */ "IntegrityCk",
21488      /* 105 */ "RowSetAdd",
21489      /* 106 */ "RowSetRead",
21490      /* 107 */ "RowSetTest",
21491      /* 108 */ "Program",
21492      /* 109 */ "Param",
21493      /* 110 */ "FkCounter",
21494      /* 111 */ "FkIfZero",
21495      /* 112 */ "MemMax",
21496      /* 113 */ "IfPos",
21497      /* 114 */ "IfNeg",
21498      /* 115 */ "IfZero",
21499      /* 116 */ "AggStep",
21500      /* 117 */ "AggFinal",
21501      /* 118 */ "Checkpoint",
21502      /* 119 */ "JournalMode",
21503      /* 120 */ "Vacuum",
21504      /* 121 */ "IncrVacuum",
21505      /* 122 */ "Expire",
21506      /* 123 */ "TableLock",
21507      /* 124 */ "VBegin",
21508      /* 125 */ "VCreate",
21509      /* 126 */ "VDestroy",
21510      /* 127 */ "VOpen",
21511      /* 128 */ "VFilter",
21512      /* 129 */ "VColumn",
21513      /* 130 */ "Real",
21514      /* 131 */ "VNext",
21515      /* 132 */ "VRename",
21516      /* 133 */ "VUpdate",
21517      /* 134 */ "Pagecount",
21518      /* 135 */ "MaxPgcnt",
21519      /* 136 */ "Trace",
21520      /* 137 */ "Noop",
21521      /* 138 */ "Explain",
21522      /* 139 */ "NotUsed_139",
21523      /* 140 */ "NotUsed_140",
21524      /* 141 */ "ToText",
21525      /* 142 */ "ToBlob",
21526      /* 143 */ "ToNumeric",
21527      /* 144 */ "ToInt",
21528      /* 145 */ "ToReal",
21529   };
21530   return azName[i];
21531 }
21532 #endif
21533
21534 /************** End of opcodes.c *********************************************/
21535 /************** Begin file os_os2.c ******************************************/
21536 /*
21537 ** 2006 Feb 14
21538 **
21539 ** The author disclaims copyright to this source code.  In place of
21540 ** a legal notice, here is a blessing:
21541 **
21542 **    May you do good and not evil.
21543 **    May you find forgiveness for yourself and forgive others.
21544 **    May you share freely, never taking more than you give.
21545 **
21546 ******************************************************************************
21547 **
21548 ** This file contains code that is specific to OS/2.
21549 */
21550
21551
21552 #if SQLITE_OS_OS2
21553
21554 /*
21555 ** A Note About Memory Allocation:
21556 **
21557 ** This driver uses malloc()/free() directly rather than going through
21558 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
21559 ** are designed for use on embedded systems where memory is scarce and
21560 ** malloc failures happen frequently.  OS/2 does not typically run on
21561 ** embedded systems, and when it does the developers normally have bigger
21562 ** problems to worry about than running out of memory.  So there is not
21563 ** a compelling need to use the wrappers.
21564 **
21565 ** But there is a good reason to not use the wrappers.  If we use the
21566 ** wrappers then we will get simulated malloc() failures within this
21567 ** driver.  And that causes all kinds of problems for our tests.  We
21568 ** could enhance SQLite to deal with simulated malloc failures within
21569 ** the OS driver, but the code to deal with those failure would not
21570 ** be exercised on Linux (which does not need to malloc() in the driver)
21571 ** and so we would have difficulty writing coverage tests for that
21572 ** code.  Better to leave the code out, we think.
21573 **
21574 ** The point of this discussion is as follows:  When creating a new
21575 ** OS layer for an embedded system, if you use this file as an example,
21576 ** avoid the use of malloc()/free().  Those routines work ok on OS/2
21577 ** desktops but not so well in embedded systems.
21578 */
21579
21580 /*
21581 ** Macros used to determine whether or not to use threads.
21582 */
21583 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
21584 # define SQLITE_OS2_THREADS 1
21585 #endif
21586
21587 /*
21588 ** Include code that is common to all os_*.c files
21589 */
21590 /************** Include os_common.h in the middle of os_os2.c ****************/
21591 /************** Begin file os_common.h ***************************************/
21592 /*
21593 ** 2004 May 22
21594 **
21595 ** The author disclaims copyright to this source code.  In place of
21596 ** a legal notice, here is a blessing:
21597 **
21598 **    May you do good and not evil.
21599 **    May you find forgiveness for yourself and forgive others.
21600 **    May you share freely, never taking more than you give.
21601 **
21602 ******************************************************************************
21603 **
21604 ** This file contains macros and a little bit of code that is common to
21605 ** all of the platform-specific files (os_*.c) and is #included into those
21606 ** files.
21607 **
21608 ** This file should be #included by the os_*.c files only.  It is not a
21609 ** general purpose header file.
21610 */
21611 #ifndef _OS_COMMON_H_
21612 #define _OS_COMMON_H_
21613
21614 /*
21615 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
21616 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
21617 ** switch.  The following code should catch this problem at compile-time.
21618 */
21619 #ifdef MEMORY_DEBUG
21620 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
21621 #endif
21622
21623 #ifdef SQLITE_DEBUG
21624 SQLITE_PRIVATE int sqlite3OSTrace = 0;
21625 #define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
21626 #else
21627 #define OSTRACE(X)
21628 #endif
21629
21630 /*
21631 ** Macros for performance tracing.  Normally turned off.  Only works
21632 ** on i486 hardware.
21633 */
21634 #ifdef SQLITE_PERFORMANCE_TRACE
21635
21636 /* 
21637 ** hwtime.h contains inline assembler code for implementing 
21638 ** high-performance timing routines.
21639 */
21640 /************** Include hwtime.h in the middle of os_common.h ****************/
21641 /************** Begin file hwtime.h ******************************************/
21642 /*
21643 ** 2008 May 27
21644 **
21645 ** The author disclaims copyright to this source code.  In place of
21646 ** a legal notice, here is a blessing:
21647 **
21648 **    May you do good and not evil.
21649 **    May you find forgiveness for yourself and forgive others.
21650 **    May you share freely, never taking more than you give.
21651 **
21652 ******************************************************************************
21653 **
21654 ** This file contains inline asm code for retrieving "high-performance"
21655 ** counters for x86 class CPUs.
21656 */
21657 #ifndef _HWTIME_H_
21658 #define _HWTIME_H_
21659
21660 /*
21661 ** The following routine only works on pentium-class (or newer) processors.
21662 ** It uses the RDTSC opcode to read the cycle count value out of the
21663 ** processor and returns that value.  This can be used for high-res
21664 ** profiling.
21665 */
21666 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
21667       (defined(i386) || defined(__i386__) || defined(_M_IX86))
21668
21669   #if defined(__GNUC__)
21670
21671   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21672      unsigned int lo, hi;
21673      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
21674      return (sqlite_uint64)hi << 32 | lo;
21675   }
21676
21677   #elif defined(_MSC_VER)
21678
21679   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
21680      __asm {
21681         rdtsc
21682         ret       ; return value at EDX:EAX
21683      }
21684   }
21685
21686   #endif
21687
21688 #elif (defined(__GNUC__) && defined(__x86_64__))
21689
21690   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21691       unsigned long val;
21692       __asm__ __volatile__ ("rdtsc" : "=A" (val));
21693       return val;
21694   }
21695  
21696 #elif (defined(__GNUC__) && defined(__ppc__))
21697
21698   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21699       unsigned long long retval;
21700       unsigned long junk;
21701       __asm__ __volatile__ ("\n\
21702           1:      mftbu   %1\n\
21703                   mftb    %L0\n\
21704                   mftbu   %0\n\
21705                   cmpw    %0,%1\n\
21706                   bne     1b"
21707                   : "=r" (retval), "=r" (junk));
21708       return retval;
21709   }
21710
21711 #else
21712
21713   #error Need implementation of sqlite3Hwtime() for your platform.
21714
21715   /*
21716   ** To compile without implementing sqlite3Hwtime() for your platform,
21717   ** you can remove the above #error and use the following
21718   ** stub function.  You will lose timing support for many
21719   ** of the debugging and testing utilities, but it should at
21720   ** least compile and run.
21721   */
21722 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
21723
21724 #endif
21725
21726 #endif /* !defined(_HWTIME_H_) */
21727
21728 /************** End of hwtime.h **********************************************/
21729 /************** Continuing where we left off in os_common.h ******************/
21730
21731 static sqlite_uint64 g_start;
21732 static sqlite_uint64 g_elapsed;
21733 #define TIMER_START       g_start=sqlite3Hwtime()
21734 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
21735 #define TIMER_ELAPSED     g_elapsed
21736 #else
21737 #define TIMER_START
21738 #define TIMER_END
21739 #define TIMER_ELAPSED     ((sqlite_uint64)0)
21740 #endif
21741
21742 /*
21743 ** If we compile with the SQLITE_TEST macro set, then the following block
21744 ** of code will give us the ability to simulate a disk I/O error.  This
21745 ** is used for testing the I/O recovery logic.
21746 */
21747 #ifdef SQLITE_TEST
21748 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
21749 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
21750 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
21751 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
21752 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
21753 SQLITE_API int sqlite3_diskfull_pending = 0;
21754 SQLITE_API int sqlite3_diskfull = 0;
21755 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
21756 #define SimulateIOError(CODE)  \
21757   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
21758        || sqlite3_io_error_pending-- == 1 )  \
21759               { local_ioerr(); CODE; }
21760 static void local_ioerr(){
21761   IOTRACE(("IOERR\n"));
21762   sqlite3_io_error_hit++;
21763   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
21764 }
21765 #define SimulateDiskfullError(CODE) \
21766    if( sqlite3_diskfull_pending ){ \
21767      if( sqlite3_diskfull_pending == 1 ){ \
21768        local_ioerr(); \
21769        sqlite3_diskfull = 1; \
21770        sqlite3_io_error_hit = 1; \
21771        CODE; \
21772      }else{ \
21773        sqlite3_diskfull_pending--; \
21774      } \
21775    }
21776 #else
21777 #define SimulateIOErrorBenign(X)
21778 #define SimulateIOError(A)
21779 #define SimulateDiskfullError(A)
21780 #endif
21781
21782 /*
21783 ** When testing, keep a count of the number of open files.
21784 */
21785 #ifdef SQLITE_TEST
21786 SQLITE_API int sqlite3_open_file_count = 0;
21787 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
21788 #else
21789 #define OpenCounter(X)
21790 #endif
21791
21792 #endif /* !defined(_OS_COMMON_H_) */
21793
21794 /************** End of os_common.h *******************************************/
21795 /************** Continuing where we left off in os_os2.c *********************/
21796
21797 /*
21798 ** The os2File structure is subclass of sqlite3_file specific for the OS/2
21799 ** protability layer.
21800 */
21801 typedef struct os2File os2File;
21802 struct os2File {
21803   const sqlite3_io_methods *pMethod;  /* Always the first entry */
21804   HFILE h;                  /* Handle for accessing the file */
21805   char* pathToDel;          /* Name of file to delete on close, NULL if not */
21806   unsigned char locktype;   /* Type of lock currently held on this file */
21807 };
21808
21809 #define LOCK_TIMEOUT 10L /* the default locking timeout */
21810
21811 /*****************************************************************************
21812 ** The next group of routines implement the I/O methods specified
21813 ** by the sqlite3_io_methods object.
21814 ******************************************************************************/
21815
21816 /*
21817 ** Close a file.
21818 */
21819 static int os2Close( sqlite3_file *id ){
21820   APIRET rc = NO_ERROR;
21821   os2File *pFile;
21822   if( id && (pFile = (os2File*)id) != 0 ){
21823     OSTRACE(( "CLOSE %d\n", pFile->h ));
21824     rc = DosClose( pFile->h );
21825     pFile->locktype = NO_LOCK;
21826     if( pFile->pathToDel != NULL ){
21827       rc = DosForceDelete( (PSZ)pFile->pathToDel );
21828       free( pFile->pathToDel );
21829       pFile->pathToDel = NULL;
21830     }
21831     id = 0;
21832     OpenCounter( -1 );
21833   }
21834
21835   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
21836 }
21837
21838 /*
21839 ** Read data from a file into a buffer.  Return SQLITE_OK if all
21840 ** bytes were read successfully and SQLITE_IOERR if anything goes
21841 ** wrong.
21842 */
21843 static int os2Read(
21844   sqlite3_file *id,               /* File to read from */
21845   void *pBuf,                     /* Write content into this buffer */
21846   int amt,                        /* Number of bytes to read */
21847   sqlite3_int64 offset            /* Begin reading at this offset */
21848 ){
21849   ULONG fileLocation = 0L;
21850   ULONG got;
21851   os2File *pFile = (os2File*)id;
21852   assert( id!=0 );
21853   SimulateIOError( return SQLITE_IOERR_READ );
21854   OSTRACE(( "READ %d lock=%d\n", pFile->h, pFile->locktype ));
21855   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
21856     return SQLITE_IOERR;
21857   }
21858   if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
21859     return SQLITE_IOERR_READ;
21860   }
21861   if( got == (ULONG)amt )
21862     return SQLITE_OK;
21863   else {
21864     /* Unread portions of the input buffer must be zero-filled */
21865     memset(&((char*)pBuf)[got], 0, amt-got);
21866     return SQLITE_IOERR_SHORT_READ;
21867   }
21868 }
21869
21870 /*
21871 ** Write data from a buffer into a file.  Return SQLITE_OK on success
21872 ** or some other error code on failure.
21873 */
21874 static int os2Write(
21875   sqlite3_file *id,               /* File to write into */
21876   const void *pBuf,               /* The bytes to be written */
21877   int amt,                        /* Number of bytes to write */
21878   sqlite3_int64 offset            /* Offset into the file to begin writing at */
21879 ){
21880   ULONG fileLocation = 0L;
21881   APIRET rc = NO_ERROR;
21882   ULONG wrote;
21883   os2File *pFile = (os2File*)id;
21884   assert( id!=0 );
21885   SimulateIOError( return SQLITE_IOERR_WRITE );
21886   SimulateDiskfullError( return SQLITE_FULL );
21887   OSTRACE(( "WRITE %d lock=%d\n", pFile->h, pFile->locktype ));
21888   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
21889     return SQLITE_IOERR;
21890   }
21891   assert( amt>0 );
21892   while( amt > 0 &&
21893          ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
21894          wrote > 0
21895   ){
21896     amt -= wrote;
21897     pBuf = &((char*)pBuf)[wrote];
21898   }
21899
21900   return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
21901 }
21902
21903 /*
21904 ** Truncate an open file to a specified size
21905 */
21906 static int os2Truncate( sqlite3_file *id, i64 nByte ){
21907   APIRET rc = NO_ERROR;
21908   os2File *pFile = (os2File*)id;
21909   OSTRACE(( "TRUNCATE %d %lld\n", pFile->h, nByte ));
21910   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
21911   rc = DosSetFileSize( pFile->h, nByte );
21912   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
21913 }
21914
21915 #ifdef SQLITE_TEST
21916 /*
21917 ** Count the number of fullsyncs and normal syncs.  This is used to test
21918 ** that syncs and fullsyncs are occuring at the right times.
21919 */
21920 SQLITE_API int sqlite3_sync_count = 0;
21921 SQLITE_API int sqlite3_fullsync_count = 0;
21922 #endif
21923
21924 /*
21925 ** Make sure all writes to a particular file are committed to disk.
21926 */
21927 static int os2Sync( sqlite3_file *id, int flags ){
21928   os2File *pFile = (os2File*)id;
21929   OSTRACE(( "SYNC %d lock=%d\n", pFile->h, pFile->locktype ));
21930 #ifdef SQLITE_TEST
21931   if( flags & SQLITE_SYNC_FULL){
21932     sqlite3_fullsync_count++;
21933   }
21934   sqlite3_sync_count++;
21935 #endif
21936   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
21937   ** no-op
21938   */
21939 #ifdef SQLITE_NO_SYNC
21940   UNUSED_PARAMETER(pFile);
21941   return SQLITE_OK;
21942 #else
21943   return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
21944 #endif
21945 }
21946
21947 /*
21948 ** Determine the current size of a file in bytes
21949 */
21950 static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
21951   APIRET rc = NO_ERROR;
21952   FILESTATUS3 fsts3FileInfo;
21953   memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
21954   assert( id!=0 );
21955   SimulateIOError( return SQLITE_IOERR_FSTAT );
21956   rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
21957   if( rc == NO_ERROR ){
21958     *pSize = fsts3FileInfo.cbFile;
21959     return SQLITE_OK;
21960   }else{
21961     return SQLITE_IOERR_FSTAT;
21962   }
21963 }
21964
21965 /*
21966 ** Acquire a reader lock.
21967 */
21968 static int getReadLock( os2File *pFile ){
21969   FILELOCK  LockArea,
21970             UnlockArea;
21971   APIRET res;
21972   memset(&LockArea, 0, sizeof(LockArea));
21973   memset(&UnlockArea, 0, sizeof(UnlockArea));
21974   LockArea.lOffset = SHARED_FIRST;
21975   LockArea.lRange = SHARED_SIZE;
21976   UnlockArea.lOffset = 0L;
21977   UnlockArea.lRange = 0L;
21978   res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
21979   OSTRACE(( "GETREADLOCK %d res=%d\n", pFile->h, res ));
21980   return res;
21981 }
21982
21983 /*
21984 ** Undo a readlock
21985 */
21986 static int unlockReadLock( os2File *id ){
21987   FILELOCK  LockArea,
21988             UnlockArea;
21989   APIRET res;
21990   memset(&LockArea, 0, sizeof(LockArea));
21991   memset(&UnlockArea, 0, sizeof(UnlockArea));
21992   LockArea.lOffset = 0L;
21993   LockArea.lRange = 0L;
21994   UnlockArea.lOffset = SHARED_FIRST;
21995   UnlockArea.lRange = SHARED_SIZE;
21996   res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
21997   OSTRACE(( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res ));
21998   return res;
21999 }
22000
22001 /*
22002 ** Lock the file with the lock specified by parameter locktype - one
22003 ** of the following:
22004 **
22005 **     (1) SHARED_LOCK
22006 **     (2) RESERVED_LOCK
22007 **     (3) PENDING_LOCK
22008 **     (4) EXCLUSIVE_LOCK
22009 **
22010 ** Sometimes when requesting one lock state, additional lock states
22011 ** are inserted in between.  The locking might fail on one of the later
22012 ** transitions leaving the lock state different from what it started but
22013 ** still short of its goal.  The following chart shows the allowed
22014 ** transitions and the inserted intermediate states:
22015 **
22016 **    UNLOCKED -> SHARED
22017 **    SHARED -> RESERVED
22018 **    SHARED -> (PENDING) -> EXCLUSIVE
22019 **    RESERVED -> (PENDING) -> EXCLUSIVE
22020 **    PENDING -> EXCLUSIVE
22021 **
22022 ** This routine will only increase a lock.  The os2Unlock() routine
22023 ** erases all locks at once and returns us immediately to locking level 0.
22024 ** It is not possible to lower the locking level one step at a time.  You
22025 ** must go straight to locking level 0.
22026 */
22027 static int os2Lock( sqlite3_file *id, int locktype ){
22028   int rc = SQLITE_OK;       /* Return code from subroutines */
22029   APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
22030   int newLocktype;       /* Set pFile->locktype to this value before exiting */
22031   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
22032   FILELOCK  LockArea,
22033             UnlockArea;
22034   os2File *pFile = (os2File*)id;
22035   memset(&LockArea, 0, sizeof(LockArea));
22036   memset(&UnlockArea, 0, sizeof(UnlockArea));
22037   assert( pFile!=0 );
22038   OSTRACE(( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype ));
22039
22040   /* If there is already a lock of this type or more restrictive on the
22041   ** os2File, do nothing. Don't use the end_lock: exit path, as
22042   ** sqlite3_mutex_enter() hasn't been called yet.
22043   */
22044   if( pFile->locktype>=locktype ){
22045     OSTRACE(( "LOCK %d %d ok (already held)\n", pFile->h, locktype ));
22046     return SQLITE_OK;
22047   }
22048
22049   /* Make sure the locking sequence is correct
22050   */
22051   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
22052   assert( locktype!=PENDING_LOCK );
22053   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
22054
22055   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
22056   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
22057   ** the PENDING_LOCK byte is temporary.
22058   */
22059   newLocktype = pFile->locktype;
22060   if( pFile->locktype==NO_LOCK
22061       || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
22062   ){
22063     LockArea.lOffset = PENDING_BYTE;
22064     LockArea.lRange = 1L;
22065     UnlockArea.lOffset = 0L;
22066     UnlockArea.lRange = 0L;
22067
22068     /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
22069     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
22070     if( res == NO_ERROR ){
22071       gotPendingLock = 1;
22072       OSTRACE(( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res ));
22073     }
22074   }
22075
22076   /* Acquire a shared lock
22077   */
22078   if( locktype==SHARED_LOCK && res == NO_ERROR ){
22079     assert( pFile->locktype==NO_LOCK );
22080     res = getReadLock(pFile);
22081     if( res == NO_ERROR ){
22082       newLocktype = SHARED_LOCK;
22083     }
22084     OSTRACE(( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res ));
22085   }
22086
22087   /* Acquire a RESERVED lock
22088   */
22089   if( locktype==RESERVED_LOCK && res == NO_ERROR ){
22090     assert( pFile->locktype==SHARED_LOCK );
22091     LockArea.lOffset = RESERVED_BYTE;
22092     LockArea.lRange = 1L;
22093     UnlockArea.lOffset = 0L;
22094     UnlockArea.lRange = 0L;
22095     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22096     if( res == NO_ERROR ){
22097       newLocktype = RESERVED_LOCK;
22098     }
22099     OSTRACE(( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res ));
22100   }
22101
22102   /* Acquire a PENDING lock
22103   */
22104   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
22105     newLocktype = PENDING_LOCK;
22106     gotPendingLock = 0;
22107     OSTRACE(( "LOCK %d acquire pending lock. pending lock boolean unset.\n",
22108                pFile->h ));
22109   }
22110
22111   /* Acquire an EXCLUSIVE lock
22112   */
22113   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
22114     assert( pFile->locktype>=SHARED_LOCK );
22115     res = unlockReadLock(pFile);
22116     OSTRACE(( "unreadlock = %d\n", res ));
22117     LockArea.lOffset = SHARED_FIRST;
22118     LockArea.lRange = SHARED_SIZE;
22119     UnlockArea.lOffset = 0L;
22120     UnlockArea.lRange = 0L;
22121     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22122     if( res == NO_ERROR ){
22123       newLocktype = EXCLUSIVE_LOCK;
22124     }else{
22125       OSTRACE(( "OS/2 error-code = %d\n", res ));
22126       getReadLock(pFile);
22127     }
22128     OSTRACE(( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res ));
22129   }
22130
22131   /* If we are holding a PENDING lock that ought to be released, then
22132   ** release it now.
22133   */
22134   if( gotPendingLock && locktype==SHARED_LOCK ){
22135     int r;
22136     LockArea.lOffset = 0L;
22137     LockArea.lRange = 0L;
22138     UnlockArea.lOffset = PENDING_BYTE;
22139     UnlockArea.lRange = 1L;
22140     r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22141     OSTRACE(( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r ));
22142   }
22143
22144   /* Update the state of the lock has held in the file descriptor then
22145   ** return the appropriate result code.
22146   */
22147   if( res == NO_ERROR ){
22148     rc = SQLITE_OK;
22149   }else{
22150     OSTRACE(( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
22151               locktype, newLocktype ));
22152     rc = SQLITE_BUSY;
22153   }
22154   pFile->locktype = newLocktype;
22155   OSTRACE(( "LOCK %d now %d\n", pFile->h, pFile->locktype ));
22156   return rc;
22157 }
22158
22159 /*
22160 ** This routine checks if there is a RESERVED lock held on the specified
22161 ** file by this or any other process. If such a lock is held, return
22162 ** non-zero, otherwise zero.
22163 */
22164 static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
22165   int r = 0;
22166   os2File *pFile = (os2File*)id;
22167   assert( pFile!=0 );
22168   if( pFile->locktype>=RESERVED_LOCK ){
22169     r = 1;
22170     OSTRACE(( "TEST WR-LOCK %d %d (local)\n", pFile->h, r ));
22171   }else{
22172     FILELOCK  LockArea,
22173               UnlockArea;
22174     APIRET rc = NO_ERROR;
22175     memset(&LockArea, 0, sizeof(LockArea));
22176     memset(&UnlockArea, 0, sizeof(UnlockArea));
22177     LockArea.lOffset = RESERVED_BYTE;
22178     LockArea.lRange = 1L;
22179     UnlockArea.lOffset = 0L;
22180     UnlockArea.lRange = 0L;
22181     rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22182     OSTRACE(( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc ));
22183     if( rc == NO_ERROR ){
22184       APIRET rcu = NO_ERROR; /* return code for unlocking */
22185       LockArea.lOffset = 0L;
22186       LockArea.lRange = 0L;
22187       UnlockArea.lOffset = RESERVED_BYTE;
22188       UnlockArea.lRange = 1L;
22189       rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22190       OSTRACE(( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu ));
22191     }
22192     r = !(rc == NO_ERROR);
22193     OSTRACE(( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r ));
22194   }
22195   *pOut = r;
22196   return SQLITE_OK;
22197 }
22198
22199 /*
22200 ** Lower the locking level on file descriptor id to locktype.  locktype
22201 ** must be either NO_LOCK or SHARED_LOCK.
22202 **
22203 ** If the locking level of the file descriptor is already at or below
22204 ** the requested locking level, this routine is a no-op.
22205 **
22206 ** It is not possible for this routine to fail if the second argument
22207 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
22208 ** might return SQLITE_IOERR;
22209 */
22210 static int os2Unlock( sqlite3_file *id, int locktype ){
22211   int type;
22212   os2File *pFile = (os2File*)id;
22213   APIRET rc = SQLITE_OK;
22214   APIRET res = NO_ERROR;
22215   FILELOCK  LockArea,
22216             UnlockArea;
22217   memset(&LockArea, 0, sizeof(LockArea));
22218   memset(&UnlockArea, 0, sizeof(UnlockArea));
22219   assert( pFile!=0 );
22220   assert( locktype<=SHARED_LOCK );
22221   OSTRACE(( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype ));
22222   type = pFile->locktype;
22223   if( type>=EXCLUSIVE_LOCK ){
22224     LockArea.lOffset = 0L;
22225     LockArea.lRange = 0L;
22226     UnlockArea.lOffset = SHARED_FIRST;
22227     UnlockArea.lRange = SHARED_SIZE;
22228     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22229     OSTRACE(( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res ));
22230     if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
22231       /* This should never happen.  We should always be able to
22232       ** reacquire the read lock */
22233       OSTRACE(( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype ));
22234       rc = SQLITE_IOERR_UNLOCK;
22235     }
22236   }
22237   if( type>=RESERVED_LOCK ){
22238     LockArea.lOffset = 0L;
22239     LockArea.lRange = 0L;
22240     UnlockArea.lOffset = RESERVED_BYTE;
22241     UnlockArea.lRange = 1L;
22242     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22243     OSTRACE(( "UNLOCK %d reserved res=%d\n", pFile->h, res ));
22244   }
22245   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
22246     res = unlockReadLock(pFile);
22247     OSTRACE(( "UNLOCK %d is %d want %d res=%d\n",
22248               pFile->h, type, locktype, res ));
22249   }
22250   if( type>=PENDING_LOCK ){
22251     LockArea.lOffset = 0L;
22252     LockArea.lRange = 0L;
22253     UnlockArea.lOffset = PENDING_BYTE;
22254     UnlockArea.lRange = 1L;
22255     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22256     OSTRACE(( "UNLOCK %d pending res=%d\n", pFile->h, res ));
22257   }
22258   pFile->locktype = locktype;
22259   OSTRACE(( "UNLOCK %d now %d\n", pFile->h, pFile->locktype ));
22260   return rc;
22261 }
22262
22263 /*
22264 ** Control and query of the open file handle.
22265 */
22266 static int os2FileControl(sqlite3_file *id, int op, void *pArg){
22267   switch( op ){
22268     case SQLITE_FCNTL_LOCKSTATE: {
22269       *(int*)pArg = ((os2File*)id)->locktype;
22270       OSTRACE(( "FCNTL_LOCKSTATE %d lock=%d\n",
22271                 ((os2File*)id)->h, ((os2File*)id)->locktype ));
22272       return SQLITE_OK;
22273     }
22274   }
22275   return SQLITE_NOTFOUND;
22276 }
22277
22278 /*
22279 ** Return the sector size in bytes of the underlying block device for
22280 ** the specified file. This is almost always 512 bytes, but may be
22281 ** larger for some devices.
22282 **
22283 ** SQLite code assumes this function cannot fail. It also assumes that
22284 ** if two files are created in the same file-system directory (i.e.
22285 ** a database and its journal file) that the sector size will be the
22286 ** same for both.
22287 */
22288 static int os2SectorSize(sqlite3_file *id){
22289   return SQLITE_DEFAULT_SECTOR_SIZE;
22290 }
22291
22292 /*
22293 ** Return a vector of device characteristics.
22294 */
22295 static int os2DeviceCharacteristics(sqlite3_file *id){
22296   return 0;
22297 }
22298
22299
22300 /*
22301 ** Character set conversion objects used by conversion routines.
22302 */
22303 static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
22304 static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
22305
22306 /*
22307 ** Helper function to initialize the conversion objects from and to UTF-8.
22308 */
22309 static void initUconvObjects( void ){
22310   if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
22311     ucUtf8 = NULL;
22312   if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
22313     uclCp = NULL;
22314 }
22315
22316 /*
22317 ** Helper function to free the conversion objects from and to UTF-8.
22318 */
22319 static void freeUconvObjects( void ){
22320   if ( ucUtf8 )
22321     UniFreeUconvObject( ucUtf8 );
22322   if ( uclCp )
22323     UniFreeUconvObject( uclCp );
22324   ucUtf8 = NULL;
22325   uclCp = NULL;
22326 }
22327
22328 /*
22329 ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
22330 ** The two-step process: first convert the incoming UTF-8 string
22331 ** into UCS-2 and then from UCS-2 to the current codepage.
22332 ** The returned char pointer has to be freed.
22333 */
22334 static char *convertUtf8PathToCp( const char *in ){
22335   UniChar tempPath[CCHMAXPATH];
22336   char *out = (char *)calloc( CCHMAXPATH, 1 );
22337
22338   if( !out )
22339     return NULL;
22340
22341   if( !ucUtf8 || !uclCp )
22342     initUconvObjects();
22343
22344   /* determine string for the conversion of UTF-8 which is CP1208 */
22345   if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
22346     return out; /* if conversion fails, return the empty string */
22347
22348   /* conversion for current codepage which can be used for paths */
22349   UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
22350
22351   return out;
22352 }
22353
22354 /*
22355 ** Helper function to convert filenames from local codepage to UTF-8.
22356 ** The two-step process: first convert the incoming codepage-specific
22357 ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
22358 ** The returned char pointer has to be freed.
22359 **
22360 ** This function is non-static to be able to use this in shell.c and
22361 ** similar applications that take command line arguments.
22362 */
22363 char *convertCpPathToUtf8( const char *in ){
22364   UniChar tempPath[CCHMAXPATH];
22365   char *out = (char *)calloc( CCHMAXPATH, 1 );
22366
22367   if( !out )
22368     return NULL;
22369
22370   if( !ucUtf8 || !uclCp )
22371     initUconvObjects();
22372
22373   /* conversion for current codepage which can be used for paths */
22374   if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
22375     return out; /* if conversion fails, return the empty string */
22376
22377   /* determine string for the conversion of UTF-8 which is CP1208 */
22378   UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
22379
22380   return out;
22381 }
22382
22383 /*
22384 ** This vector defines all the methods that can operate on an
22385 ** sqlite3_file for os2.
22386 */
22387 static const sqlite3_io_methods os2IoMethod = {
22388   1,                        /* iVersion */
22389   os2Close,
22390   os2Read,
22391   os2Write,
22392   os2Truncate,
22393   os2Sync,
22394   os2FileSize,
22395   os2Lock,
22396   os2Unlock,
22397   os2CheckReservedLock,
22398   os2FileControl,
22399   os2SectorSize,
22400   os2DeviceCharacteristics
22401 };
22402
22403 /***************************************************************************
22404 ** Here ends the I/O methods that form the sqlite3_io_methods object.
22405 **
22406 ** The next block of code implements the VFS methods.
22407 ****************************************************************************/
22408
22409 /*
22410 ** Create a temporary file name in zBuf.  zBuf must be big enough to
22411 ** hold at pVfs->mxPathname characters.
22412 */
22413 static int getTempname(int nBuf, char *zBuf ){
22414   static const unsigned char zChars[] =
22415     "abcdefghijklmnopqrstuvwxyz"
22416     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
22417     "0123456789";
22418   int i, j;
22419   char zTempPathBuf[3];
22420   PSZ zTempPath = (PSZ)&zTempPathBuf;
22421   if( sqlite3_temp_directory ){
22422     zTempPath = sqlite3_temp_directory;
22423   }else{
22424     if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
22425       if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
22426         if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
22427            ULONG ulDriveNum = 0, ulDriveMap = 0;
22428            DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
22429            sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
22430         }
22431       }
22432     }
22433   }
22434   /* Strip off a trailing slashes or backslashes, otherwise we would get *
22435    * multiple (back)slashes which causes DosOpen() to fail.              *
22436    * Trailing spaces are not allowed, either.                            */
22437   j = sqlite3Strlen30(zTempPath);
22438   while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/'
22439                     || zTempPath[j-1] == ' ' ) ){
22440     j--;
22441   }
22442   zTempPath[j] = '\0';
22443   if( !sqlite3_temp_directory ){
22444     char *zTempPathUTF = convertCpPathToUtf8( zTempPath );
22445     sqlite3_snprintf( nBuf-30, zBuf,
22446                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPathUTF );
22447     free( zTempPathUTF );
22448   }else{
22449     sqlite3_snprintf( nBuf-30, zBuf,
22450                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath );
22451   }
22452   j = sqlite3Strlen30( zBuf );
22453   sqlite3_randomness( 20, &zBuf[j] );
22454   for( i = 0; i < 20; i++, j++ ){
22455     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
22456   }
22457   zBuf[j] = 0;
22458   OSTRACE(( "TEMP FILENAME: %s\n", zBuf ));
22459   return SQLITE_OK;
22460 }
22461
22462
22463 /*
22464 ** Turn a relative pathname into a full pathname.  Write the full
22465 ** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
22466 ** bytes in size.
22467 */
22468 static int os2FullPathname(
22469   sqlite3_vfs *pVfs,          /* Pointer to vfs object */
22470   const char *zRelative,      /* Possibly relative input path */
22471   int nFull,                  /* Size of output buffer in bytes */
22472   char *zFull                 /* Output buffer */
22473 ){
22474   char *zRelativeCp = convertUtf8PathToCp( zRelative );
22475   char zFullCp[CCHMAXPATH] = "\0";
22476   char *zFullUTF;
22477   APIRET rc = DosQueryPathInfo( zRelativeCp, FIL_QUERYFULLNAME, zFullCp,
22478                                 CCHMAXPATH );
22479   free( zRelativeCp );
22480   zFullUTF = convertCpPathToUtf8( zFullCp );
22481   sqlite3_snprintf( nFull, zFull, zFullUTF );
22482   free( zFullUTF );
22483   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
22484 }
22485
22486
22487 /*
22488 ** Open a file.
22489 */
22490 static int os2Open(
22491   sqlite3_vfs *pVfs,            /* Not used */
22492   const char *zName,            /* Name of the file */
22493   sqlite3_file *id,             /* Write the SQLite file handle here */
22494   int flags,                    /* Open mode flags */
22495   int *pOutFlags                /* Status return flags */
22496 ){
22497   HFILE h;
22498   ULONG ulFileAttribute = FILE_NORMAL;
22499   ULONG ulOpenFlags = 0;
22500   ULONG ulOpenMode = 0;
22501   os2File *pFile = (os2File*)id;
22502   APIRET rc = NO_ERROR;
22503   ULONG ulAction;
22504   char *zNameCp;
22505   char zTmpname[CCHMAXPATH+1];    /* Buffer to hold name of temp file */
22506
22507   /* If the second argument to this function is NULL, generate a 
22508   ** temporary file name to use 
22509   */
22510   if( !zName ){
22511     int rc = getTempname(CCHMAXPATH+1, zTmpname);
22512     if( rc!=SQLITE_OK ){
22513       return rc;
22514     }
22515     zName = zTmpname;
22516   }
22517
22518
22519   memset( pFile, 0, sizeof(*pFile) );
22520
22521   OSTRACE(( "OPEN want %d\n", flags ));
22522
22523   if( flags & SQLITE_OPEN_READWRITE ){
22524     ulOpenMode |= OPEN_ACCESS_READWRITE;
22525     OSTRACE(( "OPEN read/write\n" ));
22526   }else{
22527     ulOpenMode |= OPEN_ACCESS_READONLY;
22528     OSTRACE(( "OPEN read only\n" ));
22529   }
22530
22531   if( flags & SQLITE_OPEN_CREATE ){
22532     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
22533     OSTRACE(( "OPEN open new/create\n" ));
22534   }else{
22535     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
22536     OSTRACE(( "OPEN open existing\n" ));
22537   }
22538
22539   if( flags & SQLITE_OPEN_MAIN_DB ){
22540     ulOpenMode |= OPEN_SHARE_DENYNONE;
22541     OSTRACE(( "OPEN share read/write\n" ));
22542   }else{
22543     ulOpenMode |= OPEN_SHARE_DENYWRITE;
22544     OSTRACE(( "OPEN share read only\n" ));
22545   }
22546
22547   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
22548     char pathUtf8[CCHMAXPATH];
22549 #ifdef NDEBUG /* when debugging we want to make sure it is deleted */
22550     ulFileAttribute = FILE_HIDDEN;
22551 #endif
22552     os2FullPathname( pVfs, zName, CCHMAXPATH, pathUtf8 );
22553     pFile->pathToDel = convertUtf8PathToCp( pathUtf8 );
22554     OSTRACE(( "OPEN hidden/delete on close file attributes\n" ));
22555   }else{
22556     pFile->pathToDel = NULL;
22557     OSTRACE(( "OPEN normal file attribute\n" ));
22558   }
22559
22560   /* always open in random access mode for possibly better speed */
22561   ulOpenMode |= OPEN_FLAGS_RANDOM;
22562   ulOpenMode |= OPEN_FLAGS_FAIL_ON_ERROR;
22563   ulOpenMode |= OPEN_FLAGS_NOINHERIT;
22564
22565   zNameCp = convertUtf8PathToCp( zName );
22566   rc = DosOpen( (PSZ)zNameCp,
22567                 &h,
22568                 &ulAction,
22569                 0L,
22570                 ulFileAttribute,
22571                 ulOpenFlags,
22572                 ulOpenMode,
22573                 (PEAOP2)NULL );
22574   free( zNameCp );
22575   if( rc != NO_ERROR ){
22576     OSTRACE(( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
22577               rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode ));
22578     if( pFile->pathToDel )
22579       free( pFile->pathToDel );
22580     pFile->pathToDel = NULL;
22581     if( flags & SQLITE_OPEN_READWRITE ){
22582       OSTRACE(( "OPEN %d Invalid handle\n",
22583                 ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) ));
22584       return os2Open( pVfs, zName, id,
22585                       ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
22586                       pOutFlags );
22587     }else{
22588       return SQLITE_CANTOPEN;
22589     }
22590   }
22591
22592   if( pOutFlags ){
22593     *pOutFlags = flags & SQLITE_OPEN_READWRITE ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
22594   }
22595
22596   pFile->pMethod = &os2IoMethod;
22597   pFile->h = h;
22598   OpenCounter(+1);
22599   OSTRACE(( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags ));
22600   return SQLITE_OK;
22601 }
22602
22603 /*
22604 ** Delete the named file.
22605 */
22606 static int os2Delete(
22607   sqlite3_vfs *pVfs,                     /* Not used on os2 */
22608   const char *zFilename,                 /* Name of file to delete */
22609   int syncDir                            /* Not used on os2 */
22610 ){
22611   APIRET rc = NO_ERROR;
22612   char *zFilenameCp = convertUtf8PathToCp( zFilename );
22613   SimulateIOError( return SQLITE_IOERR_DELETE );
22614   rc = DosDelete( (PSZ)zFilenameCp );
22615   free( zFilenameCp );
22616   OSTRACE(( "DELETE \"%s\"\n", zFilename ));
22617   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_DELETE;
22618 }
22619
22620 /*
22621 ** Check the existance and status of a file.
22622 */
22623 static int os2Access(
22624   sqlite3_vfs *pVfs,        /* Not used on os2 */
22625   const char *zFilename,    /* Name of file to check */
22626   int flags,                /* Type of test to make on this file */
22627   int *pOut                 /* Write results here */
22628 ){
22629   FILESTATUS3 fsts3ConfigInfo;
22630   APIRET rc = NO_ERROR;
22631   char *zFilenameCp = convertUtf8PathToCp( zFilename );
22632
22633   memset( &fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo) );
22634   rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
22635                          &fsts3ConfigInfo, sizeof(FILESTATUS3) );
22636   free( zFilenameCp );
22637   OSTRACE(( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
22638             fsts3ConfigInfo.attrFile, flags, rc ));
22639   switch( flags ){
22640     case SQLITE_ACCESS_READ:
22641     case SQLITE_ACCESS_EXISTS:
22642       rc = (rc == NO_ERROR);
22643       OSTRACE(( "ACCESS %s access of read and exists  rc=%d\n", zFilename, rc));
22644       break;
22645     case SQLITE_ACCESS_READWRITE:
22646       rc = (rc == NO_ERROR) && ( (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0 );
22647       OSTRACE(( "ACCESS %s access of read/write  rc=%d\n", zFilename, rc ));
22648       break;
22649     default:
22650       assert( !"Invalid flags argument" );
22651   }
22652   *pOut = rc;
22653   return SQLITE_OK;
22654 }
22655
22656
22657 #ifndef SQLITE_OMIT_LOAD_EXTENSION
22658 /*
22659 ** Interfaces for opening a shared library, finding entry points
22660 ** within the shared library, and closing the shared library.
22661 */
22662 /*
22663 ** Interfaces for opening a shared library, finding entry points
22664 ** within the shared library, and closing the shared library.
22665 */
22666 static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
22667   UCHAR loadErr[256];
22668   HMODULE hmod;
22669   APIRET rc;
22670   char *zFilenameCp = convertUtf8PathToCp(zFilename);
22671   rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilenameCp, &hmod);
22672   free(zFilenameCp);
22673   return rc != NO_ERROR ? 0 : (void*)hmod;
22674 }
22675 /*
22676 ** A no-op since the error code is returned on the DosLoadModule call.
22677 ** os2Dlopen returns zero if DosLoadModule is not successful.
22678 */
22679 static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
22680 /* no-op */
22681 }
22682 static void *os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
22683   PFN pfn;
22684   APIRET rc;
22685   rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
22686   if( rc != NO_ERROR ){
22687     /* if the symbol itself was not found, search again for the same
22688      * symbol with an extra underscore, that might be needed depending
22689      * on the calling convention */
22690     char _zSymbol[256] = "_";
22691     strncat(_zSymbol, zSymbol, 255);
22692     rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
22693   }
22694   return rc != NO_ERROR ? 0 : (void*)pfn;
22695 }
22696 static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
22697   DosFreeModule((HMODULE)pHandle);
22698 }
22699 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
22700   #define os2DlOpen 0
22701   #define os2DlError 0
22702   #define os2DlSym 0
22703   #define os2DlClose 0
22704 #endif
22705
22706
22707 /*
22708 ** Write up to nBuf bytes of randomness into zBuf.
22709 */
22710 static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
22711   int n = 0;
22712 #if defined(SQLITE_TEST)
22713   n = nBuf;
22714   memset(zBuf, 0, nBuf);
22715 #else
22716   int sizeofULong = sizeof(ULONG);
22717   if( (int)sizeof(DATETIME) <= nBuf - n ){
22718     DATETIME x;
22719     DosGetDateTime(&x);
22720     memcpy(&zBuf[n], &x, sizeof(x));
22721     n += sizeof(x);
22722   }
22723
22724   if( sizeofULong <= nBuf - n ){
22725     PPIB ppib;
22726     DosGetInfoBlocks(NULL, &ppib);
22727     memcpy(&zBuf[n], &ppib->pib_ulpid, sizeofULong);
22728     n += sizeofULong;
22729   }
22730
22731   if( sizeofULong <= nBuf - n ){
22732     PTIB ptib;
22733     DosGetInfoBlocks(&ptib, NULL);
22734     memcpy(&zBuf[n], &ptib->tib_ptib2->tib2_ultid, sizeofULong);
22735     n += sizeofULong;
22736   }
22737
22738   /* if we still haven't filled the buffer yet the following will */
22739   /* grab everything once instead of making several calls for a single item */
22740   if( sizeofULong <= nBuf - n ){
22741     ULONG ulSysInfo[QSV_MAX];
22742     DosQuerySysInfo(1L, QSV_MAX, ulSysInfo, sizeofULong * QSV_MAX);
22743
22744     memcpy(&zBuf[n], &ulSysInfo[QSV_MS_COUNT - 1], sizeofULong);
22745     n += sizeofULong;
22746
22747     if( sizeofULong <= nBuf - n ){
22748       memcpy(&zBuf[n], &ulSysInfo[QSV_TIMER_INTERVAL - 1], sizeofULong);
22749       n += sizeofULong;
22750     }
22751     if( sizeofULong <= nBuf - n ){
22752       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_LOW - 1], sizeofULong);
22753       n += sizeofULong;
22754     }
22755     if( sizeofULong <= nBuf - n ){
22756       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_HIGH - 1], sizeofULong);
22757       n += sizeofULong;
22758     }
22759     if( sizeofULong <= nBuf - n ){
22760       memcpy(&zBuf[n], &ulSysInfo[QSV_TOTAVAILMEM - 1], sizeofULong);
22761       n += sizeofULong;
22762     }
22763   }
22764 #endif
22765
22766   return n;
22767 }
22768
22769 /*
22770 ** Sleep for a little while.  Return the amount of time slept.
22771 ** The argument is the number of microseconds we want to sleep.
22772 ** The return value is the number of microseconds of sleep actually
22773 ** requested from the underlying operating system, a number which
22774 ** might be greater than or equal to the argument, but not less
22775 ** than the argument.
22776 */
22777 static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
22778   DosSleep( (microsec/1000) );
22779   return microsec;
22780 }
22781
22782 /*
22783 ** The following variable, if set to a non-zero value, becomes the result
22784 ** returned from sqlite3OsCurrentTime().  This is used for testing.
22785 */
22786 #ifdef SQLITE_TEST
22787 SQLITE_API int sqlite3_current_time = 0;
22788 #endif
22789
22790 /*
22791 ** Find the current time (in Universal Coordinated Time).  Write the
22792 ** current time and date as a Julian Day number into *prNow and
22793 ** return 0.  Return 1 if the time and date cannot be found.
22794 */
22795 int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
22796   double now;
22797   SHORT minute; /* needs to be able to cope with negative timezone offset */
22798   USHORT second, hour,
22799          day, month, year;
22800   DATETIME dt;
22801   DosGetDateTime( &dt );
22802   second = (USHORT)dt.seconds;
22803   minute = (SHORT)dt.minutes + dt.timezone;
22804   hour = (USHORT)dt.hours;
22805   day = (USHORT)dt.day;
22806   month = (USHORT)dt.month;
22807   year = (USHORT)dt.year;
22808
22809   /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
22810      http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
22811   /* Calculate the Julian days */
22812   now = day - 32076 +
22813     1461*(year + 4800 + (month - 14)/12)/4 +
22814     367*(month - 2 - (month - 14)/12*12)/12 -
22815     3*((year + 4900 + (month - 14)/12)/100)/4;
22816
22817   /* Add the fractional hours, mins and seconds */
22818   now += (hour + 12.0)/24.0;
22819   now += minute/1440.0;
22820   now += second/86400.0;
22821   *prNow = now;
22822 #ifdef SQLITE_TEST
22823   if( sqlite3_current_time ){
22824     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
22825   }
22826 #endif
22827   return 0;
22828 }
22829
22830 static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
22831   return 0;
22832 }
22833
22834 /*
22835 ** Initialize and deinitialize the operating system interface.
22836 */
22837 SQLITE_API int sqlite3_os_init(void){
22838   static sqlite3_vfs os2Vfs = {
22839     1,                 /* iVersion */
22840     sizeof(os2File),   /* szOsFile */
22841     CCHMAXPATH,        /* mxPathname */
22842     0,                 /* pNext */
22843     "os2",             /* zName */
22844     0,                 /* pAppData */
22845
22846     os2Open,           /* xOpen */
22847     os2Delete,         /* xDelete */
22848     os2Access,         /* xAccess */
22849     os2FullPathname,   /* xFullPathname */
22850     os2DlOpen,         /* xDlOpen */
22851     os2DlError,        /* xDlError */
22852     os2DlSym,          /* xDlSym */
22853     os2DlClose,        /* xDlClose */
22854     os2Randomness,     /* xRandomness */
22855     os2Sleep,          /* xSleep */
22856     os2CurrentTime,    /* xCurrentTime */
22857     os2GetLastError,   /* xGetLastError */
22858   };
22859   sqlite3_vfs_register(&os2Vfs, 1);
22860   initUconvObjects();
22861   return SQLITE_OK;
22862 }
22863 SQLITE_API int sqlite3_os_end(void){
22864   freeUconvObjects();
22865   return SQLITE_OK;
22866 }
22867
22868 #endif /* SQLITE_OS_OS2 */
22869
22870 /************** End of os_os2.c **********************************************/
22871 /************** Begin file os_unix.c *****************************************/
22872 /*
22873 ** 2004 May 22
22874 **
22875 ** The author disclaims copyright to this source code.  In place of
22876 ** a legal notice, here is a blessing:
22877 **
22878 **    May you do good and not evil.
22879 **    May you find forgiveness for yourself and forgive others.
22880 **    May you share freely, never taking more than you give.
22881 **
22882 ******************************************************************************
22883 **
22884 ** This file contains the VFS implementation for unix-like operating systems
22885 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
22886 **
22887 ** There are actually several different VFS implementations in this file.
22888 ** The differences are in the way that file locking is done.  The default
22889 ** implementation uses Posix Advisory Locks.  Alternative implementations
22890 ** use flock(), dot-files, various proprietary locking schemas, or simply
22891 ** skip locking all together.
22892 **
22893 ** This source file is organized into divisions where the logic for various
22894 ** subfunctions is contained within the appropriate division.  PLEASE
22895 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
22896 ** in the correct division and should be clearly labeled.
22897 **
22898 ** The layout of divisions is as follows:
22899 **
22900 **   *  General-purpose declarations and utility functions.
22901 **   *  Unique file ID logic used by VxWorks.
22902 **   *  Various locking primitive implementations (all except proxy locking):
22903 **      + for Posix Advisory Locks
22904 **      + for no-op locks
22905 **      + for dot-file locks
22906 **      + for flock() locking
22907 **      + for named semaphore locks (VxWorks only)
22908 **      + for AFP filesystem locks (MacOSX only)
22909 **   *  sqlite3_file methods not associated with locking.
22910 **   *  Definitions of sqlite3_io_methods objects for all locking
22911 **      methods plus "finder" functions for each locking method.
22912 **   *  sqlite3_vfs method implementations.
22913 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
22914 **   *  Definitions of sqlite3_vfs objects for all locking methods
22915 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
22916 */
22917 #if SQLITE_OS_UNIX              /* This file is used on unix only */
22918
22919 /*
22920 ** There are various methods for file locking used for concurrency
22921 ** control:
22922 **
22923 **   1. POSIX locking (the default),
22924 **   2. No locking,
22925 **   3. Dot-file locking,
22926 **   4. flock() locking,
22927 **   5. AFP locking (OSX only),
22928 **   6. Named POSIX semaphores (VXWorks only),
22929 **   7. proxy locking. (OSX only)
22930 **
22931 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
22932 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
22933 ** selection of the appropriate locking style based on the filesystem
22934 ** where the database is located.  
22935 */
22936 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
22937 #  if defined(__APPLE__)
22938 #    define SQLITE_ENABLE_LOCKING_STYLE 1
22939 #  else
22940 #    define SQLITE_ENABLE_LOCKING_STYLE 0
22941 #  endif
22942 #endif
22943
22944 /*
22945 ** Define the OS_VXWORKS pre-processor macro to 1 if building on 
22946 ** vxworks, or 0 otherwise.
22947 */
22948 #ifndef OS_VXWORKS
22949 #  if defined(__RTP__) || defined(_WRS_KERNEL)
22950 #    define OS_VXWORKS 1
22951 #  else
22952 #    define OS_VXWORKS 0
22953 #  endif
22954 #endif
22955
22956 /*
22957 ** These #defines should enable >2GB file support on Posix if the
22958 ** underlying operating system supports it.  If the OS lacks
22959 ** large file support, these should be no-ops.
22960 **
22961 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
22962 ** on the compiler command line.  This is necessary if you are compiling
22963 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
22964 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
22965 ** without this option, LFS is enable.  But LFS does not exist in the kernel
22966 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
22967 ** portability you should omit LFS.
22968 **
22969 ** The previous paragraph was written in 2005.  (This paragraph is written
22970 ** on 2008-11-28.) These days, all Linux kernels support large files, so
22971 ** you should probably leave LFS enabled.  But some embedded platforms might
22972 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
22973 */
22974 #ifndef SQLITE_DISABLE_LFS
22975 # define _LARGE_FILE       1
22976 # ifndef _FILE_OFFSET_BITS
22977 #   define _FILE_OFFSET_BITS 64
22978 # endif
22979 # define _LARGEFILE_SOURCE 1
22980 #endif
22981
22982 /*
22983 ** standard include files.
22984 */
22985 #include <sys/types.h>
22986 #include <sys/stat.h>
22987 #include <fcntl.h>
22988 #include <unistd.h>
22989 #include <sys/time.h>
22990 #include <errno.h>
22991 #ifndef SQLITE_OMIT_WAL
22992 #include <sys/mman.h>
22993 #endif
22994
22995 #if SQLITE_ENABLE_LOCKING_STYLE
22996 # include <sys/ioctl.h>
22997 # if OS_VXWORKS
22998 #  include <semaphore.h>
22999 #  include <limits.h>
23000 # else
23001 #  include <sys/file.h>
23002 #  include <sys/param.h>
23003 # endif
23004 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
23005
23006 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
23007 # include <sys/mount.h>
23008 #endif
23009
23010 /*
23011 ** Allowed values of unixFile.fsFlags
23012 */
23013 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
23014
23015 /*
23016 ** If we are to be thread-safe, include the pthreads header and define
23017 ** the SQLITE_UNIX_THREADS macro.
23018 */
23019 #if SQLITE_THREADSAFE
23020 # define SQLITE_UNIX_THREADS 1
23021 #endif
23022
23023 /*
23024 ** Default permissions when creating a new file
23025 */
23026 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
23027 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
23028 #endif
23029
23030 /*
23031  ** Default permissions when creating auto proxy dir
23032  */
23033 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
23034 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
23035 #endif
23036
23037 /*
23038 ** Maximum supported path-length.
23039 */
23040 #define MAX_PATHNAME 512
23041
23042 /*
23043 ** Only set the lastErrno if the error code is a real error and not 
23044 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
23045 */
23046 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
23047
23048 /* Forward references */
23049 typedef struct unixShm unixShm;               /* Connection shared memory */
23050 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
23051 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
23052 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
23053
23054 /*
23055 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
23056 ** cannot be closed immediately. In these cases, instances of the following
23057 ** structure are used to store the file descriptor while waiting for an
23058 ** opportunity to either close or reuse it.
23059 */
23060 struct UnixUnusedFd {
23061   int fd;                   /* File descriptor to close */
23062   int flags;                /* Flags this file descriptor was opened with */
23063   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
23064 };
23065
23066 /*
23067 ** The unixFile structure is subclass of sqlite3_file specific to the unix
23068 ** VFS implementations.
23069 */
23070 typedef struct unixFile unixFile;
23071 struct unixFile {
23072   sqlite3_io_methods const *pMethod;  /* Always the first entry */
23073   unixInodeInfo *pInode;              /* Info about locks on this inode */
23074   int h;                              /* The file descriptor */
23075   int dirfd;                          /* File descriptor for the directory */
23076   unsigned char eFileLock;            /* The type of lock held on this fd */
23077   int lastErrno;                      /* The unix errno from last I/O error */
23078   void *lockingContext;               /* Locking style specific state */
23079   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
23080   int fileFlags;                      /* Miscellanous flags */
23081   const char *zPath;                  /* Name of the file */
23082   unixShm *pShm;                      /* Shared memory segment information */
23083   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
23084 #if SQLITE_ENABLE_LOCKING_STYLE
23085   int openFlags;                      /* The flags specified at open() */
23086 #endif
23087 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
23088   unsigned fsFlags;                   /* cached details from statfs() */
23089 #endif
23090 #if OS_VXWORKS
23091   int isDelete;                       /* Delete on close if true */
23092   struct vxworksFileId *pId;          /* Unique file ID */
23093 #endif
23094 #ifndef NDEBUG
23095   /* The next group of variables are used to track whether or not the
23096   ** transaction counter in bytes 24-27 of database files are updated
23097   ** whenever any part of the database changes.  An assertion fault will
23098   ** occur if a file is updated without also updating the transaction
23099   ** counter.  This test is made to avoid new problems similar to the
23100   ** one described by ticket #3584. 
23101   */
23102   unsigned char transCntrChng;   /* True if the transaction counter changed */
23103   unsigned char dbUpdate;        /* True if any part of database file changed */
23104   unsigned char inNormalWrite;   /* True if in a normal write operation */
23105 #endif
23106 #ifdef SQLITE_TEST
23107   /* In test mode, increase the size of this structure a bit so that 
23108   ** it is larger than the struct CrashFile defined in test6.c.
23109   */
23110   char aPadding[32];
23111 #endif
23112 };
23113
23114 /*
23115 ** The following macros define bits in unixFile.fileFlags
23116 */
23117 #define SQLITE_WHOLE_FILE_LOCKING  0x0001   /* Use whole-file locking */
23118
23119 /*
23120 ** Include code that is common to all os_*.c files
23121 */
23122 /************** Include os_common.h in the middle of os_unix.c ***************/
23123 /************** Begin file os_common.h ***************************************/
23124 /*
23125 ** 2004 May 22
23126 **
23127 ** The author disclaims copyright to this source code.  In place of
23128 ** a legal notice, here is a blessing:
23129 **
23130 **    May you do good and not evil.
23131 **    May you find forgiveness for yourself and forgive others.
23132 **    May you share freely, never taking more than you give.
23133 **
23134 ******************************************************************************
23135 **
23136 ** This file contains macros and a little bit of code that is common to
23137 ** all of the platform-specific files (os_*.c) and is #included into those
23138 ** files.
23139 **
23140 ** This file should be #included by the os_*.c files only.  It is not a
23141 ** general purpose header file.
23142 */
23143 #ifndef _OS_COMMON_H_
23144 #define _OS_COMMON_H_
23145
23146 /*
23147 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
23148 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
23149 ** switch.  The following code should catch this problem at compile-time.
23150 */
23151 #ifdef MEMORY_DEBUG
23152 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
23153 #endif
23154
23155 #ifdef SQLITE_DEBUG
23156 SQLITE_PRIVATE int sqlite3OSTrace = 0;
23157 #define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
23158 #else
23159 #define OSTRACE(X)
23160 #endif
23161
23162 /*
23163 ** Macros for performance tracing.  Normally turned off.  Only works
23164 ** on i486 hardware.
23165 */
23166 #ifdef SQLITE_PERFORMANCE_TRACE
23167
23168 /* 
23169 ** hwtime.h contains inline assembler code for implementing 
23170 ** high-performance timing routines.
23171 */
23172 /************** Include hwtime.h in the middle of os_common.h ****************/
23173 /************** Begin file hwtime.h ******************************************/
23174 /*
23175 ** 2008 May 27
23176 **
23177 ** The author disclaims copyright to this source code.  In place of
23178 ** a legal notice, here is a blessing:
23179 **
23180 **    May you do good and not evil.
23181 **    May you find forgiveness for yourself and forgive others.
23182 **    May you share freely, never taking more than you give.
23183 **
23184 ******************************************************************************
23185 **
23186 ** This file contains inline asm code for retrieving "high-performance"
23187 ** counters for x86 class CPUs.
23188 */
23189 #ifndef _HWTIME_H_
23190 #define _HWTIME_H_
23191
23192 /*
23193 ** The following routine only works on pentium-class (or newer) processors.
23194 ** It uses the RDTSC opcode to read the cycle count value out of the
23195 ** processor and returns that value.  This can be used for high-res
23196 ** profiling.
23197 */
23198 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
23199       (defined(i386) || defined(__i386__) || defined(_M_IX86))
23200
23201   #if defined(__GNUC__)
23202
23203   __inline__ sqlite_uint64 sqlite3Hwtime(void){
23204      unsigned int lo, hi;
23205      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
23206      return (sqlite_uint64)hi << 32 | lo;
23207   }
23208
23209   #elif defined(_MSC_VER)
23210
23211   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
23212      __asm {
23213         rdtsc
23214         ret       ; return value at EDX:EAX
23215      }
23216   }
23217
23218   #endif
23219
23220 #elif (defined(__GNUC__) && defined(__x86_64__))
23221
23222   __inline__ sqlite_uint64 sqlite3Hwtime(void){
23223       unsigned long val;
23224       __asm__ __volatile__ ("rdtsc" : "=A" (val));
23225       return val;
23226   }
23227  
23228 #elif (defined(__GNUC__) && defined(__ppc__))
23229
23230   __inline__ sqlite_uint64 sqlite3Hwtime(void){
23231       unsigned long long retval;
23232       unsigned long junk;
23233       __asm__ __volatile__ ("\n\
23234           1:      mftbu   %1\n\
23235                   mftb    %L0\n\
23236                   mftbu   %0\n\
23237                   cmpw    %0,%1\n\
23238                   bne     1b"
23239                   : "=r" (retval), "=r" (junk));
23240       return retval;
23241   }
23242
23243 #else
23244
23245   #error Need implementation of sqlite3Hwtime() for your platform.
23246
23247   /*
23248   ** To compile without implementing sqlite3Hwtime() for your platform,
23249   ** you can remove the above #error and use the following
23250   ** stub function.  You will lose timing support for many
23251   ** of the debugging and testing utilities, but it should at
23252   ** least compile and run.
23253   */
23254 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
23255
23256 #endif
23257
23258 #endif /* !defined(_HWTIME_H_) */
23259
23260 /************** End of hwtime.h **********************************************/
23261 /************** Continuing where we left off in os_common.h ******************/
23262
23263 static sqlite_uint64 g_start;
23264 static sqlite_uint64 g_elapsed;
23265 #define TIMER_START       g_start=sqlite3Hwtime()
23266 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
23267 #define TIMER_ELAPSED     g_elapsed
23268 #else
23269 #define TIMER_START
23270 #define TIMER_END
23271 #define TIMER_ELAPSED     ((sqlite_uint64)0)
23272 #endif
23273
23274 /*
23275 ** If we compile with the SQLITE_TEST macro set, then the following block
23276 ** of code will give us the ability to simulate a disk I/O error.  This
23277 ** is used for testing the I/O recovery logic.
23278 */
23279 #ifdef SQLITE_TEST
23280 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
23281 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
23282 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
23283 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
23284 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
23285 SQLITE_API int sqlite3_diskfull_pending = 0;
23286 SQLITE_API int sqlite3_diskfull = 0;
23287 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
23288 #define SimulateIOError(CODE)  \
23289   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
23290        || sqlite3_io_error_pending-- == 1 )  \
23291               { local_ioerr(); CODE; }
23292 static void local_ioerr(){
23293   IOTRACE(("IOERR\n"));
23294   sqlite3_io_error_hit++;
23295   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
23296 }
23297 #define SimulateDiskfullError(CODE) \
23298    if( sqlite3_diskfull_pending ){ \
23299      if( sqlite3_diskfull_pending == 1 ){ \
23300        local_ioerr(); \
23301        sqlite3_diskfull = 1; \
23302        sqlite3_io_error_hit = 1; \
23303        CODE; \
23304      }else{ \
23305        sqlite3_diskfull_pending--; \
23306      } \
23307    }
23308 #else
23309 #define SimulateIOErrorBenign(X)
23310 #define SimulateIOError(A)
23311 #define SimulateDiskfullError(A)
23312 #endif
23313
23314 /*
23315 ** When testing, keep a count of the number of open files.
23316 */
23317 #ifdef SQLITE_TEST
23318 SQLITE_API int sqlite3_open_file_count = 0;
23319 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
23320 #else
23321 #define OpenCounter(X)
23322 #endif
23323
23324 #endif /* !defined(_OS_COMMON_H_) */
23325
23326 /************** End of os_common.h *******************************************/
23327 /************** Continuing where we left off in os_unix.c ********************/
23328
23329 /*
23330 ** Define various macros that are missing from some systems.
23331 */
23332 #ifndef O_LARGEFILE
23333 # define O_LARGEFILE 0
23334 #endif
23335 #ifdef SQLITE_DISABLE_LFS
23336 # undef O_LARGEFILE
23337 # define O_LARGEFILE 0
23338 #endif
23339 #ifndef O_NOFOLLOW
23340 # define O_NOFOLLOW 0
23341 #endif
23342 #ifndef O_BINARY
23343 # define O_BINARY 0
23344 #endif
23345
23346 /*
23347 ** The DJGPP compiler environment looks mostly like Unix, but it
23348 ** lacks the fcntl() system call.  So redefine fcntl() to be something
23349 ** that always succeeds.  This means that locking does not occur under
23350 ** DJGPP.  But it is DOS - what did you expect?
23351 */
23352 #ifdef __DJGPP__
23353 # define fcntl(A,B,C) 0
23354 #endif
23355
23356 /*
23357 ** The threadid macro resolves to the thread-id or to 0.  Used for
23358 ** testing and debugging only.
23359 */
23360 #if SQLITE_THREADSAFE
23361 #define threadid pthread_self()
23362 #else
23363 #define threadid 0
23364 #endif
23365
23366
23367 /*
23368 ** Helper functions to obtain and relinquish the global mutex. The
23369 ** global mutex is used to protect the unixInodeInfo and
23370 ** vxworksFileId objects used by this file, all of which may be 
23371 ** shared by multiple threads.
23372 **
23373 ** Function unixMutexHeld() is used to assert() that the global mutex 
23374 ** is held when required. This function is only used as part of assert() 
23375 ** statements. e.g.
23376 **
23377 **   unixEnterMutex()
23378 **     assert( unixMutexHeld() );
23379 **   unixEnterLeave()
23380 */
23381 static void unixEnterMutex(void){
23382   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23383 }
23384 static void unixLeaveMutex(void){
23385   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23386 }
23387 #ifdef SQLITE_DEBUG
23388 static int unixMutexHeld(void) {
23389   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23390 }
23391 #endif
23392
23393
23394 #ifdef SQLITE_DEBUG
23395 /*
23396 ** Helper function for printing out trace information from debugging
23397 ** binaries. This returns the string represetation of the supplied
23398 ** integer lock-type.
23399 */
23400 static const char *azFileLock(int eFileLock){
23401   switch( eFileLock ){
23402     case NO_LOCK: return "NONE";
23403     case SHARED_LOCK: return "SHARED";
23404     case RESERVED_LOCK: return "RESERVED";
23405     case PENDING_LOCK: return "PENDING";
23406     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
23407   }
23408   return "ERROR";
23409 }
23410 #endif
23411
23412 #ifdef SQLITE_LOCK_TRACE
23413 /*
23414 ** Print out information about all locking operations.
23415 **
23416 ** This routine is used for troubleshooting locks on multithreaded
23417 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
23418 ** command-line option on the compiler.  This code is normally
23419 ** turned off.
23420 */
23421 static int lockTrace(int fd, int op, struct flock *p){
23422   char *zOpName, *zType;
23423   int s;
23424   int savedErrno;
23425   if( op==F_GETLK ){
23426     zOpName = "GETLK";
23427   }else if( op==F_SETLK ){
23428     zOpName = "SETLK";
23429   }else{
23430     s = fcntl(fd, op, p);
23431     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
23432     return s;
23433   }
23434   if( p->l_type==F_RDLCK ){
23435     zType = "RDLCK";
23436   }else if( p->l_type==F_WRLCK ){
23437     zType = "WRLCK";
23438   }else if( p->l_type==F_UNLCK ){
23439     zType = "UNLCK";
23440   }else{
23441     assert( 0 );
23442   }
23443   assert( p->l_whence==SEEK_SET );
23444   s = fcntl(fd, op, p);
23445   savedErrno = errno;
23446   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
23447      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
23448      (int)p->l_pid, s);
23449   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
23450     struct flock l2;
23451     l2 = *p;
23452     fcntl(fd, F_GETLK, &l2);
23453     if( l2.l_type==F_RDLCK ){
23454       zType = "RDLCK";
23455     }else if( l2.l_type==F_WRLCK ){
23456       zType = "WRLCK";
23457     }else if( l2.l_type==F_UNLCK ){
23458       zType = "UNLCK";
23459     }else{
23460       assert( 0 );
23461     }
23462     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
23463        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
23464   }
23465   errno = savedErrno;
23466   return s;
23467 }
23468 #define fcntl lockTrace
23469 #endif /* SQLITE_LOCK_TRACE */
23470
23471
23472
23473 /*
23474 ** This routine translates a standard POSIX errno code into something
23475 ** useful to the clients of the sqlite3 functions.  Specifically, it is
23476 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
23477 ** and a variety of "please close the file descriptor NOW" errors into 
23478 ** SQLITE_IOERR
23479 ** 
23480 ** Errors during initialization of locks, or file system support for locks,
23481 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
23482 */
23483 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
23484   switch (posixError) {
23485   case 0: 
23486     return SQLITE_OK;
23487     
23488   case EAGAIN:
23489   case ETIMEDOUT:
23490   case EBUSY:
23491   case EINTR:
23492   case ENOLCK:  
23493     /* random NFS retry error, unless during file system support 
23494      * introspection, in which it actually means what it says */
23495     return SQLITE_BUSY;
23496     
23497   case EACCES: 
23498     /* EACCES is like EAGAIN during locking operations, but not any other time*/
23499     if( (sqliteIOErr == SQLITE_IOERR_LOCK) || 
23500         (sqliteIOErr == SQLITE_IOERR_UNLOCK) || 
23501         (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
23502         (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
23503       return SQLITE_BUSY;
23504     }
23505     /* else fall through */
23506   case EPERM: 
23507     return SQLITE_PERM;
23508     
23509   case EDEADLK:
23510     return SQLITE_IOERR_BLOCKED;
23511     
23512 #if EOPNOTSUPP!=ENOTSUP
23513   case EOPNOTSUPP: 
23514     /* something went terribly awry, unless during file system support 
23515      * introspection, in which it actually means what it says */
23516 #endif
23517 #ifdef ENOTSUP
23518   case ENOTSUP: 
23519     /* invalid fd, unless during file system support introspection, in which 
23520      * it actually means what it says */
23521 #endif
23522   case EIO:
23523   case EBADF:
23524   case EINVAL:
23525   case ENOTCONN:
23526   case ENODEV:
23527   case ENXIO:
23528   case ENOENT:
23529   case ESTALE:
23530   case ENOSYS:
23531     /* these should force the client to close the file and reconnect */
23532     
23533   default: 
23534     return sqliteIOErr;
23535   }
23536 }
23537
23538
23539
23540 /******************************************************************************
23541 ****************** Begin Unique File ID Utility Used By VxWorks ***************
23542 **
23543 ** On most versions of unix, we can get a unique ID for a file by concatenating
23544 ** the device number and the inode number.  But this does not work on VxWorks.
23545 ** On VxWorks, a unique file id must be based on the canonical filename.
23546 **
23547 ** A pointer to an instance of the following structure can be used as a
23548 ** unique file ID in VxWorks.  Each instance of this structure contains
23549 ** a copy of the canonical filename.  There is also a reference count.  
23550 ** The structure is reclaimed when the number of pointers to it drops to
23551 ** zero.
23552 **
23553 ** There are never very many files open at one time and lookups are not
23554 ** a performance-critical path, so it is sufficient to put these
23555 ** structures on a linked list.
23556 */
23557 struct vxworksFileId {
23558   struct vxworksFileId *pNext;  /* Next in a list of them all */
23559   int nRef;                     /* Number of references to this one */
23560   int nName;                    /* Length of the zCanonicalName[] string */
23561   char *zCanonicalName;         /* Canonical filename */
23562 };
23563
23564 #if OS_VXWORKS
23565 /* 
23566 ** All unique filenames are held on a linked list headed by this
23567 ** variable:
23568 */
23569 static struct vxworksFileId *vxworksFileList = 0;
23570
23571 /*
23572 ** Simplify a filename into its canonical form
23573 ** by making the following changes:
23574 **
23575 **  * removing any trailing and duplicate /
23576 **  * convert /./ into just /
23577 **  * convert /A/../ where A is any simple name into just /
23578 **
23579 ** Changes are made in-place.  Return the new name length.
23580 **
23581 ** The original filename is in z[0..n-1].  Return the number of
23582 ** characters in the simplified name.
23583 */
23584 static int vxworksSimplifyName(char *z, int n){
23585   int i, j;
23586   while( n>1 && z[n-1]=='/' ){ n--; }
23587   for(i=j=0; i<n; i++){
23588     if( z[i]=='/' ){
23589       if( z[i+1]=='/' ) continue;
23590       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
23591         i += 1;
23592         continue;
23593       }
23594       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
23595         while( j>0 && z[j-1]!='/' ){ j--; }
23596         if( j>0 ){ j--; }
23597         i += 2;
23598         continue;
23599       }
23600     }
23601     z[j++] = z[i];
23602   }
23603   z[j] = 0;
23604   return j;
23605 }
23606
23607 /*
23608 ** Find a unique file ID for the given absolute pathname.  Return
23609 ** a pointer to the vxworksFileId object.  This pointer is the unique
23610 ** file ID.
23611 **
23612 ** The nRef field of the vxworksFileId object is incremented before
23613 ** the object is returned.  A new vxworksFileId object is created
23614 ** and added to the global list if necessary.
23615 **
23616 ** If a memory allocation error occurs, return NULL.
23617 */
23618 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
23619   struct vxworksFileId *pNew;         /* search key and new file ID */
23620   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
23621   int n;                              /* Length of zAbsoluteName string */
23622
23623   assert( zAbsoluteName[0]=='/' );
23624   n = (int)strlen(zAbsoluteName);
23625   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
23626   if( pNew==0 ) return 0;
23627   pNew->zCanonicalName = (char*)&pNew[1];
23628   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
23629   n = vxworksSimplifyName(pNew->zCanonicalName, n);
23630
23631   /* Search for an existing entry that matching the canonical name.
23632   ** If found, increment the reference count and return a pointer to
23633   ** the existing file ID.
23634   */
23635   unixEnterMutex();
23636   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
23637     if( pCandidate->nName==n 
23638      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
23639     ){
23640        sqlite3_free(pNew);
23641        pCandidate->nRef++;
23642        unixLeaveMutex();
23643        return pCandidate;
23644     }
23645   }
23646
23647   /* No match was found.  We will make a new file ID */
23648   pNew->nRef = 1;
23649   pNew->nName = n;
23650   pNew->pNext = vxworksFileList;
23651   vxworksFileList = pNew;
23652   unixLeaveMutex();
23653   return pNew;
23654 }
23655
23656 /*
23657 ** Decrement the reference count on a vxworksFileId object.  Free
23658 ** the object when the reference count reaches zero.
23659 */
23660 static void vxworksReleaseFileId(struct vxworksFileId *pId){
23661   unixEnterMutex();
23662   assert( pId->nRef>0 );
23663   pId->nRef--;
23664   if( pId->nRef==0 ){
23665     struct vxworksFileId **pp;
23666     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
23667     assert( *pp==pId );
23668     *pp = pId->pNext;
23669     sqlite3_free(pId);
23670   }
23671   unixLeaveMutex();
23672 }
23673 #endif /* OS_VXWORKS */
23674 /*************** End of Unique File ID Utility Used By VxWorks ****************
23675 ******************************************************************************/
23676
23677
23678 /******************************************************************************
23679 *************************** Posix Advisory Locking ****************************
23680 **
23681 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
23682 ** section 6.5.2.2 lines 483 through 490 specify that when a process
23683 ** sets or clears a lock, that operation overrides any prior locks set
23684 ** by the same process.  It does not explicitly say so, but this implies
23685 ** that it overrides locks set by the same process using a different
23686 ** file descriptor.  Consider this test case:
23687 **
23688 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
23689 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
23690 **
23691 ** Suppose ./file1 and ./file2 are really the same file (because
23692 ** one is a hard or symbolic link to the other) then if you set
23693 ** an exclusive lock on fd1, then try to get an exclusive lock
23694 ** on fd2, it works.  I would have expected the second lock to
23695 ** fail since there was already a lock on the file due to fd1.
23696 ** But not so.  Since both locks came from the same process, the
23697 ** second overrides the first, even though they were on different
23698 ** file descriptors opened on different file names.
23699 **
23700 ** This means that we cannot use POSIX locks to synchronize file access
23701 ** among competing threads of the same process.  POSIX locks will work fine
23702 ** to synchronize access for threads in separate processes, but not
23703 ** threads within the same process.
23704 **
23705 ** To work around the problem, SQLite has to manage file locks internally
23706 ** on its own.  Whenever a new database is opened, we have to find the
23707 ** specific inode of the database file (the inode is determined by the
23708 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
23709 ** and check for locks already existing on that inode.  When locks are
23710 ** created or removed, we have to look at our own internal record of the
23711 ** locks to see if another thread has previously set a lock on that same
23712 ** inode.
23713 **
23714 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
23715 ** For VxWorks, we have to use the alternative unique ID system based on
23716 ** canonical filename and implemented in the previous division.)
23717 **
23718 ** The sqlite3_file structure for POSIX is no longer just an integer file
23719 ** descriptor.  It is now a structure that holds the integer file
23720 ** descriptor and a pointer to a structure that describes the internal
23721 ** locks on the corresponding inode.  There is one locking structure
23722 ** per inode, so if the same inode is opened twice, both unixFile structures
23723 ** point to the same locking structure.  The locking structure keeps
23724 ** a reference count (so we will know when to delete it) and a "cnt"
23725 ** field that tells us its internal lock status.  cnt==0 means the
23726 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
23727 ** cnt>0 means there are cnt shared locks on the file.
23728 **
23729 ** Any attempt to lock or unlock a file first checks the locking
23730 ** structure.  The fcntl() system call is only invoked to set a 
23731 ** POSIX lock if the internal lock structure transitions between
23732 ** a locked and an unlocked state.
23733 **
23734 ** But wait:  there are yet more problems with POSIX advisory locks.
23735 **
23736 ** If you close a file descriptor that points to a file that has locks,
23737 ** all locks on that file that are owned by the current process are
23738 ** released.  To work around this problem, each unixInodeInfo object
23739 ** maintains a count of the number of pending locks on tha inode.
23740 ** When an attempt is made to close an unixFile, if there are
23741 ** other unixFile open on the same inode that are holding locks, the call
23742 ** to close() the file descriptor is deferred until all of the locks clear.
23743 ** The unixInodeInfo structure keeps a list of file descriptors that need to
23744 ** be closed and that list is walked (and cleared) when the last lock
23745 ** clears.
23746 **
23747 ** Yet another problem:  LinuxThreads do not play well with posix locks.
23748 **
23749 ** Many older versions of linux use the LinuxThreads library which is
23750 ** not posix compliant.  Under LinuxThreads, a lock created by thread
23751 ** A cannot be modified or overridden by a different thread B.
23752 ** Only thread A can modify the lock.  Locking behavior is correct
23753 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
23754 ** on linux - with NPTL a lock created by thread A can override locks
23755 ** in thread B.  But there is no way to know at compile-time which
23756 ** threading library is being used.  So there is no way to know at
23757 ** compile-time whether or not thread A can override locks on thread B.
23758 ** One has to do a run-time check to discover the behavior of the
23759 ** current process.
23760 **
23761 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
23762 ** was dropped beginning with version 3.7.0.  SQLite will still work with
23763 ** LinuxThreads provided that (1) there is no more than one connection 
23764 ** per database file in the same process and (2) database connections
23765 ** do not move across threads.
23766 */
23767
23768 /*
23769 ** An instance of the following structure serves as the key used
23770 ** to locate a particular unixInodeInfo object.
23771 */
23772 struct unixFileId {
23773   dev_t dev;                  /* Device number */
23774 #if OS_VXWORKS
23775   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
23776 #else
23777   ino_t ino;                  /* Inode number */
23778 #endif
23779 };
23780
23781 /*
23782 ** An instance of the following structure is allocated for each open
23783 ** inode.  Or, on LinuxThreads, there is one of these structures for
23784 ** each inode opened by each thread.
23785 **
23786 ** A single inode can have multiple file descriptors, so each unixFile
23787 ** structure contains a pointer to an instance of this object and this
23788 ** object keeps a count of the number of unixFile pointing to it.
23789 */
23790 struct unixInodeInfo {
23791   struct unixFileId fileId;       /* The lookup key */
23792   int nShared;                    /* Number of SHARED locks held */
23793   int eFileLock;                  /* One of SHARED_LOCK, RESERVED_LOCK etc. */
23794   int nRef;                       /* Number of pointers to this structure */
23795   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
23796   int nLock;                      /* Number of outstanding file locks */
23797   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
23798   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
23799   unixInodeInfo *pPrev;           /*    .... doubly linked */
23800 #if defined(SQLITE_ENABLE_LOCKING_STYLE)
23801   unsigned long long sharedByte;  /* for AFP simulated shared lock */
23802 #endif
23803 #if OS_VXWORKS
23804   sem_t *pSem;                    /* Named POSIX semaphore */
23805   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
23806 #endif
23807 };
23808
23809 /*
23810 ** A lists of all unixInodeInfo objects.
23811 */
23812 static unixInodeInfo *inodeList = 0;
23813
23814 /*
23815 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
23816 ** If all such file descriptors are closed without error, the list is
23817 ** cleared and SQLITE_OK returned.
23818 **
23819 ** Otherwise, if an error occurs, then successfully closed file descriptor
23820 ** entries are removed from the list, and SQLITE_IOERR_CLOSE returned. 
23821 ** not deleted and SQLITE_IOERR_CLOSE returned.
23822 */ 
23823 static int closePendingFds(unixFile *pFile){
23824   int rc = SQLITE_OK;
23825   unixInodeInfo *pInode = pFile->pInode;
23826   UnixUnusedFd *pError = 0;
23827   UnixUnusedFd *p;
23828   UnixUnusedFd *pNext;
23829   for(p=pInode->pUnused; p; p=pNext){
23830     pNext = p->pNext;
23831     if( close(p->fd) ){
23832       pFile->lastErrno = errno;
23833       rc = SQLITE_IOERR_CLOSE;
23834       p->pNext = pError;
23835       pError = p;
23836     }else{
23837       sqlite3_free(p);
23838     }
23839   }
23840   pInode->pUnused = pError;
23841   return rc;
23842 }
23843
23844 /*
23845 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
23846 **
23847 ** The mutex entered using the unixEnterMutex() function must be held
23848 ** when this function is called.
23849 */
23850 static void releaseInodeInfo(unixFile *pFile){
23851   unixInodeInfo *pInode = pFile->pInode;
23852   assert( unixMutexHeld() );
23853   if( pInode ){
23854     pInode->nRef--;
23855     if( pInode->nRef==0 ){
23856       assert( pInode->pShmNode==0 );
23857       closePendingFds(pFile);
23858       if( pInode->pPrev ){
23859         assert( pInode->pPrev->pNext==pInode );
23860         pInode->pPrev->pNext = pInode->pNext;
23861       }else{
23862         assert( inodeList==pInode );
23863         inodeList = pInode->pNext;
23864       }
23865       if( pInode->pNext ){
23866         assert( pInode->pNext->pPrev==pInode );
23867         pInode->pNext->pPrev = pInode->pPrev;
23868       }
23869       sqlite3_free(pInode);
23870     }
23871   }
23872 }
23873
23874 /*
23875 ** Given a file descriptor, locate the unixInodeInfo object that
23876 ** describes that file descriptor.  Create a new one if necessary.  The
23877 ** return value might be uninitialized if an error occurs.
23878 **
23879 ** The mutex entered using the unixEnterMutex() function must be held
23880 ** when this function is called.
23881 **
23882 ** Return an appropriate error code.
23883 */
23884 static int findInodeInfo(
23885   unixFile *pFile,               /* Unix file with file desc used in the key */
23886   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
23887 ){
23888   int rc;                        /* System call return code */
23889   int fd;                        /* The file descriptor for pFile */
23890   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
23891   struct stat statbuf;           /* Low-level file information */
23892   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
23893
23894   assert( unixMutexHeld() );
23895
23896   /* Get low-level information about the file that we can used to
23897   ** create a unique name for the file.
23898   */
23899   fd = pFile->h;
23900   rc = fstat(fd, &statbuf);
23901   if( rc!=0 ){
23902     pFile->lastErrno = errno;
23903 #ifdef EOVERFLOW
23904     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
23905 #endif
23906     return SQLITE_IOERR;
23907   }
23908
23909 #ifdef __APPLE__
23910   /* On OS X on an msdos filesystem, the inode number is reported
23911   ** incorrectly for zero-size files.  See ticket #3260.  To work
23912   ** around this problem (we consider it a bug in OS X, not SQLite)
23913   ** we always increase the file size to 1 by writing a single byte
23914   ** prior to accessing the inode number.  The one byte written is
23915   ** an ASCII 'S' character which also happens to be the first byte
23916   ** in the header of every SQLite database.  In this way, if there
23917   ** is a race condition such that another thread has already populated
23918   ** the first page of the database, no damage is done.
23919   */
23920   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
23921     rc = write(fd, "S", 1);
23922     if( rc!=1 ){
23923       pFile->lastErrno = errno;
23924       return SQLITE_IOERR;
23925     }
23926     rc = fstat(fd, &statbuf);
23927     if( rc!=0 ){
23928       pFile->lastErrno = errno;
23929       return SQLITE_IOERR;
23930     }
23931   }
23932 #endif
23933
23934   memset(&fileId, 0, sizeof(fileId));
23935   fileId.dev = statbuf.st_dev;
23936 #if OS_VXWORKS
23937   fileId.pId = pFile->pId;
23938 #else
23939   fileId.ino = statbuf.st_ino;
23940 #endif
23941   pInode = inodeList;
23942   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
23943     pInode = pInode->pNext;
23944   }
23945   if( pInode==0 ){
23946     pInode = sqlite3_malloc( sizeof(*pInode) );
23947     if( pInode==0 ){
23948       return SQLITE_NOMEM;
23949     }
23950     memset(pInode, 0, sizeof(*pInode));
23951     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
23952     pInode->nRef = 1;
23953     pInode->pNext = inodeList;
23954     pInode->pPrev = 0;
23955     if( inodeList ) inodeList->pPrev = pInode;
23956     inodeList = pInode;
23957   }else{
23958     pInode->nRef++;
23959   }
23960   *ppInode = pInode;
23961   return SQLITE_OK;
23962 }
23963
23964
23965 /*
23966 ** This routine checks if there is a RESERVED lock held on the specified
23967 ** file by this or any other process. If such a lock is held, set *pResOut
23968 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
23969 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23970 */
23971 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
23972   int rc = SQLITE_OK;
23973   int reserved = 0;
23974   unixFile *pFile = (unixFile*)id;
23975
23976   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23977
23978   assert( pFile );
23979   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
23980
23981   /* Check if a thread in this process holds such a lock */
23982   if( pFile->pInode->eFileLock>SHARED_LOCK ){
23983     reserved = 1;
23984   }
23985
23986   /* Otherwise see if some other process holds it.
23987   */
23988 #ifndef __DJGPP__
23989   if( !reserved ){
23990     struct flock lock;
23991     lock.l_whence = SEEK_SET;
23992     lock.l_start = RESERVED_BYTE;
23993     lock.l_len = 1;
23994     lock.l_type = F_WRLCK;
23995     if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
23996       int tErrno = errno;
23997       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
23998       pFile->lastErrno = tErrno;
23999     } else if( lock.l_type!=F_UNLCK ){
24000       reserved = 1;
24001     }
24002   }
24003 #endif
24004   
24005   unixLeaveMutex();
24006   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
24007
24008   *pResOut = reserved;
24009   return rc;
24010 }
24011
24012 /*
24013 ** Lock the file with the lock specified by parameter eFileLock - one
24014 ** of the following:
24015 **
24016 **     (1) SHARED_LOCK
24017 **     (2) RESERVED_LOCK
24018 **     (3) PENDING_LOCK
24019 **     (4) EXCLUSIVE_LOCK
24020 **
24021 ** Sometimes when requesting one lock state, additional lock states
24022 ** are inserted in between.  The locking might fail on one of the later
24023 ** transitions leaving the lock state different from what it started but
24024 ** still short of its goal.  The following chart shows the allowed
24025 ** transitions and the inserted intermediate states:
24026 **
24027 **    UNLOCKED -> SHARED
24028 **    SHARED -> RESERVED
24029 **    SHARED -> (PENDING) -> EXCLUSIVE
24030 **    RESERVED -> (PENDING) -> EXCLUSIVE
24031 **    PENDING -> EXCLUSIVE
24032 **
24033 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24034 ** routine to lower a locking level.
24035 */
24036 static int unixLock(sqlite3_file *id, int eFileLock){
24037   /* The following describes the implementation of the various locks and
24038   ** lock transitions in terms of the POSIX advisory shared and exclusive
24039   ** lock primitives (called read-locks and write-locks below, to avoid
24040   ** confusion with SQLite lock names). The algorithms are complicated
24041   ** slightly in order to be compatible with windows systems simultaneously
24042   ** accessing the same database file, in case that is ever required.
24043   **
24044   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
24045   ** byte', each single bytes at well known offsets, and the 'shared byte
24046   ** range', a range of 510 bytes at a well known offset.
24047   **
24048   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
24049   ** byte'.  If this is successful, a random byte from the 'shared byte
24050   ** range' is read-locked and the lock on the 'pending byte' released.
24051   **
24052   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
24053   ** A RESERVED lock is implemented by grabbing a write-lock on the
24054   ** 'reserved byte'. 
24055   **
24056   ** A process may only obtain a PENDING lock after it has obtained a
24057   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
24058   ** on the 'pending byte'. This ensures that no new SHARED locks can be
24059   ** obtained, but existing SHARED locks are allowed to persist. A process
24060   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
24061   ** This property is used by the algorithm for rolling back a journal file
24062   ** after a crash.
24063   **
24064   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
24065   ** implemented by obtaining a write-lock on the entire 'shared byte
24066   ** range'. Since all other locks require a read-lock on one of the bytes
24067   ** within this range, this ensures that no other locks are held on the
24068   ** database. 
24069   **
24070   ** The reason a single byte cannot be used instead of the 'shared byte
24071   ** range' is that some versions of windows do not support read-locks. By
24072   ** locking a random byte from a range, concurrent SHARED locks may exist
24073   ** even if the locking primitive used is always a write-lock.
24074   */
24075   int rc = SQLITE_OK;
24076   unixFile *pFile = (unixFile*)id;
24077   unixInodeInfo *pInode = pFile->pInode;
24078   struct flock lock;
24079   int s = 0;
24080   int tErrno = 0;
24081
24082   assert( pFile );
24083   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
24084       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
24085       azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
24086
24087   /* If there is already a lock of this type or more restrictive on the
24088   ** unixFile, do nothing. Don't use the end_lock: exit path, as
24089   ** unixEnterMutex() hasn't been called yet.
24090   */
24091   if( pFile->eFileLock>=eFileLock ){
24092     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
24093             azFileLock(eFileLock)));
24094     return SQLITE_OK;
24095   }
24096
24097   /* Make sure the locking sequence is correct.
24098   **  (1) We never move from unlocked to anything higher than shared lock.
24099   **  (2) SQLite never explicitly requests a pendig lock.
24100   **  (3) A shared lock is always held when a reserve lock is requested.
24101   */
24102   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
24103   assert( eFileLock!=PENDING_LOCK );
24104   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
24105
24106   /* This mutex is needed because pFile->pInode is shared across threads
24107   */
24108   unixEnterMutex();
24109   pInode = pFile->pInode;
24110
24111   /* If some thread using this PID has a lock via a different unixFile*
24112   ** handle that precludes the requested lock, return BUSY.
24113   */
24114   if( (pFile->eFileLock!=pInode->eFileLock && 
24115           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
24116   ){
24117     rc = SQLITE_BUSY;
24118     goto end_lock;
24119   }
24120
24121   /* If a SHARED lock is requested, and some thread using this PID already
24122   ** has a SHARED or RESERVED lock, then increment reference counts and
24123   ** return SQLITE_OK.
24124   */
24125   if( eFileLock==SHARED_LOCK && 
24126       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
24127     assert( eFileLock==SHARED_LOCK );
24128     assert( pFile->eFileLock==0 );
24129     assert( pInode->nShared>0 );
24130     pFile->eFileLock = SHARED_LOCK;
24131     pInode->nShared++;
24132     pInode->nLock++;
24133     goto end_lock;
24134   }
24135
24136
24137   /* A PENDING lock is needed before acquiring a SHARED lock and before
24138   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
24139   ** be released.
24140   */
24141   lock.l_len = 1L;
24142   lock.l_whence = SEEK_SET;
24143   if( eFileLock==SHARED_LOCK 
24144       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
24145   ){
24146     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
24147     lock.l_start = PENDING_BYTE;
24148     s = fcntl(pFile->h, F_SETLK, &lock);
24149     if( s==(-1) ){
24150       tErrno = errno;
24151       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24152       if( IS_LOCK_ERROR(rc) ){
24153         pFile->lastErrno = tErrno;
24154       }
24155       goto end_lock;
24156     }
24157   }
24158
24159
24160   /* If control gets to this point, then actually go ahead and make
24161   ** operating system calls for the specified lock.
24162   */
24163   if( eFileLock==SHARED_LOCK ){
24164     assert( pInode->nShared==0 );
24165     assert( pInode->eFileLock==0 );
24166
24167     /* Now get the read-lock */
24168     lock.l_start = SHARED_FIRST;
24169     lock.l_len = SHARED_SIZE;
24170     if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
24171       tErrno = errno;
24172     }
24173     /* Drop the temporary PENDING lock */
24174     lock.l_start = PENDING_BYTE;
24175     lock.l_len = 1L;
24176     lock.l_type = F_UNLCK;
24177     if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
24178       if( s != -1 ){
24179         /* This could happen with a network mount */
24180         tErrno = errno; 
24181         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 
24182         if( IS_LOCK_ERROR(rc) ){
24183           pFile->lastErrno = tErrno;
24184         }
24185         goto end_lock;
24186       }
24187     }
24188     if( s==(-1) ){
24189       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24190       if( IS_LOCK_ERROR(rc) ){
24191         pFile->lastErrno = tErrno;
24192       }
24193     }else{
24194       pFile->eFileLock = SHARED_LOCK;
24195       pInode->nLock++;
24196       pInode->nShared = 1;
24197     }
24198   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
24199     /* We are trying for an exclusive lock but another thread in this
24200     ** same process is still holding a shared lock. */
24201     rc = SQLITE_BUSY;
24202   }else{
24203     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
24204     ** assumed that there is a SHARED or greater lock on the file
24205     ** already.
24206     */
24207     assert( 0!=pFile->eFileLock );
24208     lock.l_type = F_WRLCK;
24209     switch( eFileLock ){
24210       case RESERVED_LOCK:
24211         lock.l_start = RESERVED_BYTE;
24212         break;
24213       case EXCLUSIVE_LOCK:
24214         lock.l_start = SHARED_FIRST;
24215         lock.l_len = SHARED_SIZE;
24216         break;
24217       default:
24218         assert(0);
24219     }
24220     s = fcntl(pFile->h, F_SETLK, &lock);
24221     if( s==(-1) ){
24222       tErrno = errno;
24223       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24224       if( IS_LOCK_ERROR(rc) ){
24225         pFile->lastErrno = tErrno;
24226       }
24227     }
24228   }
24229   
24230
24231 #ifndef NDEBUG
24232   /* Set up the transaction-counter change checking flags when
24233   ** transitioning from a SHARED to a RESERVED lock.  The change
24234   ** from SHARED to RESERVED marks the beginning of a normal
24235   ** write operation (not a hot journal rollback).
24236   */
24237   if( rc==SQLITE_OK
24238    && pFile->eFileLock<=SHARED_LOCK
24239    && eFileLock==RESERVED_LOCK
24240   ){
24241     pFile->transCntrChng = 0;
24242     pFile->dbUpdate = 0;
24243     pFile->inNormalWrite = 1;
24244   }
24245 #endif
24246
24247
24248   if( rc==SQLITE_OK ){
24249     pFile->eFileLock = eFileLock;
24250     pInode->eFileLock = eFileLock;
24251   }else if( eFileLock==EXCLUSIVE_LOCK ){
24252     pFile->eFileLock = PENDING_LOCK;
24253     pInode->eFileLock = PENDING_LOCK;
24254   }
24255
24256 end_lock:
24257   unixLeaveMutex();
24258   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), 
24259       rc==SQLITE_OK ? "ok" : "failed"));
24260   return rc;
24261 }
24262
24263 /*
24264 ** Add the file descriptor used by file handle pFile to the corresponding
24265 ** pUnused list.
24266 */
24267 static void setPendingFd(unixFile *pFile){
24268   unixInodeInfo *pInode = pFile->pInode;
24269   UnixUnusedFd *p = pFile->pUnused;
24270   p->pNext = pInode->pUnused;
24271   pInode->pUnused = p;
24272   pFile->h = -1;
24273   pFile->pUnused = 0;
24274 }
24275
24276 /*
24277 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24278 ** must be either NO_LOCK or SHARED_LOCK.
24279 **
24280 ** If the locking level of the file descriptor is already at or below
24281 ** the requested locking level, this routine is a no-op.
24282 ** 
24283 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
24284 ** the byte range is divided into 2 parts and the first part is unlocked then
24285 ** set to a read lock, then the other part is simply unlocked.  This works 
24286 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to 
24287 ** remove the write lock on a region when a read lock is set.
24288 */
24289 static int _posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
24290   unixFile *pFile = (unixFile*)id;
24291   unixInodeInfo *pInode;
24292   struct flock lock;
24293   int rc = SQLITE_OK;
24294   int h;
24295   int tErrno;                      /* Error code from system call errors */
24296
24297   assert( pFile );
24298   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
24299       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
24300       getpid()));
24301
24302   assert( eFileLock<=SHARED_LOCK );
24303   if( pFile->eFileLock<=eFileLock ){
24304     return SQLITE_OK;
24305   }
24306   unixEnterMutex();
24307   h = pFile->h;
24308   pInode = pFile->pInode;
24309   assert( pInode->nShared!=0 );
24310   if( pFile->eFileLock>SHARED_LOCK ){
24311     assert( pInode->eFileLock==pFile->eFileLock );
24312     SimulateIOErrorBenign(1);
24313     SimulateIOError( h=(-1) )
24314     SimulateIOErrorBenign(0);
24315
24316 #ifndef NDEBUG
24317     /* When reducing a lock such that other processes can start
24318     ** reading the database file again, make sure that the
24319     ** transaction counter was updated if any part of the database
24320     ** file changed.  If the transaction counter is not updated,
24321     ** other connections to the same file might not realize that
24322     ** the file has changed and hence might not know to flush their
24323     ** cache.  The use of a stale cache can lead to database corruption.
24324     */
24325 #if 0
24326     assert( pFile->inNormalWrite==0
24327          || pFile->dbUpdate==0
24328          || pFile->transCntrChng==1 );
24329 #endif
24330     pFile->inNormalWrite = 0;
24331 #endif
24332
24333     /* downgrading to a shared lock on NFS involves clearing the write lock
24334     ** before establishing the readlock - to avoid a race condition we downgrade
24335     ** the lock in 2 blocks, so that part of the range will be covered by a 
24336     ** write lock until the rest is covered by a read lock:
24337     **  1:   [WWWWW]
24338     **  2:   [....W]
24339     **  3:   [RRRRW]
24340     **  4:   [RRRR.]
24341     */
24342     if( eFileLock==SHARED_LOCK ){
24343       if( handleNFSUnlock ){
24344         off_t divSize = SHARED_SIZE - 1;
24345         
24346         lock.l_type = F_UNLCK;
24347         lock.l_whence = SEEK_SET;
24348         lock.l_start = SHARED_FIRST;
24349         lock.l_len = divSize;
24350         if( fcntl(h, F_SETLK, &lock)==(-1) ){
24351           tErrno = errno;
24352           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24353           if( IS_LOCK_ERROR(rc) ){
24354             pFile->lastErrno = tErrno;
24355           }
24356           goto end_unlock;
24357         }
24358         lock.l_type = F_RDLCK;
24359         lock.l_whence = SEEK_SET;
24360         lock.l_start = SHARED_FIRST;
24361         lock.l_len = divSize;
24362         if( fcntl(h, F_SETLK, &lock)==(-1) ){
24363           tErrno = errno;
24364           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
24365           if( IS_LOCK_ERROR(rc) ){
24366             pFile->lastErrno = tErrno;
24367           }
24368           goto end_unlock;
24369         }
24370         lock.l_type = F_UNLCK;
24371         lock.l_whence = SEEK_SET;
24372         lock.l_start = SHARED_FIRST+divSize;
24373         lock.l_len = SHARED_SIZE-divSize;
24374         if( fcntl(h, F_SETLK, &lock)==(-1) ){
24375           tErrno = errno;
24376           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24377           if( IS_LOCK_ERROR(rc) ){
24378             pFile->lastErrno = tErrno;
24379           }
24380           goto end_unlock;
24381         }
24382       }else{
24383         lock.l_type = F_RDLCK;
24384         lock.l_whence = SEEK_SET;
24385         lock.l_start = SHARED_FIRST;
24386         lock.l_len = SHARED_SIZE;
24387         if( fcntl(h, F_SETLK, &lock)==(-1) ){
24388           tErrno = errno;
24389           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
24390           if( IS_LOCK_ERROR(rc) ){
24391             pFile->lastErrno = tErrno;
24392           }
24393           goto end_unlock;
24394         }
24395       }
24396     }
24397     lock.l_type = F_UNLCK;
24398     lock.l_whence = SEEK_SET;
24399     lock.l_start = PENDING_BYTE;
24400     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
24401     if( fcntl(h, F_SETLK, &lock)!=(-1) ){
24402       pInode->eFileLock = SHARED_LOCK;
24403     }else{
24404       tErrno = errno;
24405       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24406       if( IS_LOCK_ERROR(rc) ){
24407         pFile->lastErrno = tErrno;
24408       }
24409       goto end_unlock;
24410     }
24411   }
24412   if( eFileLock==NO_LOCK ){
24413     /* Decrement the shared lock counter.  Release the lock using an
24414     ** OS call only when all threads in this same process have released
24415     ** the lock.
24416     */
24417     pInode->nShared--;
24418     if( pInode->nShared==0 ){
24419       lock.l_type = F_UNLCK;
24420       lock.l_whence = SEEK_SET;
24421       lock.l_start = lock.l_len = 0L;
24422       SimulateIOErrorBenign(1);
24423       SimulateIOError( h=(-1) )
24424       SimulateIOErrorBenign(0);
24425       if( fcntl(h, F_SETLK, &lock)!=(-1) ){
24426         pInode->eFileLock = NO_LOCK;
24427       }else{
24428         tErrno = errno;
24429         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24430         if( IS_LOCK_ERROR(rc) ){
24431           pFile->lastErrno = tErrno;
24432         }
24433         pInode->eFileLock = NO_LOCK;
24434         pFile->eFileLock = NO_LOCK;
24435       }
24436     }
24437
24438     /* Decrement the count of locks against this same file.  When the
24439     ** count reaches zero, close any other file descriptors whose close
24440     ** was deferred because of outstanding locks.
24441     */
24442     pInode->nLock--;
24443     assert( pInode->nLock>=0 );
24444     if( pInode->nLock==0 ){
24445       int rc2 = closePendingFds(pFile);
24446       if( rc==SQLITE_OK ){
24447         rc = rc2;
24448       }
24449     }
24450   }
24451         
24452 end_unlock:
24453   unixLeaveMutex();
24454   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
24455   return rc;
24456 }
24457
24458 /*
24459 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24460 ** must be either NO_LOCK or SHARED_LOCK.
24461 **
24462 ** If the locking level of the file descriptor is already at or below
24463 ** the requested locking level, this routine is a no-op.
24464 */
24465 static int unixUnlock(sqlite3_file *id, int eFileLock){
24466   return _posixUnlock(id, eFileLock, 0);
24467 }
24468
24469 /*
24470 ** This function performs the parts of the "close file" operation 
24471 ** common to all locking schemes. It closes the directory and file
24472 ** handles, if they are valid, and sets all fields of the unixFile
24473 ** structure to 0.
24474 **
24475 ** It is *not* necessary to hold the mutex when this routine is called,
24476 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
24477 ** vxworksReleaseFileId() routine.
24478 */
24479 static int closeUnixFile(sqlite3_file *id){
24480   unixFile *pFile = (unixFile*)id;
24481   if( pFile ){
24482     if( pFile->dirfd>=0 ){
24483       int err = close(pFile->dirfd);
24484       if( err ){
24485         pFile->lastErrno = errno;
24486         return SQLITE_IOERR_DIR_CLOSE;
24487       }else{
24488         pFile->dirfd=-1;
24489       }
24490     }
24491     if( pFile->h>=0 ){
24492       int err = close(pFile->h);
24493       if( err ){
24494         pFile->lastErrno = errno;
24495         return SQLITE_IOERR_CLOSE;
24496       }
24497     }
24498 #if OS_VXWORKS
24499     if( pFile->pId ){
24500       if( pFile->isDelete ){
24501         unlink(pFile->pId->zCanonicalName);
24502       }
24503       vxworksReleaseFileId(pFile->pId);
24504       pFile->pId = 0;
24505     }
24506 #endif
24507     OSTRACE(("CLOSE   %-3d\n", pFile->h));
24508     OpenCounter(-1);
24509     sqlite3_free(pFile->pUnused);
24510     memset(pFile, 0, sizeof(unixFile));
24511   }
24512   return SQLITE_OK;
24513 }
24514
24515 /*
24516 ** Close a file.
24517 */
24518 static int unixClose(sqlite3_file *id){
24519   int rc = SQLITE_OK;
24520   if( id ){
24521     unixFile *pFile = (unixFile *)id;
24522     unixUnlock(id, NO_LOCK);
24523     unixEnterMutex();
24524     if( pFile->pInode && pFile->pInode->nLock ){
24525       /* If there are outstanding locks, do not actually close the file just
24526       ** yet because that would clear those locks.  Instead, add the file
24527       ** descriptor to pInode->pUnused list.  It will be automatically closed 
24528       ** when the last lock is cleared.
24529       */
24530       setPendingFd(pFile);
24531     }
24532     releaseInodeInfo(pFile);
24533     rc = closeUnixFile(id);
24534     unixLeaveMutex();
24535   }
24536   return rc;
24537 }
24538
24539 /************** End of the posix advisory lock implementation *****************
24540 ******************************************************************************/
24541
24542 /******************************************************************************
24543 ****************************** No-op Locking **********************************
24544 **
24545 ** Of the various locking implementations available, this is by far the
24546 ** simplest:  locking is ignored.  No attempt is made to lock the database
24547 ** file for reading or writing.
24548 **
24549 ** This locking mode is appropriate for use on read-only databases
24550 ** (ex: databases that are burned into CD-ROM, for example.)  It can
24551 ** also be used if the application employs some external mechanism to
24552 ** prevent simultaneous access of the same database by two or more
24553 ** database connections.  But there is a serious risk of database
24554 ** corruption if this locking mode is used in situations where multiple
24555 ** database connections are accessing the same database file at the same
24556 ** time and one or more of those connections are writing.
24557 */
24558
24559 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
24560   UNUSED_PARAMETER(NotUsed);
24561   *pResOut = 0;
24562   return SQLITE_OK;
24563 }
24564 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
24565   UNUSED_PARAMETER2(NotUsed, NotUsed2);
24566   return SQLITE_OK;
24567 }
24568 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
24569   UNUSED_PARAMETER2(NotUsed, NotUsed2);
24570   return SQLITE_OK;
24571 }
24572
24573 /*
24574 ** Close the file.
24575 */
24576 static int nolockClose(sqlite3_file *id) {
24577   return closeUnixFile(id);
24578 }
24579
24580 /******************* End of the no-op lock implementation *********************
24581 ******************************************************************************/
24582
24583 /******************************************************************************
24584 ************************* Begin dot-file Locking ******************************
24585 **
24586 ** The dotfile locking implementation uses the existance of separate lock
24587 ** files in order to control access to the database.  This works on just
24588 ** about every filesystem imaginable.  But there are serious downsides:
24589 **
24590 **    (1)  There is zero concurrency.  A single reader blocks all other
24591 **         connections from reading or writing the database.
24592 **
24593 **    (2)  An application crash or power loss can leave stale lock files
24594 **         sitting around that need to be cleared manually.
24595 **
24596 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
24597 ** other locking strategy is available.
24598 **
24599 ** Dotfile locking works by creating a file in the same directory as the
24600 ** database and with the same name but with a ".lock" extension added.
24601 ** The existance of a lock file implies an EXCLUSIVE lock.  All other lock
24602 ** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
24603 */
24604
24605 /*
24606 ** The file suffix added to the data base filename in order to create the
24607 ** lock file.
24608 */
24609 #define DOTLOCK_SUFFIX ".lock"
24610
24611 /*
24612 ** This routine checks if there is a RESERVED lock held on the specified
24613 ** file by this or any other process. If such a lock is held, set *pResOut
24614 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24615 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24616 **
24617 ** In dotfile locking, either a lock exists or it does not.  So in this
24618 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
24619 ** is held on the file and false if the file is unlocked.
24620 */
24621 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
24622   int rc = SQLITE_OK;
24623   int reserved = 0;
24624   unixFile *pFile = (unixFile*)id;
24625
24626   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24627   
24628   assert( pFile );
24629
24630   /* Check if a thread in this process holds such a lock */
24631   if( pFile->eFileLock>SHARED_LOCK ){
24632     /* Either this connection or some other connection in the same process
24633     ** holds a lock on the file.  No need to check further. */
24634     reserved = 1;
24635   }else{
24636     /* The lock is held if and only if the lockfile exists */
24637     const char *zLockFile = (const char*)pFile->lockingContext;
24638     reserved = access(zLockFile, 0)==0;
24639   }
24640   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
24641   *pResOut = reserved;
24642   return rc;
24643 }
24644
24645 /*
24646 ** Lock the file with the lock specified by parameter eFileLock - one
24647 ** of the following:
24648 **
24649 **     (1) SHARED_LOCK
24650 **     (2) RESERVED_LOCK
24651 **     (3) PENDING_LOCK
24652 **     (4) EXCLUSIVE_LOCK
24653 **
24654 ** Sometimes when requesting one lock state, additional lock states
24655 ** are inserted in between.  The locking might fail on one of the later
24656 ** transitions leaving the lock state different from what it started but
24657 ** still short of its goal.  The following chart shows the allowed
24658 ** transitions and the inserted intermediate states:
24659 **
24660 **    UNLOCKED -> SHARED
24661 **    SHARED -> RESERVED
24662 **    SHARED -> (PENDING) -> EXCLUSIVE
24663 **    RESERVED -> (PENDING) -> EXCLUSIVE
24664 **    PENDING -> EXCLUSIVE
24665 **
24666 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24667 ** routine to lower a locking level.
24668 **
24669 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
24670 ** But we track the other locking levels internally.
24671 */
24672 static int dotlockLock(sqlite3_file *id, int eFileLock) {
24673   unixFile *pFile = (unixFile*)id;
24674   int fd;
24675   char *zLockFile = (char *)pFile->lockingContext;
24676   int rc = SQLITE_OK;
24677
24678
24679   /* If we have any lock, then the lock file already exists.  All we have
24680   ** to do is adjust our internal record of the lock level.
24681   */
24682   if( pFile->eFileLock > NO_LOCK ){
24683     pFile->eFileLock = eFileLock;
24684 #if !OS_VXWORKS
24685     /* Always update the timestamp on the old file */
24686     utimes(zLockFile, NULL);
24687 #endif
24688     return SQLITE_OK;
24689   }
24690   
24691   /* grab an exclusive lock */
24692   fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
24693   if( fd<0 ){
24694     /* failed to open/create the file, someone else may have stolen the lock */
24695     int tErrno = errno;
24696     if( EEXIST == tErrno ){
24697       rc = SQLITE_BUSY;
24698     } else {
24699       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24700       if( IS_LOCK_ERROR(rc) ){
24701         pFile->lastErrno = tErrno;
24702       }
24703     }
24704     return rc;
24705   } 
24706   if( close(fd) ){
24707     pFile->lastErrno = errno;
24708     rc = SQLITE_IOERR_CLOSE;
24709   }
24710   
24711   /* got it, set the type and return ok */
24712   pFile->eFileLock = eFileLock;
24713   return rc;
24714 }
24715
24716 /*
24717 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24718 ** must be either NO_LOCK or SHARED_LOCK.
24719 **
24720 ** If the locking level of the file descriptor is already at or below
24721 ** the requested locking level, this routine is a no-op.
24722 **
24723 ** When the locking level reaches NO_LOCK, delete the lock file.
24724 */
24725 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
24726   unixFile *pFile = (unixFile*)id;
24727   char *zLockFile = (char *)pFile->lockingContext;
24728
24729   assert( pFile );
24730   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
24731            pFile->eFileLock, getpid()));
24732   assert( eFileLock<=SHARED_LOCK );
24733   
24734   /* no-op if possible */
24735   if( pFile->eFileLock==eFileLock ){
24736     return SQLITE_OK;
24737   }
24738
24739   /* To downgrade to shared, simply update our internal notion of the
24740   ** lock state.  No need to mess with the file on disk.
24741   */
24742   if( eFileLock==SHARED_LOCK ){
24743     pFile->eFileLock = SHARED_LOCK;
24744     return SQLITE_OK;
24745   }
24746   
24747   /* To fully unlock the database, delete the lock file */
24748   assert( eFileLock==NO_LOCK );
24749   if( unlink(zLockFile) ){
24750     int rc = 0;
24751     int tErrno = errno;
24752     if( ENOENT != tErrno ){
24753       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24754     }
24755     if( IS_LOCK_ERROR(rc) ){
24756       pFile->lastErrno = tErrno;
24757     }
24758     return rc; 
24759   }
24760   pFile->eFileLock = NO_LOCK;
24761   return SQLITE_OK;
24762 }
24763
24764 /*
24765 ** Close a file.  Make sure the lock has been released before closing.
24766 */
24767 static int dotlockClose(sqlite3_file *id) {
24768   int rc;
24769   if( id ){
24770     unixFile *pFile = (unixFile*)id;
24771     dotlockUnlock(id, NO_LOCK);
24772     sqlite3_free(pFile->lockingContext);
24773   }
24774   rc = closeUnixFile(id);
24775   return rc;
24776 }
24777 /****************** End of the dot-file lock implementation *******************
24778 ******************************************************************************/
24779
24780 /******************************************************************************
24781 ************************** Begin flock Locking ********************************
24782 **
24783 ** Use the flock() system call to do file locking.
24784 **
24785 ** flock() locking is like dot-file locking in that the various
24786 ** fine-grain locking levels supported by SQLite are collapsed into
24787 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
24788 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
24789 ** still works when you do this, but concurrency is reduced since
24790 ** only a single process can be reading the database at a time.
24791 **
24792 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
24793 ** compiling for VXWORKS.
24794 */
24795 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
24796
24797 /*
24798 ** This routine checks if there is a RESERVED lock held on the specified
24799 ** file by this or any other process. If such a lock is held, set *pResOut
24800 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24801 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24802 */
24803 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
24804   int rc = SQLITE_OK;
24805   int reserved = 0;
24806   unixFile *pFile = (unixFile*)id;
24807   
24808   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24809   
24810   assert( pFile );
24811   
24812   /* Check if a thread in this process holds such a lock */
24813   if( pFile->eFileLock>SHARED_LOCK ){
24814     reserved = 1;
24815   }
24816   
24817   /* Otherwise see if some other process holds it. */
24818   if( !reserved ){
24819     /* attempt to get the lock */
24820     int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
24821     if( !lrc ){
24822       /* got the lock, unlock it */
24823       lrc = flock(pFile->h, LOCK_UN);
24824       if ( lrc ) {
24825         int tErrno = errno;
24826         /* unlock failed with an error */
24827         lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 
24828         if( IS_LOCK_ERROR(lrc) ){
24829           pFile->lastErrno = tErrno;
24830           rc = lrc;
24831         }
24832       }
24833     } else {
24834       int tErrno = errno;
24835       reserved = 1;
24836       /* someone else might have it reserved */
24837       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 
24838       if( IS_LOCK_ERROR(lrc) ){
24839         pFile->lastErrno = tErrno;
24840         rc = lrc;
24841       }
24842     }
24843   }
24844   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
24845
24846 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24847   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
24848     rc = SQLITE_OK;
24849     reserved=1;
24850   }
24851 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
24852   *pResOut = reserved;
24853   return rc;
24854 }
24855
24856 /*
24857 ** Lock the file with the lock specified by parameter eFileLock - one
24858 ** of the following:
24859 **
24860 **     (1) SHARED_LOCK
24861 **     (2) RESERVED_LOCK
24862 **     (3) PENDING_LOCK
24863 **     (4) EXCLUSIVE_LOCK
24864 **
24865 ** Sometimes when requesting one lock state, additional lock states
24866 ** are inserted in between.  The locking might fail on one of the later
24867 ** transitions leaving the lock state different from what it started but
24868 ** still short of its goal.  The following chart shows the allowed
24869 ** transitions and the inserted intermediate states:
24870 **
24871 **    UNLOCKED -> SHARED
24872 **    SHARED -> RESERVED
24873 **    SHARED -> (PENDING) -> EXCLUSIVE
24874 **    RESERVED -> (PENDING) -> EXCLUSIVE
24875 **    PENDING -> EXCLUSIVE
24876 **
24877 ** flock() only really support EXCLUSIVE locks.  We track intermediate
24878 ** lock states in the sqlite3_file structure, but all locks SHARED or
24879 ** above are really EXCLUSIVE locks and exclude all other processes from
24880 ** access the file.
24881 **
24882 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24883 ** routine to lower a locking level.
24884 */
24885 static int flockLock(sqlite3_file *id, int eFileLock) {
24886   int rc = SQLITE_OK;
24887   unixFile *pFile = (unixFile*)id;
24888
24889   assert( pFile );
24890
24891   /* if we already have a lock, it is exclusive.  
24892   ** Just adjust level and punt on outta here. */
24893   if (pFile->eFileLock > NO_LOCK) {
24894     pFile->eFileLock = eFileLock;
24895     return SQLITE_OK;
24896   }
24897   
24898   /* grab an exclusive lock */
24899   
24900   if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
24901     int tErrno = errno;
24902     /* didn't get, must be busy */
24903     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24904     if( IS_LOCK_ERROR(rc) ){
24905       pFile->lastErrno = tErrno;
24906     }
24907   } else {
24908     /* got it, set the type and return ok */
24909     pFile->eFileLock = eFileLock;
24910   }
24911   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), 
24912            rc==SQLITE_OK ? "ok" : "failed"));
24913 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24914   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
24915     rc = SQLITE_BUSY;
24916   }
24917 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
24918   return rc;
24919 }
24920
24921
24922 /*
24923 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24924 ** must be either NO_LOCK or SHARED_LOCK.
24925 **
24926 ** If the locking level of the file descriptor is already at or below
24927 ** the requested locking level, this routine is a no-op.
24928 */
24929 static int flockUnlock(sqlite3_file *id, int eFileLock) {
24930   unixFile *pFile = (unixFile*)id;
24931   
24932   assert( pFile );
24933   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
24934            pFile->eFileLock, getpid()));
24935   assert( eFileLock<=SHARED_LOCK );
24936   
24937   /* no-op if possible */
24938   if( pFile->eFileLock==eFileLock ){
24939     return SQLITE_OK;
24940   }
24941   
24942   /* shared can just be set because we always have an exclusive */
24943   if (eFileLock==SHARED_LOCK) {
24944     pFile->eFileLock = eFileLock;
24945     return SQLITE_OK;
24946   }
24947   
24948   /* no, really, unlock. */
24949   int rc = flock(pFile->h, LOCK_UN);
24950   if (rc) {
24951     int r, tErrno = errno;
24952     r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24953     if( IS_LOCK_ERROR(r) ){
24954       pFile->lastErrno = tErrno;
24955     }
24956 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24957     if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
24958       r = SQLITE_BUSY;
24959     }
24960 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
24961     
24962     return r;
24963   } else {
24964     pFile->eFileLock = NO_LOCK;
24965     return SQLITE_OK;
24966   }
24967 }
24968
24969 /*
24970 ** Close a file.
24971 */
24972 static int flockClose(sqlite3_file *id) {
24973   if( id ){
24974     flockUnlock(id, NO_LOCK);
24975   }
24976   return closeUnixFile(id);
24977 }
24978
24979 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
24980
24981 /******************* End of the flock lock implementation *********************
24982 ******************************************************************************/
24983
24984 /******************************************************************************
24985 ************************ Begin Named Semaphore Locking ************************
24986 **
24987 ** Named semaphore locking is only supported on VxWorks.
24988 **
24989 ** Semaphore locking is like dot-lock and flock in that it really only
24990 ** supports EXCLUSIVE locking.  Only a single process can read or write
24991 ** the database file at a time.  This reduces potential concurrency, but
24992 ** makes the lock implementation much easier.
24993 */
24994 #if OS_VXWORKS
24995
24996 /*
24997 ** This routine checks if there is a RESERVED lock held on the specified
24998 ** file by this or any other process. If such a lock is held, set *pResOut
24999 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25000 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25001 */
25002 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
25003   int rc = SQLITE_OK;
25004   int reserved = 0;
25005   unixFile *pFile = (unixFile*)id;
25006
25007   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25008   
25009   assert( pFile );
25010
25011   /* Check if a thread in this process holds such a lock */
25012   if( pFile->eFileLock>SHARED_LOCK ){
25013     reserved = 1;
25014   }
25015   
25016   /* Otherwise see if some other process holds it. */
25017   if( !reserved ){
25018     sem_t *pSem = pFile->pInode->pSem;
25019     struct stat statBuf;
25020
25021     if( sem_trywait(pSem)==-1 ){
25022       int tErrno = errno;
25023       if( EAGAIN != tErrno ){
25024         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
25025         pFile->lastErrno = tErrno;
25026       } else {
25027         /* someone else has the lock when we are in NO_LOCK */
25028         reserved = (pFile->eFileLock < SHARED_LOCK);
25029       }
25030     }else{
25031       /* we could have it if we want it */
25032       sem_post(pSem);
25033     }
25034   }
25035   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
25036
25037   *pResOut = reserved;
25038   return rc;
25039 }
25040
25041 /*
25042 ** Lock the file with the lock specified by parameter eFileLock - one
25043 ** of the following:
25044 **
25045 **     (1) SHARED_LOCK
25046 **     (2) RESERVED_LOCK
25047 **     (3) PENDING_LOCK
25048 **     (4) EXCLUSIVE_LOCK
25049 **
25050 ** Sometimes when requesting one lock state, additional lock states
25051 ** are inserted in between.  The locking might fail on one of the later
25052 ** transitions leaving the lock state different from what it started but
25053 ** still short of its goal.  The following chart shows the allowed
25054 ** transitions and the inserted intermediate states:
25055 **
25056 **    UNLOCKED -> SHARED
25057 **    SHARED -> RESERVED
25058 **    SHARED -> (PENDING) -> EXCLUSIVE
25059 **    RESERVED -> (PENDING) -> EXCLUSIVE
25060 **    PENDING -> EXCLUSIVE
25061 **
25062 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
25063 ** lock states in the sqlite3_file structure, but all locks SHARED or
25064 ** above are really EXCLUSIVE locks and exclude all other processes from
25065 ** access the file.
25066 **
25067 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25068 ** routine to lower a locking level.
25069 */
25070 static int semLock(sqlite3_file *id, int eFileLock) {
25071   unixFile *pFile = (unixFile*)id;
25072   int fd;
25073   sem_t *pSem = pFile->pInode->pSem;
25074   int rc = SQLITE_OK;
25075
25076   /* if we already have a lock, it is exclusive.  
25077   ** Just adjust level and punt on outta here. */
25078   if (pFile->eFileLock > NO_LOCK) {
25079     pFile->eFileLock = eFileLock;
25080     rc = SQLITE_OK;
25081     goto sem_end_lock;
25082   }
25083   
25084   /* lock semaphore now but bail out when already locked. */
25085   if( sem_trywait(pSem)==-1 ){
25086     rc = SQLITE_BUSY;
25087     goto sem_end_lock;
25088   }
25089
25090   /* got it, set the type and return ok */
25091   pFile->eFileLock = eFileLock;
25092
25093  sem_end_lock:
25094   return rc;
25095 }
25096
25097 /*
25098 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25099 ** must be either NO_LOCK or SHARED_LOCK.
25100 **
25101 ** If the locking level of the file descriptor is already at or below
25102 ** the requested locking level, this routine is a no-op.
25103 */
25104 static int semUnlock(sqlite3_file *id, int eFileLock) {
25105   unixFile *pFile = (unixFile*)id;
25106   sem_t *pSem = pFile->pInode->pSem;
25107
25108   assert( pFile );
25109   assert( pSem );
25110   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
25111            pFile->eFileLock, getpid()));
25112   assert( eFileLock<=SHARED_LOCK );
25113   
25114   /* no-op if possible */
25115   if( pFile->eFileLock==eFileLock ){
25116     return SQLITE_OK;
25117   }
25118   
25119   /* shared can just be set because we always have an exclusive */
25120   if (eFileLock==SHARED_LOCK) {
25121     pFile->eFileLock = eFileLock;
25122     return SQLITE_OK;
25123   }
25124   
25125   /* no, really unlock. */
25126   if ( sem_post(pSem)==-1 ) {
25127     int rc, tErrno = errno;
25128     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
25129     if( IS_LOCK_ERROR(rc) ){
25130       pFile->lastErrno = tErrno;
25131     }
25132     return rc; 
25133   }
25134   pFile->eFileLock = NO_LOCK;
25135   return SQLITE_OK;
25136 }
25137
25138 /*
25139  ** Close a file.
25140  */
25141 static int semClose(sqlite3_file *id) {
25142   if( id ){
25143     unixFile *pFile = (unixFile*)id;
25144     semUnlock(id, NO_LOCK);
25145     assert( pFile );
25146     unixEnterMutex();
25147     releaseInodeInfo(pFile);
25148     unixLeaveMutex();
25149     closeUnixFile(id);
25150   }
25151   return SQLITE_OK;
25152 }
25153
25154 #endif /* OS_VXWORKS */
25155 /*
25156 ** Named semaphore locking is only available on VxWorks.
25157 **
25158 *************** End of the named semaphore lock implementation ****************
25159 ******************************************************************************/
25160
25161
25162 /******************************************************************************
25163 *************************** Begin AFP Locking *********************************
25164 **
25165 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
25166 ** on Apple Macintosh computers - both OS9 and OSX.
25167 **
25168 ** Third-party implementations of AFP are available.  But this code here
25169 ** only works on OSX.
25170 */
25171
25172 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25173 /*
25174 ** The afpLockingContext structure contains all afp lock specific state
25175 */
25176 typedef struct afpLockingContext afpLockingContext;
25177 struct afpLockingContext {
25178   int reserved;
25179   const char *dbPath;             /* Name of the open file */
25180 };
25181
25182 struct ByteRangeLockPB2
25183 {
25184   unsigned long long offset;        /* offset to first byte to lock */
25185   unsigned long long length;        /* nbr of bytes to lock */
25186   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
25187   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
25188   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
25189   int fd;                           /* file desc to assoc this lock with */
25190 };
25191
25192 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
25193
25194 /*
25195 ** This is a utility for setting or clearing a bit-range lock on an
25196 ** AFP filesystem.
25197 ** 
25198 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
25199 */
25200 static int afpSetLock(
25201   const char *path,              /* Name of the file to be locked or unlocked */
25202   unixFile *pFile,               /* Open file descriptor on path */
25203   unsigned long long offset,     /* First byte to be locked */
25204   unsigned long long length,     /* Number of bytes to lock */
25205   int setLockFlag                /* True to set lock.  False to clear lock */
25206 ){
25207   struct ByteRangeLockPB2 pb;
25208   int err;
25209   
25210   pb.unLockFlag = setLockFlag ? 0 : 1;
25211   pb.startEndFlag = 0;
25212   pb.offset = offset;
25213   pb.length = length; 
25214   pb.fd = pFile->h;
25215   
25216   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
25217     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
25218     offset, length));
25219   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
25220   if ( err==-1 ) {
25221     int rc;
25222     int tErrno = errno;
25223     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
25224              path, tErrno, strerror(tErrno)));
25225 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
25226     rc = SQLITE_BUSY;
25227 #else
25228     rc = sqliteErrorFromPosixError(tErrno,
25229                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
25230 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
25231     if( IS_LOCK_ERROR(rc) ){
25232       pFile->lastErrno = tErrno;
25233     }
25234     return rc;
25235   } else {
25236     return SQLITE_OK;
25237   }
25238 }
25239
25240 /*
25241 ** This routine checks if there is a RESERVED lock held on the specified
25242 ** file by this or any other process. If such a lock is held, set *pResOut
25243 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25244 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25245 */
25246 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
25247   int rc = SQLITE_OK;
25248   int reserved = 0;
25249   unixFile *pFile = (unixFile*)id;
25250   
25251   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25252   
25253   assert( pFile );
25254   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
25255   if( context->reserved ){
25256     *pResOut = 1;
25257     return SQLITE_OK;
25258   }
25259   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
25260   
25261   /* Check if a thread in this process holds such a lock */
25262   if( pFile->pInode->eFileLock>SHARED_LOCK ){
25263     reserved = 1;
25264   }
25265   
25266   /* Otherwise see if some other process holds it.
25267    */
25268   if( !reserved ){
25269     /* lock the RESERVED byte */
25270     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  
25271     if( SQLITE_OK==lrc ){
25272       /* if we succeeded in taking the reserved lock, unlock it to restore
25273       ** the original state */
25274       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
25275     } else {
25276       /* if we failed to get the lock then someone else must have it */
25277       reserved = 1;
25278     }
25279     if( IS_LOCK_ERROR(lrc) ){
25280       rc=lrc;
25281     }
25282   }
25283   
25284   unixLeaveMutex();
25285   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
25286   
25287   *pResOut = reserved;
25288   return rc;
25289 }
25290
25291 /*
25292 ** Lock the file with the lock specified by parameter eFileLock - one
25293 ** of the following:
25294 **
25295 **     (1) SHARED_LOCK
25296 **     (2) RESERVED_LOCK
25297 **     (3) PENDING_LOCK
25298 **     (4) EXCLUSIVE_LOCK
25299 **
25300 ** Sometimes when requesting one lock state, additional lock states
25301 ** are inserted in between.  The locking might fail on one of the later
25302 ** transitions leaving the lock state different from what it started but
25303 ** still short of its goal.  The following chart shows the allowed
25304 ** transitions and the inserted intermediate states:
25305 **
25306 **    UNLOCKED -> SHARED
25307 **    SHARED -> RESERVED
25308 **    SHARED -> (PENDING) -> EXCLUSIVE
25309 **    RESERVED -> (PENDING) -> EXCLUSIVE
25310 **    PENDING -> EXCLUSIVE
25311 **
25312 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25313 ** routine to lower a locking level.
25314 */
25315 static int afpLock(sqlite3_file *id, int eFileLock){
25316   int rc = SQLITE_OK;
25317   unixFile *pFile = (unixFile*)id;
25318   unixInodeInfo *pInode = pFile->pInode;
25319   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
25320   
25321   assert( pFile );
25322   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
25323            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
25324            azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
25325
25326   /* If there is already a lock of this type or more restrictive on the
25327   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
25328   ** unixEnterMutex() hasn't been called yet.
25329   */
25330   if( pFile->eFileLock>=eFileLock ){
25331     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
25332            azFileLock(eFileLock)));
25333     return SQLITE_OK;
25334   }
25335
25336   /* Make sure the locking sequence is correct
25337   **  (1) We never move from unlocked to anything higher than shared lock.
25338   **  (2) SQLite never explicitly requests a pendig lock.
25339   **  (3) A shared lock is always held when a reserve lock is requested.
25340   */
25341   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
25342   assert( eFileLock!=PENDING_LOCK );
25343   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
25344   
25345   /* This mutex is needed because pFile->pInode is shared across threads
25346   */
25347   unixEnterMutex();
25348   pInode = pFile->pInode;
25349
25350   /* If some thread using this PID has a lock via a different unixFile*
25351   ** handle that precludes the requested lock, return BUSY.
25352   */
25353   if( (pFile->eFileLock!=pInode->eFileLock && 
25354        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
25355      ){
25356     rc = SQLITE_BUSY;
25357     goto afp_end_lock;
25358   }
25359   
25360   /* If a SHARED lock is requested, and some thread using this PID already
25361   ** has a SHARED or RESERVED lock, then increment reference counts and
25362   ** return SQLITE_OK.
25363   */
25364   if( eFileLock==SHARED_LOCK && 
25365      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
25366     assert( eFileLock==SHARED_LOCK );
25367     assert( pFile->eFileLock==0 );
25368     assert( pInode->nShared>0 );
25369     pFile->eFileLock = SHARED_LOCK;
25370     pInode->nShared++;
25371     pInode->nLock++;
25372     goto afp_end_lock;
25373   }
25374     
25375   /* A PENDING lock is needed before acquiring a SHARED lock and before
25376   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
25377   ** be released.
25378   */
25379   if( eFileLock==SHARED_LOCK 
25380       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
25381   ){
25382     int failed;
25383     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
25384     if (failed) {
25385       rc = failed;
25386       goto afp_end_lock;
25387     }
25388   }
25389   
25390   /* If control gets to this point, then actually go ahead and make
25391   ** operating system calls for the specified lock.
25392   */
25393   if( eFileLock==SHARED_LOCK ){
25394     int lrc1, lrc2, lrc1Errno;
25395     long lk, mask;
25396     
25397     assert( pInode->nShared==0 );
25398     assert( pInode->eFileLock==0 );
25399         
25400     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
25401     /* Now get the read-lock SHARED_LOCK */
25402     /* note that the quality of the randomness doesn't matter that much */
25403     lk = random(); 
25404     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
25405     lrc1 = afpSetLock(context->dbPath, pFile, 
25406           SHARED_FIRST+pInode->sharedByte, 1, 1);
25407     if( IS_LOCK_ERROR(lrc1) ){
25408       lrc1Errno = pFile->lastErrno;
25409     }
25410     /* Drop the temporary PENDING lock */
25411     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
25412     
25413     if( IS_LOCK_ERROR(lrc1) ) {
25414       pFile->lastErrno = lrc1Errno;
25415       rc = lrc1;
25416       goto afp_end_lock;
25417     } else if( IS_LOCK_ERROR(lrc2) ){
25418       rc = lrc2;
25419       goto afp_end_lock;
25420     } else if( lrc1 != SQLITE_OK ) {
25421       rc = lrc1;
25422     } else {
25423       pFile->eFileLock = SHARED_LOCK;
25424       pInode->nLock++;
25425       pInode->nShared = 1;
25426     }
25427   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
25428     /* We are trying for an exclusive lock but another thread in this
25429      ** same process is still holding a shared lock. */
25430     rc = SQLITE_BUSY;
25431   }else{
25432     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
25433     ** assumed that there is a SHARED or greater lock on the file
25434     ** already.
25435     */
25436     int failed = 0;
25437     assert( 0!=pFile->eFileLock );
25438     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
25439         /* Acquire a RESERVED lock */
25440         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
25441       if( !failed ){
25442         context->reserved = 1;
25443       }
25444     }
25445     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
25446       /* Acquire an EXCLUSIVE lock */
25447         
25448       /* Remove the shared lock before trying the range.  we'll need to 
25449       ** reestablish the shared lock if we can't get the  afpUnlock
25450       */
25451       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
25452                          pInode->sharedByte, 1, 0)) ){
25453         int failed2 = SQLITE_OK;
25454         /* now attemmpt to get the exclusive lock range */
25455         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
25456                                SHARED_SIZE, 1);
25457         if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
25458                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
25459           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
25460           ** a critical I/O error
25461           */
25462           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : 
25463                SQLITE_IOERR_LOCK;
25464           goto afp_end_lock;
25465         } 
25466       }else{
25467         rc = failed; 
25468       }
25469     }
25470     if( failed ){
25471       rc = failed;
25472     }
25473   }
25474   
25475   if( rc==SQLITE_OK ){
25476     pFile->eFileLock = eFileLock;
25477     pInode->eFileLock = eFileLock;
25478   }else if( eFileLock==EXCLUSIVE_LOCK ){
25479     pFile->eFileLock = PENDING_LOCK;
25480     pInode->eFileLock = PENDING_LOCK;
25481   }
25482   
25483 afp_end_lock:
25484   unixLeaveMutex();
25485   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), 
25486          rc==SQLITE_OK ? "ok" : "failed"));
25487   return rc;
25488 }
25489
25490 /*
25491 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25492 ** must be either NO_LOCK or SHARED_LOCK.
25493 **
25494 ** If the locking level of the file descriptor is already at or below
25495 ** the requested locking level, this routine is a no-op.
25496 */
25497 static int afpUnlock(sqlite3_file *id, int eFileLock) {
25498   int rc = SQLITE_OK;
25499   unixFile *pFile = (unixFile*)id;
25500   unixInodeInfo *pInode;
25501   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
25502   int skipShared = 0;
25503 #ifdef SQLITE_TEST
25504   int h = pFile->h;
25505 #endif
25506
25507   assert( pFile );
25508   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
25509            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
25510            getpid()));
25511
25512   assert( eFileLock<=SHARED_LOCK );
25513   if( pFile->eFileLock<=eFileLock ){
25514     return SQLITE_OK;
25515   }
25516   unixEnterMutex();
25517   pInode = pFile->pInode;
25518   assert( pInode->nShared!=0 );
25519   if( pFile->eFileLock>SHARED_LOCK ){
25520     assert( pInode->eFileLock==pFile->eFileLock );
25521     SimulateIOErrorBenign(1);
25522     SimulateIOError( h=(-1) )
25523     SimulateIOErrorBenign(0);
25524     
25525 #ifndef NDEBUG
25526     /* When reducing a lock such that other processes can start
25527     ** reading the database file again, make sure that the
25528     ** transaction counter was updated if any part of the database
25529     ** file changed.  If the transaction counter is not updated,
25530     ** other connections to the same file might not realize that
25531     ** the file has changed and hence might not know to flush their
25532     ** cache.  The use of a stale cache can lead to database corruption.
25533     */
25534     assert( pFile->inNormalWrite==0
25535            || pFile->dbUpdate==0
25536            || pFile->transCntrChng==1 );
25537     pFile->inNormalWrite = 0;
25538 #endif
25539     
25540     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
25541       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
25542       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
25543         /* only re-establish the shared lock if necessary */
25544         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
25545         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
25546       } else {
25547         skipShared = 1;
25548       }
25549     }
25550     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
25551       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
25552     } 
25553     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
25554       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
25555       if( !rc ){ 
25556         context->reserved = 0; 
25557       }
25558     }
25559     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
25560       pInode->eFileLock = SHARED_LOCK;
25561     }
25562   }
25563   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
25564
25565     /* Decrement the shared lock counter.  Release the lock using an
25566     ** OS call only when all threads in this same process have released
25567     ** the lock.
25568     */
25569     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
25570     pInode->nShared--;
25571     if( pInode->nShared==0 ){
25572       SimulateIOErrorBenign(1);
25573       SimulateIOError( h=(-1) )
25574       SimulateIOErrorBenign(0);
25575       if( !skipShared ){
25576         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
25577       }
25578       if( !rc ){
25579         pInode->eFileLock = NO_LOCK;
25580         pFile->eFileLock = NO_LOCK;
25581       }
25582     }
25583     if( rc==SQLITE_OK ){
25584       pInode->nLock--;
25585       assert( pInode->nLock>=0 );
25586       if( pInode->nLock==0 ){
25587         rc = closePendingFds(pFile);
25588       }
25589     }
25590   }
25591   
25592   unixLeaveMutex();
25593   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
25594   return rc;
25595 }
25596
25597 /*
25598 ** Close a file & cleanup AFP specific locking context 
25599 */
25600 static int afpClose(sqlite3_file *id) {
25601   int rc = SQLITE_OK;
25602   if( id ){
25603     unixFile *pFile = (unixFile*)id;
25604     afpUnlock(id, NO_LOCK);
25605     unixEnterMutex();
25606     if( pFile->pInode && pFile->pInode->nLock ){
25607       /* If there are outstanding locks, do not actually close the file just
25608       ** yet because that would clear those locks.  Instead, add the file
25609       ** descriptor to pInode->aPending.  It will be automatically closed when
25610       ** the last lock is cleared.
25611       */
25612       setPendingFd(pFile);
25613     }
25614     releaseInodeInfo(pFile);
25615     sqlite3_free(pFile->lockingContext);
25616     rc = closeUnixFile(id);
25617     unixLeaveMutex();
25618   }
25619   return rc;
25620 }
25621
25622 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25623 /*
25624 ** The code above is the AFP lock implementation.  The code is specific
25625 ** to MacOSX and does not work on other unix platforms.  No alternative
25626 ** is available.  If you don't compile for a mac, then the "unix-afp"
25627 ** VFS is not available.
25628 **
25629 ********************* End of the AFP lock implementation **********************
25630 ******************************************************************************/
25631
25632 /******************************************************************************
25633 *************************** Begin NFS Locking ********************************/
25634
25635 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25636 /*
25637  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25638  ** must be either NO_LOCK or SHARED_LOCK.
25639  **
25640  ** If the locking level of the file descriptor is already at or below
25641  ** the requested locking level, this routine is a no-op.
25642  */
25643 static int nfsUnlock(sqlite3_file *id, int eFileLock){
25644   return _posixUnlock(id, eFileLock, 1);
25645 }
25646
25647 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25648 /*
25649 ** The code above is the NFS lock implementation.  The code is specific
25650 ** to MacOSX and does not work on other unix platforms.  No alternative
25651 ** is available.  
25652 **
25653 ********************* End of the NFS lock implementation **********************
25654 ******************************************************************************/
25655
25656 /******************************************************************************
25657 **************** Non-locking sqlite3_file methods *****************************
25658 **
25659 ** The next division contains implementations for all methods of the 
25660 ** sqlite3_file object other than the locking methods.  The locking
25661 ** methods were defined in divisions above (one locking method per
25662 ** division).  Those methods that are common to all locking modes
25663 ** are gather together into this division.
25664 */
25665
25666 /*
25667 ** Seek to the offset passed as the second argument, then read cnt 
25668 ** bytes into pBuf. Return the number of bytes actually read.
25669 **
25670 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
25671 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
25672 ** one system to another.  Since SQLite does not define USE_PREAD
25673 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
25674 ** See tickets #2741 and #2681.
25675 **
25676 ** To avoid stomping the errno value on a failed read the lastErrno value
25677 ** is set before returning.
25678 */
25679 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
25680   int got;
25681 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
25682   i64 newOffset;
25683 #endif
25684   TIMER_START;
25685 #if defined(USE_PREAD)
25686   got = pread(id->h, pBuf, cnt, offset);
25687   SimulateIOError( got = -1 );
25688 #elif defined(USE_PREAD64)
25689   got = pread64(id->h, pBuf, cnt, offset);
25690   SimulateIOError( got = -1 );
25691 #else
25692   newOffset = lseek(id->h, offset, SEEK_SET);
25693   SimulateIOError( newOffset-- );
25694   if( newOffset!=offset ){
25695     if( newOffset == -1 ){
25696       ((unixFile*)id)->lastErrno = errno;
25697     }else{
25698       ((unixFile*)id)->lastErrno = 0;                   
25699     }
25700     return -1;
25701   }
25702   got = read(id->h, pBuf, cnt);
25703 #endif
25704   TIMER_END;
25705   if( got<0 ){
25706     ((unixFile*)id)->lastErrno = errno;
25707   }
25708   OSTRACE(("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
25709   return got;
25710 }
25711
25712 /*
25713 ** Read data from a file into a buffer.  Return SQLITE_OK if all
25714 ** bytes were read successfully and SQLITE_IOERR if anything goes
25715 ** wrong.
25716 */
25717 static int unixRead(
25718   sqlite3_file *id, 
25719   void *pBuf, 
25720   int amt,
25721   sqlite3_int64 offset
25722 ){
25723   unixFile *pFile = (unixFile *)id;
25724   int got;
25725   assert( id );
25726
25727   /* If this is a database file (not a journal, master-journal or temp
25728   ** file), the bytes in the locking range should never be read or written. */
25729 #if 0
25730   assert( pFile->pUnused==0
25731        || offset>=PENDING_BYTE+512
25732        || offset+amt<=PENDING_BYTE 
25733   );
25734 #endif
25735
25736   got = seekAndRead(pFile, offset, pBuf, amt);
25737   if( got==amt ){
25738     return SQLITE_OK;
25739   }else if( got<0 ){
25740     /* lastErrno set by seekAndRead */
25741     return SQLITE_IOERR_READ;
25742   }else{
25743     pFile->lastErrno = 0; /* not a system error */
25744     /* Unread parts of the buffer must be zero-filled */
25745     memset(&((char*)pBuf)[got], 0, amt-got);
25746     return SQLITE_IOERR_SHORT_READ;
25747   }
25748 }
25749
25750 /*
25751 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
25752 ** Return the number of bytes actually read.  Update the offset.
25753 **
25754 ** To avoid stomping the errno value on a failed write the lastErrno value
25755 ** is set before returning.
25756 */
25757 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
25758   int got;
25759 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
25760   i64 newOffset;
25761 #endif
25762   TIMER_START;
25763 #if defined(USE_PREAD)
25764   got = pwrite(id->h, pBuf, cnt, offset);
25765 #elif defined(USE_PREAD64)
25766   got = pwrite64(id->h, pBuf, cnt, offset);
25767 #else
25768   newOffset = lseek(id->h, offset, SEEK_SET);
25769   if( newOffset!=offset ){
25770     if( newOffset == -1 ){
25771       ((unixFile*)id)->lastErrno = errno;
25772     }else{
25773       ((unixFile*)id)->lastErrno = 0;                   
25774     }
25775     return -1;
25776   }
25777   got = write(id->h, pBuf, cnt);
25778 #endif
25779   TIMER_END;
25780   if( got<0 ){
25781     ((unixFile*)id)->lastErrno = errno;
25782   }
25783
25784   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
25785   return got;
25786 }
25787
25788
25789 /*
25790 ** Write data from a buffer into a file.  Return SQLITE_OK on success
25791 ** or some other error code on failure.
25792 */
25793 static int unixWrite(
25794   sqlite3_file *id, 
25795   const void *pBuf, 
25796   int amt,
25797   sqlite3_int64 offset 
25798 ){
25799   unixFile *pFile = (unixFile*)id;
25800   int wrote = 0;
25801   assert( id );
25802   assert( amt>0 );
25803
25804   /* If this is a database file (not a journal, master-journal or temp
25805   ** file), the bytes in the locking range should never be read or written. */
25806 #if 0
25807   assert( pFile->pUnused==0
25808        || offset>=PENDING_BYTE+512
25809        || offset+amt<=PENDING_BYTE 
25810   );
25811 #endif
25812
25813 #ifndef NDEBUG
25814   /* If we are doing a normal write to a database file (as opposed to
25815   ** doing a hot-journal rollback or a write to some file other than a
25816   ** normal database file) then record the fact that the database
25817   ** has changed.  If the transaction counter is modified, record that
25818   ** fact too.
25819   */
25820   if( pFile->inNormalWrite ){
25821     pFile->dbUpdate = 1;  /* The database has been modified */
25822     if( offset<=24 && offset+amt>=27 ){
25823       int rc;
25824       char oldCntr[4];
25825       SimulateIOErrorBenign(1);
25826       rc = seekAndRead(pFile, 24, oldCntr, 4);
25827       SimulateIOErrorBenign(0);
25828       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
25829         pFile->transCntrChng = 1;  /* The transaction counter has changed */
25830       }
25831     }
25832   }
25833 #endif
25834
25835   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
25836     amt -= wrote;
25837     offset += wrote;
25838     pBuf = &((char*)pBuf)[wrote];
25839   }
25840   SimulateIOError(( wrote=(-1), amt=1 ));
25841   SimulateDiskfullError(( wrote=0, amt=1 ));
25842
25843   if( amt>0 ){
25844     if( wrote<0 ){
25845       /* lastErrno set by seekAndWrite */
25846       return SQLITE_IOERR_WRITE;
25847     }else{
25848       pFile->lastErrno = 0; /* not a system error */
25849       return SQLITE_FULL;
25850     }
25851   }
25852
25853   return SQLITE_OK;
25854 }
25855
25856 #ifdef SQLITE_TEST
25857 /*
25858 ** Count the number of fullsyncs and normal syncs.  This is used to test
25859 ** that syncs and fullsyncs are occurring at the right times.
25860 */
25861 SQLITE_API int sqlite3_sync_count = 0;
25862 SQLITE_API int sqlite3_fullsync_count = 0;
25863 #endif
25864
25865 /*
25866 ** We do not trust systems to provide a working fdatasync().  Some do.
25867 ** Others do no.  To be safe, we will stick with the (slower) fsync().
25868 ** If you know that your system does support fdatasync() correctly,
25869 ** then simply compile with -Dfdatasync=fdatasync
25870 */
25871 #if !defined(fdatasync) && !defined(__linux__)
25872 # define fdatasync fsync
25873 #endif
25874
25875 /*
25876 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
25877 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
25878 ** only available on Mac OS X.  But that could change.
25879 */
25880 #ifdef F_FULLFSYNC
25881 # define HAVE_FULLFSYNC 1
25882 #else
25883 # define HAVE_FULLFSYNC 0
25884 #endif
25885
25886
25887 /*
25888 ** The fsync() system call does not work as advertised on many
25889 ** unix systems.  The following procedure is an attempt to make
25890 ** it work better.
25891 **
25892 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
25893 ** for testing when we want to run through the test suite quickly.
25894 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
25895 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
25896 ** or power failure will likely corrupt the database file.
25897 **
25898 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
25899 ** The idea behind dataOnly is that it should only write the file content
25900 ** to disk, not the inode.  We only set dataOnly if the file size is 
25901 ** unchanged since the file size is part of the inode.  However, 
25902 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
25903 ** file size has changed.  The only real difference between fdatasync()
25904 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
25905 ** inode if the mtime or owner or other inode attributes have changed.
25906 ** We only care about the file size, not the other file attributes, so
25907 ** as far as SQLite is concerned, an fdatasync() is always adequate.
25908 ** So, we always use fdatasync() if it is available, regardless of
25909 ** the value of the dataOnly flag.
25910 */
25911 static int full_fsync(int fd, int fullSync, int dataOnly){
25912   int rc;
25913
25914   /* The following "ifdef/elif/else/" block has the same structure as
25915   ** the one below. It is replicated here solely to avoid cluttering 
25916   ** up the real code with the UNUSED_PARAMETER() macros.
25917   */
25918 #ifdef SQLITE_NO_SYNC
25919   UNUSED_PARAMETER(fd);
25920   UNUSED_PARAMETER(fullSync);
25921   UNUSED_PARAMETER(dataOnly);
25922 #elif HAVE_FULLFSYNC
25923   UNUSED_PARAMETER(dataOnly);
25924 #else
25925   UNUSED_PARAMETER(fullSync);
25926   UNUSED_PARAMETER(dataOnly);
25927 #endif
25928
25929   /* Record the number of times that we do a normal fsync() and 
25930   ** FULLSYNC.  This is used during testing to verify that this procedure
25931   ** gets called with the correct arguments.
25932   */
25933 #ifdef SQLITE_TEST
25934   if( fullSync ) sqlite3_fullsync_count++;
25935   sqlite3_sync_count++;
25936 #endif
25937
25938   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
25939   ** no-op
25940   */
25941 #ifdef SQLITE_NO_SYNC
25942   rc = SQLITE_OK;
25943 #elif HAVE_FULLFSYNC
25944   if( fullSync ){
25945     rc = fcntl(fd, F_FULLFSYNC, 0);
25946   }else{
25947     rc = 1;
25948   }
25949   /* If the FULLFSYNC failed, fall back to attempting an fsync().
25950   ** It shouldn't be possible for fullfsync to fail on the local 
25951   ** file system (on OSX), so failure indicates that FULLFSYNC
25952   ** isn't supported for this file system. So, attempt an fsync 
25953   ** and (for now) ignore the overhead of a superfluous fcntl call.  
25954   ** It'd be better to detect fullfsync support once and avoid 
25955   ** the fcntl call every time sync is called.
25956   */
25957   if( rc ) rc = fsync(fd);
25958
25959 #elif defined(__APPLE__)
25960   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
25961   ** so currently we default to the macro that redefines fdatasync to fsync
25962   */
25963   rc = fsync(fd);
25964 #else 
25965   rc = fdatasync(fd);
25966 #if OS_VXWORKS
25967   if( rc==-1 && errno==ENOTSUP ){
25968     rc = fsync(fd);
25969   }
25970 #endif /* OS_VXWORKS */
25971 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
25972
25973   if( OS_VXWORKS && rc!= -1 ){
25974     rc = 0;
25975   }
25976   return rc;
25977 }
25978
25979 /*
25980 ** Make sure all writes to a particular file are committed to disk.
25981 **
25982 ** If dataOnly==0 then both the file itself and its metadata (file
25983 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
25984 ** file data is synced.
25985 **
25986 ** Under Unix, also make sure that the directory entry for the file
25987 ** has been created by fsync-ing the directory that contains the file.
25988 ** If we do not do this and we encounter a power failure, the directory
25989 ** entry for the journal might not exist after we reboot.  The next
25990 ** SQLite to access the file will not know that the journal exists (because
25991 ** the directory entry for the journal was never created) and the transaction
25992 ** will not roll back - possibly leading to database corruption.
25993 */
25994 static int unixSync(sqlite3_file *id, int flags){
25995   int rc;
25996   unixFile *pFile = (unixFile*)id;
25997
25998   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
25999   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
26000
26001   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
26002   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
26003       || (flags&0x0F)==SQLITE_SYNC_FULL
26004   );
26005
26006   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
26007   ** line is to test that doing so does not cause any problems.
26008   */
26009   SimulateDiskfullError( return SQLITE_FULL );
26010
26011   assert( pFile );
26012   OSTRACE(("SYNC    %-3d\n", pFile->h));
26013   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
26014   SimulateIOError( rc=1 );
26015   if( rc ){
26016     pFile->lastErrno = errno;
26017     return SQLITE_IOERR_FSYNC;
26018   }
26019   if( pFile->dirfd>=0 ){
26020     int err;
26021     OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
26022             HAVE_FULLFSYNC, isFullsync));
26023 #ifndef SQLITE_DISABLE_DIRSYNC
26024     /* The directory sync is only attempted if full_fsync is
26025     ** turned off or unavailable.  If a full_fsync occurred above,
26026     ** then the directory sync is superfluous.
26027     */
26028     if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
26029        /*
26030        ** We have received multiple reports of fsync() returning
26031        ** errors when applied to directories on certain file systems.
26032        ** A failed directory sync is not a big deal.  So it seems
26033        ** better to ignore the error.  Ticket #1657
26034        */
26035        /* pFile->lastErrno = errno; */
26036        /* return SQLITE_IOERR; */
26037     }
26038 #endif
26039     err = close(pFile->dirfd); /* Only need to sync once, so close the */
26040     if( err==0 ){              /* directory when we are done */
26041       pFile->dirfd = -1;
26042     }else{
26043       pFile->lastErrno = errno;
26044       rc = SQLITE_IOERR_DIR_CLOSE;
26045     }
26046   }
26047   return rc;
26048 }
26049
26050 /*
26051 ** Truncate an open file to a specified size
26052 */
26053 static int unixTruncate(sqlite3_file *id, i64 nByte){
26054   unixFile *pFile = (unixFile *)id;
26055   int rc;
26056   assert( pFile );
26057   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
26058
26059   /* If the user has configured a chunk-size for this file, truncate the
26060   ** file so that it consists of an integer number of chunks (i.e. the
26061   ** actual file size after the operation may be larger than the requested
26062   ** size).
26063   */
26064   if( pFile->szChunk ){
26065     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
26066   }
26067
26068   rc = ftruncate(pFile->h, (off_t)nByte);
26069   if( rc ){
26070     pFile->lastErrno = errno;
26071     return SQLITE_IOERR_TRUNCATE;
26072   }else{
26073 #ifndef NDEBUG
26074     /* If we are doing a normal write to a database file (as opposed to
26075     ** doing a hot-journal rollback or a write to some file other than a
26076     ** normal database file) and we truncate the file to zero length,
26077     ** that effectively updates the change counter.  This might happen
26078     ** when restoring a database using the backup API from a zero-length
26079     ** source.
26080     */
26081     if( pFile->inNormalWrite && nByte==0 ){
26082       pFile->transCntrChng = 1;
26083     }
26084 #endif
26085
26086     return SQLITE_OK;
26087   }
26088 }
26089
26090 /*
26091 ** Determine the current size of a file in bytes
26092 */
26093 static int unixFileSize(sqlite3_file *id, i64 *pSize){
26094   int rc;
26095   struct stat buf;
26096   assert( id );
26097   rc = fstat(((unixFile*)id)->h, &buf);
26098   SimulateIOError( rc=1 );
26099   if( rc!=0 ){
26100     ((unixFile*)id)->lastErrno = errno;
26101     return SQLITE_IOERR_FSTAT;
26102   }
26103   *pSize = buf.st_size;
26104
26105   /* When opening a zero-size database, the findInodeInfo() procedure
26106   ** writes a single byte into that file in order to work around a bug
26107   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
26108   ** layers, we need to report this file size as zero even though it is
26109   ** really 1.   Ticket #3260.
26110   */
26111   if( *pSize==1 ) *pSize = 0;
26112
26113
26114   return SQLITE_OK;
26115 }
26116
26117 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26118 /*
26119 ** Handler for proxy-locking file-control verbs.  Defined below in the
26120 ** proxying locking division.
26121 */
26122 static int proxyFileControl(sqlite3_file*,int,void*);
26123 #endif
26124
26125 /* 
26126 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT 
26127 ** file-control operation.
26128 **
26129 ** If the user has configured a chunk-size for this file, it could be
26130 ** that the file needs to be extended at this point. Otherwise, the
26131 ** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
26132 */
26133 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
26134   if( pFile->szChunk ){
26135     i64 nSize;                    /* Required file size */
26136     struct stat buf;              /* Used to hold return values of fstat() */
26137    
26138     if( fstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
26139
26140     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
26141     if( nSize>(i64)buf.st_size ){
26142 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
26143       if( posix_fallocate(pFile->h, buf.st_size, nSize-buf.st_size) ){
26144         return SQLITE_IOERR_WRITE;
26145       }
26146 #else
26147       /* If the OS does not have posix_fallocate(), fake it. First use
26148       ** ftruncate() to set the file size, then write a single byte to
26149       ** the last byte in each block within the extended region. This
26150       ** is the same technique used by glibc to implement posix_fallocate()
26151       ** on systems that do not have a real fallocate() system call.
26152       */
26153       int nBlk = buf.st_blksize;  /* File-system block size */
26154       i64 iWrite;                 /* Next offset to write to */
26155       int nWrite;                 /* Return value from seekAndWrite() */
26156
26157       if( ftruncate(pFile->h, nSize) ){
26158         pFile->lastErrno = errno;
26159         return SQLITE_IOERR_TRUNCATE;
26160       }
26161       iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
26162       do {
26163         nWrite = seekAndWrite(pFile, iWrite, "", 1);
26164         iWrite += nBlk;
26165       } while( nWrite==1 && iWrite<nSize );
26166       if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
26167 #endif
26168     }
26169   }
26170
26171   return SQLITE_OK;
26172 }
26173
26174 /*
26175 ** Information and control of an open file handle.
26176 */
26177 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
26178   switch( op ){
26179     case SQLITE_FCNTL_LOCKSTATE: {
26180       *(int*)pArg = ((unixFile*)id)->eFileLock;
26181       return SQLITE_OK;
26182     }
26183     case SQLITE_LAST_ERRNO: {
26184       *(int*)pArg = ((unixFile*)id)->lastErrno;
26185       return SQLITE_OK;
26186     }
26187     case SQLITE_FCNTL_CHUNK_SIZE: {
26188       ((unixFile*)id)->szChunk = *(int *)pArg;
26189       return SQLITE_OK;
26190     }
26191     case SQLITE_FCNTL_SIZE_HINT: {
26192       return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
26193     }
26194 #ifndef NDEBUG
26195     /* The pager calls this method to signal that it has done
26196     ** a rollback and that the database is therefore unchanged and
26197     ** it hence it is OK for the transaction change counter to be
26198     ** unchanged.
26199     */
26200     case SQLITE_FCNTL_DB_UNCHANGED: {
26201       ((unixFile*)id)->dbUpdate = 0;
26202       return SQLITE_OK;
26203     }
26204 #endif
26205 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26206     case SQLITE_SET_LOCKPROXYFILE:
26207     case SQLITE_GET_LOCKPROXYFILE: {
26208       return proxyFileControl(id,op,pArg);
26209     }
26210 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
26211     case SQLITE_FCNTL_SYNC_OMITTED: {
26212       return SQLITE_OK;  /* A no-op */
26213     }
26214   }
26215   return SQLITE_NOTFOUND;
26216 }
26217
26218 /*
26219 ** Return the sector size in bytes of the underlying block device for
26220 ** the specified file. This is almost always 512 bytes, but may be
26221 ** larger for some devices.
26222 **
26223 ** SQLite code assumes this function cannot fail. It also assumes that
26224 ** if two files are created in the same file-system directory (i.e.
26225 ** a database and its journal file) that the sector size will be the
26226 ** same for both.
26227 */
26228 static int unixSectorSize(sqlite3_file *NotUsed){
26229   UNUSED_PARAMETER(NotUsed);
26230   return SQLITE_DEFAULT_SECTOR_SIZE;
26231 }
26232
26233 /*
26234 ** Return the device characteristics for the file. This is always 0 for unix.
26235 */
26236 static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
26237   UNUSED_PARAMETER(NotUsed);
26238   return 0;
26239 }
26240
26241 #ifndef SQLITE_OMIT_WAL
26242
26243
26244 /*
26245 ** Object used to represent an shared memory buffer.  
26246 **
26247 ** When multiple threads all reference the same wal-index, each thread
26248 ** has its own unixShm object, but they all point to a single instance
26249 ** of this unixShmNode object.  In other words, each wal-index is opened
26250 ** only once per process.
26251 **
26252 ** Each unixShmNode object is connected to a single unixInodeInfo object.
26253 ** We could coalesce this object into unixInodeInfo, but that would mean
26254 ** every open file that does not use shared memory (in other words, most
26255 ** open files) would have to carry around this extra information.  So
26256 ** the unixInodeInfo object contains a pointer to this unixShmNode object
26257 ** and the unixShmNode object is created only when needed.
26258 **
26259 ** unixMutexHeld() must be true when creating or destroying
26260 ** this object or while reading or writing the following fields:
26261 **
26262 **      nRef
26263 **
26264 ** The following fields are read-only after the object is created:
26265 ** 
26266 **      fid
26267 **      zFilename
26268 **
26269 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
26270 ** unixMutexHeld() is true when reading or writing any other field
26271 ** in this structure.
26272 */
26273 struct unixShmNode {
26274   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
26275   sqlite3_mutex *mutex;      /* Mutex to access this object */
26276   char *zFilename;           /* Name of the mmapped file */
26277   int h;                     /* Open file descriptor */
26278   int szRegion;              /* Size of shared-memory regions */
26279   int nRegion;               /* Size of array apRegion */
26280   char **apRegion;           /* Array of mapped shared-memory regions */
26281   int nRef;                  /* Number of unixShm objects pointing to this */
26282   unixShm *pFirst;           /* All unixShm objects pointing to this */
26283 #ifdef SQLITE_DEBUG
26284   u8 exclMask;               /* Mask of exclusive locks held */
26285   u8 sharedMask;             /* Mask of shared locks held */
26286   u8 nextShmId;              /* Next available unixShm.id value */
26287 #endif
26288 };
26289
26290 /*
26291 ** Structure used internally by this VFS to record the state of an
26292 ** open shared memory connection.
26293 **
26294 ** The following fields are initialized when this object is created and
26295 ** are read-only thereafter:
26296 **
26297 **    unixShm.pFile
26298 **    unixShm.id
26299 **
26300 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
26301 ** while accessing any read/write fields.
26302 */
26303 struct unixShm {
26304   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
26305   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
26306   u8 hasMutex;               /* True if holding the unixShmNode mutex */
26307   u16 sharedMask;            /* Mask of shared locks held */
26308   u16 exclMask;              /* Mask of exclusive locks held */
26309 #ifdef SQLITE_DEBUG
26310   u8 id;                     /* Id of this connection within its unixShmNode */
26311 #endif
26312 };
26313
26314 /*
26315 ** Constants used for locking
26316 */
26317 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
26318 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
26319
26320 /*
26321 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
26322 **
26323 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
26324 ** otherwise.
26325 */
26326 static int unixShmSystemLock(
26327   unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
26328   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
26329   int ofst,              /* First byte of the locking range */
26330   int n                  /* Number of bytes to lock */
26331 ){
26332   struct flock f;       /* The posix advisory locking structure */
26333   int rc = SQLITE_OK;   /* Result code form fcntl() */
26334
26335   /* Access to the unixShmNode object is serialized by the caller */
26336   assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
26337
26338   /* Shared locks never span more than one byte */
26339   assert( n==1 || lockType!=F_RDLCK );
26340
26341   /* Locks are within range */
26342   assert( n>=1 && n<SQLITE_SHM_NLOCK );
26343
26344   /* Initialize the locking parameters */
26345   memset(&f, 0, sizeof(f));
26346   f.l_type = lockType;
26347   f.l_whence = SEEK_SET;
26348   f.l_start = ofst;
26349   f.l_len = n;
26350
26351   rc = fcntl(pShmNode->h, F_SETLK, &f);
26352   rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
26353
26354   /* Update the global lock state and do debug tracing */
26355 #ifdef SQLITE_DEBUG
26356   { u16 mask;
26357   OSTRACE(("SHM-LOCK "));
26358   mask = (1<<(ofst+n)) - (1<<ofst);
26359   if( rc==SQLITE_OK ){
26360     if( lockType==F_UNLCK ){
26361       OSTRACE(("unlock %d ok", ofst));
26362       pShmNode->exclMask &= ~mask;
26363       pShmNode->sharedMask &= ~mask;
26364     }else if( lockType==F_RDLCK ){
26365       OSTRACE(("read-lock %d ok", ofst));
26366       pShmNode->exclMask &= ~mask;
26367       pShmNode->sharedMask |= mask;
26368     }else{
26369       assert( lockType==F_WRLCK );
26370       OSTRACE(("write-lock %d ok", ofst));
26371       pShmNode->exclMask |= mask;
26372       pShmNode->sharedMask &= ~mask;
26373     }
26374   }else{
26375     if( lockType==F_UNLCK ){
26376       OSTRACE(("unlock %d failed", ofst));
26377     }else if( lockType==F_RDLCK ){
26378       OSTRACE(("read-lock failed"));
26379     }else{
26380       assert( lockType==F_WRLCK );
26381       OSTRACE(("write-lock %d failed", ofst));
26382     }
26383   }
26384   OSTRACE((" - afterwards %03x,%03x\n",
26385            pShmNode->sharedMask, pShmNode->exclMask));
26386   }
26387 #endif
26388
26389   return rc;        
26390 }
26391
26392
26393 /*
26394 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
26395 **
26396 ** This is not a VFS shared-memory method; it is a utility function called
26397 ** by VFS shared-memory methods.
26398 */
26399 static void unixShmPurge(unixFile *pFd){
26400   unixShmNode *p = pFd->pInode->pShmNode;
26401   assert( unixMutexHeld() );
26402   if( p && p->nRef==0 ){
26403     int i;
26404     assert( p->pInode==pFd->pInode );
26405     if( p->mutex ) sqlite3_mutex_free(p->mutex);
26406     for(i=0; i<p->nRegion; i++){
26407       munmap(p->apRegion[i], p->szRegion);
26408     }
26409     sqlite3_free(p->apRegion);
26410     if( p->h>=0 ) close(p->h);
26411     p->pInode->pShmNode = 0;
26412     sqlite3_free(p);
26413   }
26414 }
26415
26416 /*
26417 ** Open a shared-memory area associated with open database file pDbFd.  
26418 ** This particular implementation uses mmapped files.
26419 **
26420 ** The file used to implement shared-memory is in the same directory
26421 ** as the open database file and has the same name as the open database
26422 ** file with the "-shm" suffix added.  For example, if the database file
26423 ** is "/home/user1/config.db" then the file that is created and mmapped
26424 ** for shared memory will be called "/home/user1/config.db-shm".  
26425 **
26426 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
26427 ** some other tmpfs mount. But if a file in a different directory
26428 ** from the database file is used, then differing access permissions
26429 ** or a chroot() might cause two different processes on the same
26430 ** database to end up using different files for shared memory - 
26431 ** meaning that their memory would not really be shared - resulting
26432 ** in database corruption.  Nevertheless, this tmpfs file usage
26433 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
26434 ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
26435 ** option results in an incompatible build of SQLite;  builds of SQLite
26436 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
26437 ** same database file at the same time, database corruption will likely
26438 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
26439 ** "unsupported" and may go away in a future SQLite release.
26440 **
26441 ** When opening a new shared-memory file, if no other instances of that
26442 ** file are currently open, in this process or in other processes, then
26443 ** the file must be truncated to zero length or have its header cleared.
26444 */
26445 static int unixOpenSharedMemory(unixFile *pDbFd){
26446   struct unixShm *p = 0;          /* The connection to be opened */
26447   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
26448   int rc;                         /* Result code */
26449   unixInodeInfo *pInode;          /* The inode of fd */
26450   char *zShmFilename;             /* Name of the file used for SHM */
26451   int nShmFilename;               /* Size of the SHM filename in bytes */
26452
26453   /* Allocate space for the new unixShm object. */
26454   p = sqlite3_malloc( sizeof(*p) );
26455   if( p==0 ) return SQLITE_NOMEM;
26456   memset(p, 0, sizeof(*p));
26457   assert( pDbFd->pShm==0 );
26458
26459   /* Check to see if a unixShmNode object already exists. Reuse an existing
26460   ** one if present. Create a new one if necessary.
26461   */
26462   unixEnterMutex();
26463   pInode = pDbFd->pInode;
26464   pShmNode = pInode->pShmNode;
26465   if( pShmNode==0 ){
26466     struct stat sStat;                 /* fstat() info for database file */
26467
26468     /* Call fstat() to figure out the permissions on the database file. If
26469     ** a new *-shm file is created, an attempt will be made to create it
26470     ** with the same permissions. The actual permissions the file is created
26471     ** with are subject to the current umask setting.
26472     */
26473     if( fstat(pDbFd->h, &sStat) ){
26474       rc = SQLITE_IOERR_FSTAT;
26475       goto shm_open_err;
26476     }
26477
26478 #ifdef SQLITE_SHM_DIRECTORY
26479     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
26480 #else
26481     nShmFilename = 5 + (int)strlen(pDbFd->zPath);
26482 #endif
26483     pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
26484     if( pShmNode==0 ){
26485       rc = SQLITE_NOMEM;
26486       goto shm_open_err;
26487     }
26488     memset(pShmNode, 0, sizeof(*pShmNode));
26489     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
26490 #ifdef SQLITE_SHM_DIRECTORY
26491     sqlite3_snprintf(nShmFilename, zShmFilename, 
26492                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
26493                      (u32)sStat.st_ino, (u32)sStat.st_dev);
26494 #else
26495     sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
26496 #endif
26497     pShmNode->h = -1;
26498     pDbFd->pInode->pShmNode = pShmNode;
26499     pShmNode->pInode = pDbFd->pInode;
26500     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
26501     if( pShmNode->mutex==0 ){
26502       rc = SQLITE_NOMEM;
26503       goto shm_open_err;
26504     }
26505
26506     pShmNode->h = open(zShmFilename, O_RDWR|O_CREAT, (sStat.st_mode & 0777));
26507     if( pShmNode->h<0 ){
26508       rc = SQLITE_CANTOPEN_BKPT;
26509       goto shm_open_err;
26510     }
26511
26512     /* Check to see if another process is holding the dead-man switch.
26513     ** If not, truncate the file to zero length. 
26514     */
26515     rc = SQLITE_OK;
26516     if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
26517       if( ftruncate(pShmNode->h, 0) ){
26518         rc = SQLITE_IOERR_SHMOPEN;
26519       }
26520     }
26521     if( rc==SQLITE_OK ){
26522       rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
26523     }
26524     if( rc ) goto shm_open_err;
26525   }
26526
26527   /* Make the new connection a child of the unixShmNode */
26528   p->pShmNode = pShmNode;
26529 #ifdef SQLITE_DEBUG
26530   p->id = pShmNode->nextShmId++;
26531 #endif
26532   pShmNode->nRef++;
26533   pDbFd->pShm = p;
26534   unixLeaveMutex();
26535
26536   /* The reference count on pShmNode has already been incremented under
26537   ** the cover of the unixEnterMutex() mutex and the pointer from the
26538   ** new (struct unixShm) object to the pShmNode has been set. All that is
26539   ** left to do is to link the new object into the linked list starting
26540   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
26541   ** mutex.
26542   */
26543   sqlite3_mutex_enter(pShmNode->mutex);
26544   p->pNext = pShmNode->pFirst;
26545   pShmNode->pFirst = p;
26546   sqlite3_mutex_leave(pShmNode->mutex);
26547   return SQLITE_OK;
26548
26549   /* Jump here on any error */
26550 shm_open_err:
26551   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
26552   sqlite3_free(p);
26553   unixLeaveMutex();
26554   return rc;
26555 }
26556
26557 /*
26558 ** This function is called to obtain a pointer to region iRegion of the 
26559 ** shared-memory associated with the database file fd. Shared-memory regions 
26560 ** are numbered starting from zero. Each shared-memory region is szRegion 
26561 ** bytes in size.
26562 **
26563 ** If an error occurs, an error code is returned and *pp is set to NULL.
26564 **
26565 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
26566 ** region has not been allocated (by any client, including one running in a
26567 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
26568 ** bExtend is non-zero and the requested shared-memory region has not yet 
26569 ** been allocated, it is allocated by this function.
26570 **
26571 ** If the shared-memory region has already been allocated or is allocated by
26572 ** this call as described above, then it is mapped into this processes 
26573 ** address space (if it is not already), *pp is set to point to the mapped 
26574 ** memory and SQLITE_OK returned.
26575 */
26576 static int unixShmMap(
26577   sqlite3_file *fd,               /* Handle open on database file */
26578   int iRegion,                    /* Region to retrieve */
26579   int szRegion,                   /* Size of regions */
26580   int bExtend,                    /* True to extend file if necessary */
26581   void volatile **pp              /* OUT: Mapped memory */
26582 ){
26583   unixFile *pDbFd = (unixFile*)fd;
26584   unixShm *p;
26585   unixShmNode *pShmNode;
26586   int rc = SQLITE_OK;
26587
26588   /* If the shared-memory file has not yet been opened, open it now. */
26589   if( pDbFd->pShm==0 ){
26590     rc = unixOpenSharedMemory(pDbFd);
26591     if( rc!=SQLITE_OK ) return rc;
26592   }
26593
26594   p = pDbFd->pShm;
26595   pShmNode = p->pShmNode;
26596   sqlite3_mutex_enter(pShmNode->mutex);
26597   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
26598
26599   if( pShmNode->nRegion<=iRegion ){
26600     char **apNew;                      /* New apRegion[] array */
26601     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
26602     struct stat sStat;                 /* Used by fstat() */
26603
26604     pShmNode->szRegion = szRegion;
26605
26606     /* The requested region is not mapped into this processes address space.
26607     ** Check to see if it has been allocated (i.e. if the wal-index file is
26608     ** large enough to contain the requested region).
26609     */
26610     if( fstat(pShmNode->h, &sStat) ){
26611       rc = SQLITE_IOERR_SHMSIZE;
26612       goto shmpage_out;
26613     }
26614
26615     if( sStat.st_size<nByte ){
26616       /* The requested memory region does not exist. If bExtend is set to
26617       ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
26618       **
26619       ** Alternatively, if bExtend is true, use ftruncate() to allocate
26620       ** the requested memory region.
26621       */
26622       if( !bExtend ) goto shmpage_out;
26623       if( ftruncate(pShmNode->h, nByte) ){
26624         rc = SQLITE_IOERR_SHMSIZE;
26625         goto shmpage_out;
26626       }
26627     }
26628
26629     /* Map the requested memory region into this processes address space. */
26630     apNew = (char **)sqlite3_realloc(
26631         pShmNode->apRegion, (iRegion+1)*sizeof(char *)
26632     );
26633     if( !apNew ){
26634       rc = SQLITE_IOERR_NOMEM;
26635       goto shmpage_out;
26636     }
26637     pShmNode->apRegion = apNew;
26638     while(pShmNode->nRegion<=iRegion){
26639       void *pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE, 
26640           MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
26641       );
26642       if( pMem==MAP_FAILED ){
26643         rc = SQLITE_IOERR;
26644         goto shmpage_out;
26645       }
26646       pShmNode->apRegion[pShmNode->nRegion] = pMem;
26647       pShmNode->nRegion++;
26648     }
26649   }
26650
26651 shmpage_out:
26652   if( pShmNode->nRegion>iRegion ){
26653     *pp = pShmNode->apRegion[iRegion];
26654   }else{
26655     *pp = 0;
26656   }
26657   sqlite3_mutex_leave(pShmNode->mutex);
26658   return rc;
26659 }
26660
26661 /*
26662 ** Change the lock state for a shared-memory segment.
26663 **
26664 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
26665 ** different here than in posix.  In xShmLock(), one can go from unlocked
26666 ** to shared and back or from unlocked to exclusive and back.  But one may
26667 ** not go from shared to exclusive or from exclusive to shared.
26668 */
26669 static int unixShmLock(
26670   sqlite3_file *fd,          /* Database file holding the shared memory */
26671   int ofst,                  /* First lock to acquire or release */
26672   int n,                     /* Number of locks to acquire or release */
26673   int flags                  /* What to do with the lock */
26674 ){
26675   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
26676   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
26677   unixShm *pX;                          /* For looping over all siblings */
26678   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
26679   int rc = SQLITE_OK;                   /* Result code */
26680   u16 mask;                             /* Mask of locks to take or release */
26681
26682   assert( pShmNode==pDbFd->pInode->pShmNode );
26683   assert( pShmNode->pInode==pDbFd->pInode );
26684   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
26685   assert( n>=1 );
26686   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
26687        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
26688        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
26689        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
26690   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
26691
26692   mask = (1<<(ofst+n)) - (1<<ofst);
26693   assert( n>1 || mask==(1<<ofst) );
26694   sqlite3_mutex_enter(pShmNode->mutex);
26695   if( flags & SQLITE_SHM_UNLOCK ){
26696     u16 allMask = 0; /* Mask of locks held by siblings */
26697
26698     /* See if any siblings hold this same lock */
26699     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
26700       if( pX==p ) continue;
26701       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
26702       allMask |= pX->sharedMask;
26703     }
26704
26705     /* Unlock the system-level locks */
26706     if( (mask & allMask)==0 ){
26707       rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
26708     }else{
26709       rc = SQLITE_OK;
26710     }
26711
26712     /* Undo the local locks */
26713     if( rc==SQLITE_OK ){
26714       p->exclMask &= ~mask;
26715       p->sharedMask &= ~mask;
26716     } 
26717   }else if( flags & SQLITE_SHM_SHARED ){
26718     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
26719
26720     /* Find out which shared locks are already held by sibling connections.
26721     ** If any sibling already holds an exclusive lock, go ahead and return
26722     ** SQLITE_BUSY.
26723     */
26724     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
26725       if( (pX->exclMask & mask)!=0 ){
26726         rc = SQLITE_BUSY;
26727         break;
26728       }
26729       allShared |= pX->sharedMask;
26730     }
26731
26732     /* Get shared locks at the system level, if necessary */
26733     if( rc==SQLITE_OK ){
26734       if( (allShared & mask)==0 ){
26735         rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
26736       }else{
26737         rc = SQLITE_OK;
26738       }
26739     }
26740
26741     /* Get the local shared locks */
26742     if( rc==SQLITE_OK ){
26743       p->sharedMask |= mask;
26744     }
26745   }else{
26746     /* Make sure no sibling connections hold locks that will block this
26747     ** lock.  If any do, return SQLITE_BUSY right away.
26748     */
26749     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
26750       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
26751         rc = SQLITE_BUSY;
26752         break;
26753       }
26754     }
26755   
26756     /* Get the exclusive locks at the system level.  Then if successful
26757     ** also mark the local connection as being locked.
26758     */
26759     if( rc==SQLITE_OK ){
26760       rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
26761       if( rc==SQLITE_OK ){
26762         assert( (p->sharedMask & mask)==0 );
26763         p->exclMask |= mask;
26764       }
26765     }
26766   }
26767   sqlite3_mutex_leave(pShmNode->mutex);
26768   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
26769            p->id, getpid(), p->sharedMask, p->exclMask));
26770   return rc;
26771 }
26772
26773 /*
26774 ** Implement a memory barrier or memory fence on shared memory.  
26775 **
26776 ** All loads and stores begun before the barrier must complete before
26777 ** any load or store begun after the barrier.
26778 */
26779 static void unixShmBarrier(
26780   sqlite3_file *fd                /* Database file holding the shared memory */
26781 ){
26782   UNUSED_PARAMETER(fd);
26783   unixEnterMutex();
26784   unixLeaveMutex();
26785 }
26786
26787 /*
26788 ** Close a connection to shared-memory.  Delete the underlying 
26789 ** storage if deleteFlag is true.
26790 **
26791 ** If there is no shared memory associated with the connection then this
26792 ** routine is a harmless no-op.
26793 */
26794 static int unixShmUnmap(
26795   sqlite3_file *fd,               /* The underlying database file */
26796   int deleteFlag                  /* Delete shared-memory if true */
26797 ){
26798   unixShm *p;                     /* The connection to be closed */
26799   unixShmNode *pShmNode;          /* The underlying shared-memory file */
26800   unixShm **pp;                   /* For looping over sibling connections */
26801   unixFile *pDbFd;                /* The underlying database file */
26802
26803   pDbFd = (unixFile*)fd;
26804   p = pDbFd->pShm;
26805   if( p==0 ) return SQLITE_OK;
26806   pShmNode = p->pShmNode;
26807
26808   assert( pShmNode==pDbFd->pInode->pShmNode );
26809   assert( pShmNode->pInode==pDbFd->pInode );
26810
26811   /* Remove connection p from the set of connections associated
26812   ** with pShmNode */
26813   sqlite3_mutex_enter(pShmNode->mutex);
26814   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
26815   *pp = p->pNext;
26816
26817   /* Free the connection p */
26818   sqlite3_free(p);
26819   pDbFd->pShm = 0;
26820   sqlite3_mutex_leave(pShmNode->mutex);
26821
26822   /* If pShmNode->nRef has reached 0, then close the underlying
26823   ** shared-memory file, too */
26824   unixEnterMutex();
26825   assert( pShmNode->nRef>0 );
26826   pShmNode->nRef--;
26827   if( pShmNode->nRef==0 ){
26828     if( deleteFlag ) unlink(pShmNode->zFilename);
26829     unixShmPurge(pDbFd);
26830   }
26831   unixLeaveMutex();
26832
26833   return SQLITE_OK;
26834 }
26835
26836
26837 #else
26838 # define unixShmMap     0
26839 # define unixShmLock    0
26840 # define unixShmBarrier 0
26841 # define unixShmUnmap   0
26842 #endif /* #ifndef SQLITE_OMIT_WAL */
26843
26844 /*
26845 ** Here ends the implementation of all sqlite3_file methods.
26846 **
26847 ********************** End sqlite3_file Methods *******************************
26848 ******************************************************************************/
26849
26850 /*
26851 ** This division contains definitions of sqlite3_io_methods objects that
26852 ** implement various file locking strategies.  It also contains definitions
26853 ** of "finder" functions.  A finder-function is used to locate the appropriate
26854 ** sqlite3_io_methods object for a particular database file.  The pAppData
26855 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
26856 ** the correct finder-function for that VFS.
26857 **
26858 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
26859 ** object.  The only interesting finder-function is autolockIoFinder, which
26860 ** looks at the filesystem type and tries to guess the best locking
26861 ** strategy from that.
26862 **
26863 ** For finder-funtion F, two objects are created:
26864 **
26865 **    (1) The real finder-function named "FImpt()".
26866 **
26867 **    (2) A constant pointer to this function named just "F".
26868 **
26869 **
26870 ** A pointer to the F pointer is used as the pAppData value for VFS
26871 ** objects.  We have to do this instead of letting pAppData point
26872 ** directly at the finder-function since C90 rules prevent a void*
26873 ** from be cast into a function pointer.
26874 **
26875 **
26876 ** Each instance of this macro generates two objects:
26877 **
26878 **   *  A constant sqlite3_io_methods object call METHOD that has locking
26879 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
26880 **
26881 **   *  An I/O method finder function called FINDER that returns a pointer
26882 **      to the METHOD object in the previous bullet.
26883 */
26884 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
26885 static const sqlite3_io_methods METHOD = {                                   \
26886    VERSION,                    /* iVersion */                                \
26887    CLOSE,                      /* xClose */                                  \
26888    unixRead,                   /* xRead */                                   \
26889    unixWrite,                  /* xWrite */                                  \
26890    unixTruncate,               /* xTruncate */                               \
26891    unixSync,                   /* xSync */                                   \
26892    unixFileSize,               /* xFileSize */                               \
26893    LOCK,                       /* xLock */                                   \
26894    UNLOCK,                     /* xUnlock */                                 \
26895    CKLOCK,                     /* xCheckReservedLock */                      \
26896    unixFileControl,            /* xFileControl */                            \
26897    unixSectorSize,             /* xSectorSize */                             \
26898    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
26899    unixShmMap,                 /* xShmMap */                                 \
26900    unixShmLock,                /* xShmLock */                                \
26901    unixShmBarrier,             /* xShmBarrier */                             \
26902    unixShmUnmap                /* xShmUnmap */                               \
26903 };                                                                           \
26904 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
26905   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
26906   return &METHOD;                                                            \
26907 }                                                                            \
26908 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
26909     = FINDER##Impl;
26910
26911 /*
26912 ** Here are all of the sqlite3_io_methods objects for each of the
26913 ** locking strategies.  Functions that return pointers to these methods
26914 ** are also created.
26915 */
26916 IOMETHODS(
26917   posixIoFinder,            /* Finder function name */
26918   posixIoMethods,           /* sqlite3_io_methods object name */
26919   2,                        /* shared memory is enabled */
26920   unixClose,                /* xClose method */
26921   unixLock,                 /* xLock method */
26922   unixUnlock,               /* xUnlock method */
26923   unixCheckReservedLock     /* xCheckReservedLock method */
26924 )
26925 IOMETHODS(
26926   nolockIoFinder,           /* Finder function name */
26927   nolockIoMethods,          /* sqlite3_io_methods object name */
26928   1,                        /* shared memory is disabled */
26929   nolockClose,              /* xClose method */
26930   nolockLock,               /* xLock method */
26931   nolockUnlock,             /* xUnlock method */
26932   nolockCheckReservedLock   /* xCheckReservedLock method */
26933 )
26934 IOMETHODS(
26935   dotlockIoFinder,          /* Finder function name */
26936   dotlockIoMethods,         /* sqlite3_io_methods object name */
26937   1,                        /* shared memory is disabled */
26938   dotlockClose,             /* xClose method */
26939   dotlockLock,              /* xLock method */
26940   dotlockUnlock,            /* xUnlock method */
26941   dotlockCheckReservedLock  /* xCheckReservedLock method */
26942 )
26943
26944 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
26945 IOMETHODS(
26946   flockIoFinder,            /* Finder function name */
26947   flockIoMethods,           /* sqlite3_io_methods object name */
26948   1,                        /* shared memory is disabled */
26949   flockClose,               /* xClose method */
26950   flockLock,                /* xLock method */
26951   flockUnlock,              /* xUnlock method */
26952   flockCheckReservedLock    /* xCheckReservedLock method */
26953 )
26954 #endif
26955
26956 #if OS_VXWORKS
26957 IOMETHODS(
26958   semIoFinder,              /* Finder function name */
26959   semIoMethods,             /* sqlite3_io_methods object name */
26960   1,                        /* shared memory is disabled */
26961   semClose,                 /* xClose method */
26962   semLock,                  /* xLock method */
26963   semUnlock,                /* xUnlock method */
26964   semCheckReservedLock      /* xCheckReservedLock method */
26965 )
26966 #endif
26967
26968 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26969 IOMETHODS(
26970   afpIoFinder,              /* Finder function name */
26971   afpIoMethods,             /* sqlite3_io_methods object name */
26972   1,                        /* shared memory is disabled */
26973   afpClose,                 /* xClose method */
26974   afpLock,                  /* xLock method */
26975   afpUnlock,                /* xUnlock method */
26976   afpCheckReservedLock      /* xCheckReservedLock method */
26977 )
26978 #endif
26979
26980 /*
26981 ** The proxy locking method is a "super-method" in the sense that it
26982 ** opens secondary file descriptors for the conch and lock files and
26983 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
26984 ** secondary files.  For this reason, the division that implements
26985 ** proxy locking is located much further down in the file.  But we need
26986 ** to go ahead and define the sqlite3_io_methods and finder function
26987 ** for proxy locking here.  So we forward declare the I/O methods.
26988 */
26989 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26990 static int proxyClose(sqlite3_file*);
26991 static int proxyLock(sqlite3_file*, int);
26992 static int proxyUnlock(sqlite3_file*, int);
26993 static int proxyCheckReservedLock(sqlite3_file*, int*);
26994 IOMETHODS(
26995   proxyIoFinder,            /* Finder function name */
26996   proxyIoMethods,           /* sqlite3_io_methods object name */
26997   1,                        /* shared memory is disabled */
26998   proxyClose,               /* xClose method */
26999   proxyLock,                /* xLock method */
27000   proxyUnlock,              /* xUnlock method */
27001   proxyCheckReservedLock    /* xCheckReservedLock method */
27002 )
27003 #endif
27004
27005 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
27006 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27007 IOMETHODS(
27008   nfsIoFinder,               /* Finder function name */
27009   nfsIoMethods,              /* sqlite3_io_methods object name */
27010   1,                         /* shared memory is disabled */
27011   unixClose,                 /* xClose method */
27012   unixLock,                  /* xLock method */
27013   nfsUnlock,                 /* xUnlock method */
27014   unixCheckReservedLock      /* xCheckReservedLock method */
27015 )
27016 #endif
27017
27018 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27019 /* 
27020 ** This "finder" function attempts to determine the best locking strategy 
27021 ** for the database file "filePath".  It then returns the sqlite3_io_methods
27022 ** object that implements that strategy.
27023 **
27024 ** This is for MacOSX only.
27025 */
27026 static const sqlite3_io_methods *autolockIoFinderImpl(
27027   const char *filePath,    /* name of the database file */
27028   unixFile *pNew           /* open file object for the database file */
27029 ){
27030   static const struct Mapping {
27031     const char *zFilesystem;              /* Filesystem type name */
27032     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
27033   } aMap[] = {
27034     { "hfs",    &posixIoMethods },
27035     { "ufs",    &posixIoMethods },
27036     { "afpfs",  &afpIoMethods },
27037     { "smbfs",  &afpIoMethods },
27038     { "webdav", &nolockIoMethods },
27039     { 0, 0 }
27040   };
27041   int i;
27042   struct statfs fsInfo;
27043   struct flock lockInfo;
27044
27045   if( !filePath ){
27046     /* If filePath==NULL that means we are dealing with a transient file
27047     ** that does not need to be locked. */
27048     return &nolockIoMethods;
27049   }
27050   if( statfs(filePath, &fsInfo) != -1 ){
27051     if( fsInfo.f_flags & MNT_RDONLY ){
27052       return &nolockIoMethods;
27053     }
27054     for(i=0; aMap[i].zFilesystem; i++){
27055       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
27056         return aMap[i].pMethods;
27057       }
27058     }
27059   }
27060
27061   /* Default case. Handles, amongst others, "nfs".
27062   ** Test byte-range lock using fcntl(). If the call succeeds, 
27063   ** assume that the file-system supports POSIX style locks. 
27064   */
27065   lockInfo.l_len = 1;
27066   lockInfo.l_start = 0;
27067   lockInfo.l_whence = SEEK_SET;
27068   lockInfo.l_type = F_RDLCK;
27069   if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
27070     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
27071       return &nfsIoMethods;
27072     } else {
27073       return &posixIoMethods;
27074     }
27075   }else{
27076     return &dotlockIoMethods;
27077   }
27078 }
27079 static const sqlite3_io_methods 
27080   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
27081
27082 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27083
27084 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
27085 /* 
27086 ** This "finder" function attempts to determine the best locking strategy 
27087 ** for the database file "filePath".  It then returns the sqlite3_io_methods
27088 ** object that implements that strategy.
27089 **
27090 ** This is for VXWorks only.
27091 */
27092 static const sqlite3_io_methods *autolockIoFinderImpl(
27093   const char *filePath,    /* name of the database file */
27094   unixFile *pNew           /* the open file object */
27095 ){
27096   struct flock lockInfo;
27097
27098   if( !filePath ){
27099     /* If filePath==NULL that means we are dealing with a transient file
27100     ** that does not need to be locked. */
27101     return &nolockIoMethods;
27102   }
27103
27104   /* Test if fcntl() is supported and use POSIX style locks.
27105   ** Otherwise fall back to the named semaphore method.
27106   */
27107   lockInfo.l_len = 1;
27108   lockInfo.l_start = 0;
27109   lockInfo.l_whence = SEEK_SET;
27110   lockInfo.l_type = F_RDLCK;
27111   if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
27112     return &posixIoMethods;
27113   }else{
27114     return &semIoMethods;
27115   }
27116 }
27117 static const sqlite3_io_methods 
27118   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
27119
27120 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
27121
27122 /*
27123 ** An abstract type for a pointer to a IO method finder function:
27124 */
27125 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
27126
27127
27128 /****************************************************************************
27129 **************************** sqlite3_vfs methods ****************************
27130 **
27131 ** This division contains the implementation of methods on the
27132 ** sqlite3_vfs object.
27133 */
27134
27135 /*
27136 ** Initialize the contents of the unixFile structure pointed to by pId.
27137 */
27138 static int fillInUnixFile(
27139   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
27140   int h,                  /* Open file descriptor of file being opened */
27141   int dirfd,              /* Directory file descriptor */
27142   sqlite3_file *pId,      /* Write to the unixFile structure here */
27143   const char *zFilename,  /* Name of the file being opened */
27144   int noLock,             /* Omit locking if true */
27145   int isDelete            /* Delete on close if true */
27146 ){
27147   const sqlite3_io_methods *pLockingStyle;
27148   unixFile *pNew = (unixFile *)pId;
27149   int rc = SQLITE_OK;
27150
27151   assert( pNew->pInode==NULL );
27152
27153   /* Parameter isDelete is only used on vxworks. Express this explicitly 
27154   ** here to prevent compiler warnings about unused parameters.
27155   */
27156   UNUSED_PARAMETER(isDelete);
27157
27158   /* Usually the path zFilename should not be a relative pathname. The
27159   ** exception is when opening the proxy "conch" file in builds that
27160   ** include the special Apple locking styles.
27161   */
27162 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27163   assert( zFilename==0 || zFilename[0]=='/' 
27164     || pVfs->pAppData==(void*)&autolockIoFinder );
27165 #else
27166   assert( zFilename==0 || zFilename[0]=='/' );
27167 #endif
27168
27169   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
27170   pNew->h = h;
27171   pNew->dirfd = dirfd;
27172   pNew->fileFlags = 0;
27173   pNew->zPath = zFilename;
27174
27175 #if OS_VXWORKS
27176   pNew->pId = vxworksFindFileId(zFilename);
27177   if( pNew->pId==0 ){
27178     noLock = 1;
27179     rc = SQLITE_NOMEM;
27180   }
27181 #endif
27182
27183   if( noLock ){
27184     pLockingStyle = &nolockIoMethods;
27185   }else{
27186     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
27187 #if SQLITE_ENABLE_LOCKING_STYLE
27188     /* Cache zFilename in the locking context (AFP and dotlock override) for
27189     ** proxyLock activation is possible (remote proxy is based on db name)
27190     ** zFilename remains valid until file is closed, to support */
27191     pNew->lockingContext = (void*)zFilename;
27192 #endif
27193   }
27194
27195   if( pLockingStyle == &posixIoMethods
27196 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27197     || pLockingStyle == &nfsIoMethods
27198 #endif
27199   ){
27200     unixEnterMutex();
27201     rc = findInodeInfo(pNew, &pNew->pInode);
27202     if( rc!=SQLITE_OK ){
27203       /* If an error occured in findInodeInfo(), close the file descriptor
27204       ** immediately, before releasing the mutex. findInodeInfo() may fail
27205       ** in two scenarios:
27206       **
27207       **   (a) A call to fstat() failed.
27208       **   (b) A malloc failed.
27209       **
27210       ** Scenario (b) may only occur if the process is holding no other
27211       ** file descriptors open on the same file. If there were other file
27212       ** descriptors on this file, then no malloc would be required by
27213       ** findInodeInfo(). If this is the case, it is quite safe to close
27214       ** handle h - as it is guaranteed that no posix locks will be released
27215       ** by doing so.
27216       **
27217       ** If scenario (a) caused the error then things are not so safe. The
27218       ** implicit assumption here is that if fstat() fails, things are in
27219       ** such bad shape that dropping a lock or two doesn't matter much.
27220       */
27221       close(h);
27222       h = -1;
27223     }
27224     unixLeaveMutex();
27225   }
27226
27227 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27228   else if( pLockingStyle == &afpIoMethods ){
27229     /* AFP locking uses the file path so it needs to be included in
27230     ** the afpLockingContext.
27231     */
27232     afpLockingContext *pCtx;
27233     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
27234     if( pCtx==0 ){
27235       rc = SQLITE_NOMEM;
27236     }else{
27237       /* NB: zFilename exists and remains valid until the file is closed
27238       ** according to requirement F11141.  So we do not need to make a
27239       ** copy of the filename. */
27240       pCtx->dbPath = zFilename;
27241       pCtx->reserved = 0;
27242       srandomdev();
27243       unixEnterMutex();
27244       rc = findInodeInfo(pNew, &pNew->pInode);
27245       if( rc!=SQLITE_OK ){
27246         sqlite3_free(pNew->lockingContext);
27247         close(h);
27248         h = -1;
27249       }
27250       unixLeaveMutex();        
27251     }
27252   }
27253 #endif
27254
27255   else if( pLockingStyle == &dotlockIoMethods ){
27256     /* Dotfile locking uses the file path so it needs to be included in
27257     ** the dotlockLockingContext 
27258     */
27259     char *zLockFile;
27260     int nFilename;
27261     nFilename = (int)strlen(zFilename) + 6;
27262     zLockFile = (char *)sqlite3_malloc(nFilename);
27263     if( zLockFile==0 ){
27264       rc = SQLITE_NOMEM;
27265     }else{
27266       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
27267     }
27268     pNew->lockingContext = zLockFile;
27269   }
27270
27271 #if OS_VXWORKS
27272   else if( pLockingStyle == &semIoMethods ){
27273     /* Named semaphore locking uses the file path so it needs to be
27274     ** included in the semLockingContext
27275     */
27276     unixEnterMutex();
27277     rc = findInodeInfo(pNew, &pNew->pInode);
27278     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
27279       char *zSemName = pNew->pInode->aSemName;
27280       int n;
27281       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
27282                        pNew->pId->zCanonicalName);
27283       for( n=1; zSemName[n]; n++ )
27284         if( zSemName[n]=='/' ) zSemName[n] = '_';
27285       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
27286       if( pNew->pInode->pSem == SEM_FAILED ){
27287         rc = SQLITE_NOMEM;
27288         pNew->pInode->aSemName[0] = '\0';
27289       }
27290     }
27291     unixLeaveMutex();
27292   }
27293 #endif
27294   
27295   pNew->lastErrno = 0;
27296 #if OS_VXWORKS
27297   if( rc!=SQLITE_OK ){
27298     if( h>=0 ) close(h);
27299     h = -1;
27300     unlink(zFilename);
27301     isDelete = 0;
27302   }
27303   pNew->isDelete = isDelete;
27304 #endif
27305   if( rc!=SQLITE_OK ){
27306     if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
27307     if( h>=0 ) close(h);
27308   }else{
27309     pNew->pMethod = pLockingStyle;
27310     OpenCounter(+1);
27311   }
27312   return rc;
27313 }
27314
27315 /*
27316 ** Open a file descriptor to the directory containing file zFilename.
27317 ** If successful, *pFd is set to the opened file descriptor and
27318 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
27319 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
27320 ** value.
27321 **
27322 ** If SQLITE_OK is returned, the caller is responsible for closing
27323 ** the file descriptor *pFd using close().
27324 */
27325 static int openDirectory(const char *zFilename, int *pFd){
27326   int ii;
27327   int fd = -1;
27328   char zDirname[MAX_PATHNAME+1];
27329
27330   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
27331   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
27332   if( ii>0 ){
27333     zDirname[ii] = '\0';
27334     fd = open(zDirname, O_RDONLY|O_BINARY, 0);
27335     if( fd>=0 ){
27336 #ifdef FD_CLOEXEC
27337       fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
27338 #endif
27339       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
27340     }
27341   }
27342   *pFd = fd;
27343   return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN_BKPT);
27344 }
27345
27346 /*
27347 ** Return the name of a directory in which to put temporary files.
27348 ** If no suitable temporary file directory can be found, return NULL.
27349 */
27350 static const char *unixTempFileDir(void){
27351   static const char *azDirs[] = {
27352      0,
27353      0,
27354      "/var/tmp",
27355      "/usr/tmp",
27356      "/tmp",
27357      0        /* List terminator */
27358   };
27359   unsigned int i;
27360   struct stat buf;
27361   const char *zDir = 0;
27362
27363   azDirs[0] = sqlite3_temp_directory;
27364   if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
27365   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
27366     if( zDir==0 ) continue;
27367     if( stat(zDir, &buf) ) continue;
27368     if( !S_ISDIR(buf.st_mode) ) continue;
27369     if( access(zDir, 07) ) continue;
27370     break;
27371   }
27372   return zDir;
27373 }
27374
27375 /*
27376 ** Create a temporary file name in zBuf.  zBuf must be allocated
27377 ** by the calling process and must be big enough to hold at least
27378 ** pVfs->mxPathname bytes.
27379 */
27380 static int unixGetTempname(int nBuf, char *zBuf){
27381   static const unsigned char zChars[] =
27382     "abcdefghijklmnopqrstuvwxyz"
27383     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
27384     "0123456789";
27385   unsigned int i, j;
27386   const char *zDir;
27387
27388   /* It's odd to simulate an io-error here, but really this is just
27389   ** using the io-error infrastructure to test that SQLite handles this
27390   ** function failing. 
27391   */
27392   SimulateIOError( return SQLITE_IOERR );
27393
27394   zDir = unixTempFileDir();
27395   if( zDir==0 ) zDir = ".";
27396
27397   /* Check that the output buffer is large enough for the temporary file 
27398   ** name. If it is not, return SQLITE_ERROR.
27399   */
27400   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
27401     return SQLITE_ERROR;
27402   }
27403
27404   do{
27405     sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
27406     j = (int)strlen(zBuf);
27407     sqlite3_randomness(15, &zBuf[j]);
27408     for(i=0; i<15; i++, j++){
27409       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
27410     }
27411     zBuf[j] = 0;
27412   }while( access(zBuf,0)==0 );
27413   return SQLITE_OK;
27414 }
27415
27416 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27417 /*
27418 ** Routine to transform a unixFile into a proxy-locking unixFile.
27419 ** Implementation in the proxy-lock division, but used by unixOpen()
27420 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
27421 */
27422 static int proxyTransformUnixFile(unixFile*, const char*);
27423 #endif
27424
27425 /*
27426 ** Search for an unused file descriptor that was opened on the database 
27427 ** file (not a journal or master-journal file) identified by pathname
27428 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
27429 ** argument to this function.
27430 **
27431 ** Such a file descriptor may exist if a database connection was closed
27432 ** but the associated file descriptor could not be closed because some
27433 ** other file descriptor open on the same file is holding a file-lock.
27434 ** Refer to comments in the unixClose() function and the lengthy comment
27435 ** describing "Posix Advisory Locking" at the start of this file for 
27436 ** further details. Also, ticket #4018.
27437 **
27438 ** If a suitable file descriptor is found, then it is returned. If no
27439 ** such file descriptor is located, -1 is returned.
27440 */
27441 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
27442   UnixUnusedFd *pUnused = 0;
27443
27444   /* Do not search for an unused file descriptor on vxworks. Not because
27445   ** vxworks would not benefit from the change (it might, we're not sure),
27446   ** but because no way to test it is currently available. It is better 
27447   ** not to risk breaking vxworks support for the sake of such an obscure 
27448   ** feature.  */
27449 #if !OS_VXWORKS
27450   struct stat sStat;                   /* Results of stat() call */
27451
27452   /* A stat() call may fail for various reasons. If this happens, it is
27453   ** almost certain that an open() call on the same path will also fail.
27454   ** For this reason, if an error occurs in the stat() call here, it is
27455   ** ignored and -1 is returned. The caller will try to open a new file
27456   ** descriptor on the same path, fail, and return an error to SQLite.
27457   **
27458   ** Even if a subsequent open() call does succeed, the consequences of
27459   ** not searching for a resusable file descriptor are not dire.  */
27460   if( 0==stat(zPath, &sStat) ){
27461     unixInodeInfo *pInode;
27462
27463     unixEnterMutex();
27464     pInode = inodeList;
27465     while( pInode && (pInode->fileId.dev!=sStat.st_dev
27466                      || pInode->fileId.ino!=sStat.st_ino) ){
27467        pInode = pInode->pNext;
27468     }
27469     if( pInode ){
27470       UnixUnusedFd **pp;
27471       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
27472       pUnused = *pp;
27473       if( pUnused ){
27474         *pp = pUnused->pNext;
27475       }
27476     }
27477     unixLeaveMutex();
27478   }
27479 #endif    /* if !OS_VXWORKS */
27480   return pUnused;
27481 }
27482
27483 /*
27484 ** This function is called by unixOpen() to determine the unix permissions
27485 ** to create new files with. If no error occurs, then SQLITE_OK is returned
27486 ** and a value suitable for passing as the third argument to open(2) is
27487 ** written to *pMode. If an IO error occurs, an SQLite error code is 
27488 ** returned and the value of *pMode is not modified.
27489 **
27490 ** If the file being opened is a temporary file, it is always created with
27491 ** the octal permissions 0600 (read/writable by owner only). If the file
27492 ** is a database or master journal file, it is created with the permissions 
27493 ** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
27494 **
27495 ** Finally, if the file being opened is a WAL or regular journal file, then 
27496 ** this function queries the file-system for the permissions on the 
27497 ** corresponding database file and sets *pMode to this value. Whenever 
27498 ** possible, WAL and journal files are created using the same permissions 
27499 ** as the associated database file.
27500 */
27501 static int findCreateFileMode(
27502   const char *zPath,              /* Path of file (possibly) being created */
27503   int flags,                      /* Flags passed as 4th argument to xOpen() */
27504   mode_t *pMode                   /* OUT: Permissions to open file with */
27505 ){
27506   int rc = SQLITE_OK;             /* Return Code */
27507   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
27508     char zDb[MAX_PATHNAME+1];     /* Database file path */
27509     int nDb;                      /* Number of valid bytes in zDb */
27510     struct stat sStat;            /* Output of stat() on database file */
27511
27512     /* zPath is a path to a WAL or journal file. The following block derives
27513     ** the path to the associated database file from zPath. This block handles
27514     ** the following naming conventions:
27515     **
27516     **   "<path to db>-journal"
27517     **   "<path to db>-wal"
27518     **   "<path to db>-journal-NNNN"
27519     **   "<path to db>-wal-NNNN"
27520     **
27521     ** where NNNN is a 4 digit decimal number. The NNNN naming schemes are 
27522     ** used by the test_multiplex.c module.
27523     */
27524     nDb = sqlite3Strlen30(zPath) - 1; 
27525     while( nDb>0 && zPath[nDb]!='l' ) nDb--;
27526     nDb -= ((flags & SQLITE_OPEN_WAL) ? 3 : 7);
27527     memcpy(zDb, zPath, nDb);
27528     zDb[nDb] = '\0';
27529
27530     if( 0==stat(zDb, &sStat) ){
27531       *pMode = sStat.st_mode & 0777;
27532     }else{
27533       rc = SQLITE_IOERR_FSTAT;
27534     }
27535   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
27536     *pMode = 0600;
27537   }else{
27538     *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
27539   }
27540   return rc;
27541 }
27542
27543 /*
27544 ** Open the file zPath.
27545 ** 
27546 ** Previously, the SQLite OS layer used three functions in place of this
27547 ** one:
27548 **
27549 **     sqlite3OsOpenReadWrite();
27550 **     sqlite3OsOpenReadOnly();
27551 **     sqlite3OsOpenExclusive();
27552 **
27553 ** These calls correspond to the following combinations of flags:
27554 **
27555 **     ReadWrite() ->     (READWRITE | CREATE)
27556 **     ReadOnly()  ->     (READONLY) 
27557 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
27558 **
27559 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
27560 ** true, the file was configured to be automatically deleted when the
27561 ** file handle closed. To achieve the same effect using this new 
27562 ** interface, add the DELETEONCLOSE flag to those specified above for 
27563 ** OpenExclusive().
27564 */
27565 static int unixOpen(
27566   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
27567   const char *zPath,           /* Pathname of file to be opened */
27568   sqlite3_file *pFile,         /* The file descriptor to be filled in */
27569   int flags,                   /* Input flags to control the opening */
27570   int *pOutFlags               /* Output flags returned to SQLite core */
27571 ){
27572   unixFile *p = (unixFile *)pFile;
27573   int fd = -1;                   /* File descriptor returned by open() */
27574   int dirfd = -1;                /* Directory file descriptor */
27575   int openFlags = 0;             /* Flags to pass to open() */
27576   int eType = flags&0xFFFFFF00;  /* Type of file to open */
27577   int noLock;                    /* True to omit locking primitives */
27578   int rc = SQLITE_OK;            /* Function Return Code */
27579
27580   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
27581   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
27582   int isCreate     = (flags & SQLITE_OPEN_CREATE);
27583   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
27584   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
27585 #if SQLITE_ENABLE_LOCKING_STYLE
27586   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
27587 #endif
27588
27589   /* If creating a master or main-file journal, this function will open
27590   ** a file-descriptor on the directory too. The first time unixSync()
27591   ** is called the directory file descriptor will be fsync()ed and close()d.
27592   */
27593   int isOpenDirectory = (isCreate && (
27594         eType==SQLITE_OPEN_MASTER_JOURNAL 
27595      || eType==SQLITE_OPEN_MAIN_JOURNAL 
27596      || eType==SQLITE_OPEN_WAL
27597   ));
27598
27599   /* If argument zPath is a NULL pointer, this function is required to open
27600   ** a temporary file. Use this buffer to store the file name in.
27601   */
27602   char zTmpname[MAX_PATHNAME+1];
27603   const char *zName = zPath;
27604
27605   /* Check the following statements are true: 
27606   **
27607   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
27608   **   (b) if CREATE is set, then READWRITE must also be set, and
27609   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
27610   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
27611   */
27612   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
27613   assert(isCreate==0 || isReadWrite);
27614   assert(isExclusive==0 || isCreate);
27615   assert(isDelete==0 || isCreate);
27616
27617   /* The main DB, main journal, WAL file and master journal are never 
27618   ** automatically deleted. Nor are they ever temporary files.  */
27619   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
27620   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
27621   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
27622   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
27623
27624   /* Assert that the upper layer has set one of the "file-type" flags. */
27625   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
27626        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
27627        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
27628        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
27629   );
27630
27631   memset(p, 0, sizeof(unixFile));
27632
27633   if( eType==SQLITE_OPEN_MAIN_DB ){
27634     UnixUnusedFd *pUnused;
27635     pUnused = findReusableFd(zName, flags);
27636     if( pUnused ){
27637       fd = pUnused->fd;
27638     }else{
27639       pUnused = sqlite3_malloc(sizeof(*pUnused));
27640       if( !pUnused ){
27641         return SQLITE_NOMEM;
27642       }
27643     }
27644     p->pUnused = pUnused;
27645   }else if( !zName ){
27646     /* If zName is NULL, the upper layer is requesting a temp file. */
27647     assert(isDelete && !isOpenDirectory);
27648     rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
27649     if( rc!=SQLITE_OK ){
27650       return rc;
27651     }
27652     zName = zTmpname;
27653   }
27654
27655   /* Determine the value of the flags parameter passed to POSIX function
27656   ** open(). These must be calculated even if open() is not called, as
27657   ** they may be stored as part of the file handle and used by the 
27658   ** 'conch file' locking functions later on.  */
27659   if( isReadonly )  openFlags |= O_RDONLY;
27660   if( isReadWrite ) openFlags |= O_RDWR;
27661   if( isCreate )    openFlags |= O_CREAT;
27662   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
27663   openFlags |= (O_LARGEFILE|O_BINARY);
27664
27665   if( fd<0 ){
27666     mode_t openMode;              /* Permissions to create file with */
27667     rc = findCreateFileMode(zName, flags, &openMode);
27668     if( rc!=SQLITE_OK ){
27669       assert( !p->pUnused );
27670       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
27671       return rc;
27672     }
27673     fd = open(zName, openFlags, openMode);
27674     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
27675     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
27676       /* Failed to open the file for read/write access. Try read-only. */
27677       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
27678       openFlags &= ~(O_RDWR|O_CREAT);
27679       flags |= SQLITE_OPEN_READONLY;
27680       openFlags |= O_RDONLY;
27681       fd = open(zName, openFlags, openMode);
27682     }
27683     if( fd<0 ){
27684       rc = SQLITE_CANTOPEN_BKPT;
27685       goto open_finished;
27686     }
27687   }
27688   assert( fd>=0 );
27689   if( pOutFlags ){
27690     *pOutFlags = flags;
27691   }
27692
27693   if( p->pUnused ){
27694     p->pUnused->fd = fd;
27695     p->pUnused->flags = flags;
27696   }
27697
27698   if( isDelete ){
27699 #if OS_VXWORKS
27700     zPath = zName;
27701 #else
27702     unlink(zName);
27703 #endif
27704   }
27705 #if SQLITE_ENABLE_LOCKING_STYLE
27706   else{
27707     p->openFlags = openFlags;
27708   }
27709 #endif
27710
27711   if( isOpenDirectory ){
27712     rc = openDirectory(zPath, &dirfd);
27713     if( rc!=SQLITE_OK ){
27714       /* It is safe to close fd at this point, because it is guaranteed not
27715       ** to be open on a database file. If it were open on a database file,
27716       ** it would not be safe to close as this would release any locks held
27717       ** on the file by this process.  */
27718       assert( eType!=SQLITE_OPEN_MAIN_DB );
27719       close(fd);             /* silently leak if fail, already in error */
27720       goto open_finished;
27721     }
27722   }
27723
27724 #ifdef FD_CLOEXEC
27725   fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
27726 #endif
27727
27728   noLock = eType!=SQLITE_OPEN_MAIN_DB;
27729
27730   
27731 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
27732   struct statfs fsInfo;
27733   if( fstatfs(fd, &fsInfo) == -1 ){
27734     ((unixFile*)pFile)->lastErrno = errno;
27735     if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
27736     close(fd); /* silently leak if fail, in error */
27737     return SQLITE_IOERR_ACCESS;
27738   }
27739   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
27740     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
27741   }
27742 #endif
27743   
27744 #if SQLITE_ENABLE_LOCKING_STYLE
27745 #if SQLITE_PREFER_PROXY_LOCKING
27746   isAutoProxy = 1;
27747 #endif
27748   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
27749     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
27750     int useProxy = 0;
27751
27752     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 
27753     ** never use proxy, NULL means use proxy for non-local files only.  */
27754     if( envforce!=NULL ){
27755       useProxy = atoi(envforce)>0;
27756     }else{
27757       struct statfs fsInfo;
27758       if( statfs(zPath, &fsInfo) == -1 ){
27759         /* In theory, the close(fd) call is sub-optimal. If the file opened
27760         ** with fd is a database file, and there are other connections open
27761         ** on that file that are currently holding advisory locks on it,
27762         ** then the call to close() will cancel those locks. In practice,
27763         ** we're assuming that statfs() doesn't fail very often. At least
27764         ** not while other file descriptors opened by the same process on
27765         ** the same file are working.  */
27766         p->lastErrno = errno;
27767         if( dirfd>=0 ){
27768           close(dirfd); /* silently leak if fail, in error */
27769         }
27770         close(fd); /* silently leak if fail, in error */
27771         rc = SQLITE_IOERR_ACCESS;
27772         goto open_finished;
27773       }
27774       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
27775     }
27776     if( useProxy ){
27777       rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
27778       if( rc==SQLITE_OK ){
27779         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
27780         if( rc!=SQLITE_OK ){
27781           /* Use unixClose to clean up the resources added in fillInUnixFile 
27782           ** and clear all the structure's references.  Specifically, 
27783           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op 
27784           */
27785           unixClose(pFile);
27786           return rc;
27787         }
27788       }
27789       goto open_finished;
27790     }
27791   }
27792 #endif
27793   
27794   rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
27795 open_finished:
27796   if( rc!=SQLITE_OK ){
27797     sqlite3_free(p->pUnused);
27798   }
27799   return rc;
27800 }
27801
27802
27803 /*
27804 ** Delete the file at zPath. If the dirSync argument is true, fsync()
27805 ** the directory after deleting the file.
27806 */
27807 static int unixDelete(
27808   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
27809   const char *zPath,        /* Name of file to be deleted */
27810   int dirSync               /* If true, fsync() directory after deleting file */
27811 ){
27812   int rc = SQLITE_OK;
27813   UNUSED_PARAMETER(NotUsed);
27814   SimulateIOError(return SQLITE_IOERR_DELETE);
27815   if( unlink(zPath)==(-1) && errno!=ENOENT ){
27816     return SQLITE_IOERR_DELETE;
27817   }
27818 #ifndef SQLITE_DISABLE_DIRSYNC
27819   if( dirSync ){
27820     int fd;
27821     rc = openDirectory(zPath, &fd);
27822     if( rc==SQLITE_OK ){
27823 #if OS_VXWORKS
27824       if( fsync(fd)==-1 )
27825 #else
27826       if( fsync(fd) )
27827 #endif
27828       {
27829         rc = SQLITE_IOERR_DIR_FSYNC;
27830       }
27831       if( close(fd)&&!rc ){
27832         rc = SQLITE_IOERR_DIR_CLOSE;
27833       }
27834     }
27835   }
27836 #endif
27837   return rc;
27838 }
27839
27840 /*
27841 ** Test the existance of or access permissions of file zPath. The
27842 ** test performed depends on the value of flags:
27843 **
27844 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
27845 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
27846 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
27847 **
27848 ** Otherwise return 0.
27849 */
27850 static int unixAccess(
27851   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
27852   const char *zPath,      /* Path of the file to examine */
27853   int flags,              /* What do we want to learn about the zPath file? */
27854   int *pResOut            /* Write result boolean here */
27855 ){
27856   int amode = 0;
27857   UNUSED_PARAMETER(NotUsed);
27858   SimulateIOError( return SQLITE_IOERR_ACCESS; );
27859   switch( flags ){
27860     case SQLITE_ACCESS_EXISTS:
27861       amode = F_OK;
27862       break;
27863     case SQLITE_ACCESS_READWRITE:
27864       amode = W_OK|R_OK;
27865       break;
27866     case SQLITE_ACCESS_READ:
27867       amode = R_OK;
27868       break;
27869
27870     default:
27871       assert(!"Invalid flags argument");
27872   }
27873   *pResOut = (access(zPath, amode)==0);
27874   if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
27875     struct stat buf;
27876     if( 0==stat(zPath, &buf) && buf.st_size==0 ){
27877       *pResOut = 0;
27878     }
27879   }
27880   return SQLITE_OK;
27881 }
27882
27883
27884 /*
27885 ** Turn a relative pathname into a full pathname. The relative path
27886 ** is stored as a nul-terminated string in the buffer pointed to by
27887 ** zPath. 
27888 **
27889 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
27890 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
27891 ** this buffer before returning.
27892 */
27893 static int unixFullPathname(
27894   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
27895   const char *zPath,            /* Possibly relative input path */
27896   int nOut,                     /* Size of output buffer in bytes */
27897   char *zOut                    /* Output buffer */
27898 ){
27899
27900   /* It's odd to simulate an io-error here, but really this is just
27901   ** using the io-error infrastructure to test that SQLite handles this
27902   ** function failing. This function could fail if, for example, the
27903   ** current working directory has been unlinked.
27904   */
27905   SimulateIOError( return SQLITE_ERROR );
27906
27907   assert( pVfs->mxPathname==MAX_PATHNAME );
27908   UNUSED_PARAMETER(pVfs);
27909
27910   zOut[nOut-1] = '\0';
27911   if( zPath[0]=='/' ){
27912     sqlite3_snprintf(nOut, zOut, "%s", zPath);
27913   }else{
27914     int nCwd;
27915     if( getcwd(zOut, nOut-1)==0 ){
27916       return SQLITE_CANTOPEN_BKPT;
27917     }
27918     nCwd = (int)strlen(zOut);
27919     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
27920   }
27921   return SQLITE_OK;
27922 }
27923
27924
27925 #ifndef SQLITE_OMIT_LOAD_EXTENSION
27926 /*
27927 ** Interfaces for opening a shared library, finding entry points
27928 ** within the shared library, and closing the shared library.
27929 */
27930 #include <dlfcn.h>
27931 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
27932   UNUSED_PARAMETER(NotUsed);
27933   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
27934 }
27935
27936 /*
27937 ** SQLite calls this function immediately after a call to unixDlSym() or
27938 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
27939 ** message is available, it is written to zBufOut. If no error message
27940 ** is available, zBufOut is left unmodified and SQLite uses a default
27941 ** error message.
27942 */
27943 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
27944   const char *zErr;
27945   UNUSED_PARAMETER(NotUsed);
27946   unixEnterMutex();
27947   zErr = dlerror();
27948   if( zErr ){
27949     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
27950   }
27951   unixLeaveMutex();
27952 }
27953 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
27954   /* 
27955   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
27956   ** cast into a pointer to a function.  And yet the library dlsym() routine
27957   ** returns a void* which is really a pointer to a function.  So how do we
27958   ** use dlsym() with -pedantic-errors?
27959   **
27960   ** Variable x below is defined to be a pointer to a function taking
27961   ** parameters void* and const char* and returning a pointer to a function.
27962   ** We initialize x by assigning it a pointer to the dlsym() function.
27963   ** (That assignment requires a cast.)  Then we call the function that
27964   ** x points to.  
27965   **
27966   ** This work-around is unlikely to work correctly on any system where
27967   ** you really cannot cast a function pointer into void*.  But then, on the
27968   ** other hand, dlsym() will not work on such a system either, so we have
27969   ** not really lost anything.
27970   */
27971   void (*(*x)(void*,const char*))(void);
27972   UNUSED_PARAMETER(NotUsed);
27973   x = (void(*(*)(void*,const char*))(void))dlsym;
27974   return (*x)(p, zSym);
27975 }
27976 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
27977   UNUSED_PARAMETER(NotUsed);
27978   dlclose(pHandle);
27979 }
27980 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
27981   #define unixDlOpen  0
27982   #define unixDlError 0
27983   #define unixDlSym   0
27984   #define unixDlClose 0
27985 #endif
27986
27987 /*
27988 ** Write nBuf bytes of random data to the supplied buffer zBuf.
27989 */
27990 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
27991   UNUSED_PARAMETER(NotUsed);
27992   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
27993
27994   /* We have to initialize zBuf to prevent valgrind from reporting
27995   ** errors.  The reports issued by valgrind are incorrect - we would
27996   ** prefer that the randomness be increased by making use of the
27997   ** uninitialized space in zBuf - but valgrind errors tend to worry
27998   ** some users.  Rather than argue, it seems easier just to initialize
27999   ** the whole array and silence valgrind, even if that means less randomness
28000   ** in the random seed.
28001   **
28002   ** When testing, initializing zBuf[] to zero is all we do.  That means
28003   ** that we always use the same random number sequence.  This makes the
28004   ** tests repeatable.
28005   */
28006   memset(zBuf, 0, nBuf);
28007 #if !defined(SQLITE_TEST)
28008   {
28009     int pid, fd;
28010     fd = open("/dev/urandom", O_RDONLY);
28011     if( fd<0 ){
28012       time_t t;
28013       time(&t);
28014       memcpy(zBuf, &t, sizeof(t));
28015       pid = getpid();
28016       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
28017       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
28018       nBuf = sizeof(t) + sizeof(pid);
28019     }else{
28020       nBuf = read(fd, zBuf, nBuf);
28021       close(fd);
28022     }
28023   }
28024 #endif
28025   return nBuf;
28026 }
28027
28028
28029 /*
28030 ** Sleep for a little while.  Return the amount of time slept.
28031 ** The argument is the number of microseconds we want to sleep.
28032 ** The return value is the number of microseconds of sleep actually
28033 ** requested from the underlying operating system, a number which
28034 ** might be greater than or equal to the argument, but not less
28035 ** than the argument.
28036 */
28037 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
28038 #if OS_VXWORKS
28039   struct timespec sp;
28040
28041   sp.tv_sec = microseconds / 1000000;
28042   sp.tv_nsec = (microseconds % 1000000) * 1000;
28043   nanosleep(&sp, NULL);
28044   UNUSED_PARAMETER(NotUsed);
28045   return microseconds;
28046 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
28047   usleep(microseconds);
28048   UNUSED_PARAMETER(NotUsed);
28049   return microseconds;
28050 #else
28051   int seconds = (microseconds+999999)/1000000;
28052   sleep(seconds);
28053   UNUSED_PARAMETER(NotUsed);
28054   return seconds*1000000;
28055 #endif
28056 }
28057
28058 /*
28059 ** The following variable, if set to a non-zero value, is interpreted as
28060 ** the number of seconds since 1970 and is used to set the result of
28061 ** sqlite3OsCurrentTime() during testing.
28062 */
28063 #ifdef SQLITE_TEST
28064 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
28065 #endif
28066
28067 /*
28068 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
28069 ** the current time and date as a Julian Day number times 86_400_000.  In
28070 ** other words, write into *piNow the number of milliseconds since the Julian
28071 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
28072 ** proleptic Gregorian calendar.
28073 **
28074 ** On success, return 0.  Return 1 if the time and date cannot be found.
28075 */
28076 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
28077   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
28078 #if defined(NO_GETTOD)
28079   time_t t;
28080   time(&t);
28081   *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
28082 #elif OS_VXWORKS
28083   struct timespec sNow;
28084   clock_gettime(CLOCK_REALTIME, &sNow);
28085   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
28086 #else
28087   struct timeval sNow;
28088   gettimeofday(&sNow, 0);
28089   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
28090 #endif
28091
28092 #ifdef SQLITE_TEST
28093   if( sqlite3_current_time ){
28094     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
28095   }
28096 #endif
28097   UNUSED_PARAMETER(NotUsed);
28098   return 0;
28099 }
28100
28101 /*
28102 ** Find the current time (in Universal Coordinated Time).  Write the
28103 ** current time and date as a Julian Day number into *prNow and
28104 ** return 0.  Return 1 if the time and date cannot be found.
28105 */
28106 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
28107   sqlite3_int64 i;
28108   UNUSED_PARAMETER(NotUsed);
28109   unixCurrentTimeInt64(0, &i);
28110   *prNow = i/86400000.0;
28111   return 0;
28112 }
28113
28114 /*
28115 ** We added the xGetLastError() method with the intention of providing
28116 ** better low-level error messages when operating-system problems come up
28117 ** during SQLite operation.  But so far, none of that has been implemented
28118 ** in the core.  So this routine is never called.  For now, it is merely
28119 ** a place-holder.
28120 */
28121 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
28122   UNUSED_PARAMETER(NotUsed);
28123   UNUSED_PARAMETER(NotUsed2);
28124   UNUSED_PARAMETER(NotUsed3);
28125   return 0;
28126 }
28127
28128
28129 /*
28130 ************************ End of sqlite3_vfs methods ***************************
28131 ******************************************************************************/
28132
28133 /******************************************************************************
28134 ************************** Begin Proxy Locking ********************************
28135 **
28136 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
28137 ** other locking methods on secondary lock files.  Proxy locking is a
28138 ** meta-layer over top of the primitive locking implemented above.  For
28139 ** this reason, the division that implements of proxy locking is deferred
28140 ** until late in the file (here) after all of the other I/O methods have
28141 ** been defined - so that the primitive locking methods are available
28142 ** as services to help with the implementation of proxy locking.
28143 **
28144 ****
28145 **
28146 ** The default locking schemes in SQLite use byte-range locks on the
28147 ** database file to coordinate safe, concurrent access by multiple readers
28148 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
28149 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
28150 ** as POSIX read & write locks over fixed set of locations (via fsctl),
28151 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
28152 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
28153 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
28154 ** address in the shared range is taken for a SHARED lock, the entire
28155 ** shared range is taken for an EXCLUSIVE lock):
28156 **
28157 **      PENDING_BYTE        0x40000000                  
28158 **      RESERVED_BYTE       0x40000001
28159 **      SHARED_RANGE        0x40000002 -> 0x40000200
28160 **
28161 ** This works well on the local file system, but shows a nearly 100x
28162 ** slowdown in read performance on AFP because the AFP client disables
28163 ** the read cache when byte-range locks are present.  Enabling the read
28164 ** cache exposes a cache coherency problem that is present on all OS X
28165 ** supported network file systems.  NFS and AFP both observe the
28166 ** close-to-open semantics for ensuring cache coherency
28167 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
28168 ** address the requirements for concurrent database access by multiple
28169 ** readers and writers
28170 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
28171 **
28172 ** To address the performance and cache coherency issues, proxy file locking
28173 ** changes the way database access is controlled by limiting access to a
28174 ** single host at a time and moving file locks off of the database file
28175 ** and onto a proxy file on the local file system.  
28176 **
28177 **
28178 ** Using proxy locks
28179 ** -----------------
28180 **
28181 ** C APIs
28182 **
28183 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
28184 **                       <proxy_path> | ":auto:");
28185 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
28186 **
28187 **
28188 ** SQL pragmas
28189 **
28190 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
28191 **  PRAGMA [database.]lock_proxy_file
28192 **
28193 ** Specifying ":auto:" means that if there is a conch file with a matching
28194 ** host ID in it, the proxy path in the conch file will be used, otherwise
28195 ** a proxy path based on the user's temp dir
28196 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
28197 ** actual proxy file name is generated from the name and path of the
28198 ** database file.  For example:
28199 **
28200 **       For database path "/Users/me/foo.db" 
28201 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
28202 **
28203 ** Once a lock proxy is configured for a database connection, it can not
28204 ** be removed, however it may be switched to a different proxy path via
28205 ** the above APIs (assuming the conch file is not being held by another
28206 ** connection or process). 
28207 **
28208 **
28209 ** How proxy locking works
28210 ** -----------------------
28211 **
28212 ** Proxy file locking relies primarily on two new supporting files: 
28213 **
28214 **   *  conch file to limit access to the database file to a single host
28215 **      at a time
28216 **
28217 **   *  proxy file to act as a proxy for the advisory locks normally
28218 **      taken on the database
28219 **
28220 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
28221 ** by taking an sqlite-style shared lock on the conch file, reading the
28222 ** contents and comparing the host's unique host ID (see below) and lock
28223 ** proxy path against the values stored in the conch.  The conch file is
28224 ** stored in the same directory as the database file and the file name
28225 ** is patterned after the database file name as ".<databasename>-conch".
28226 ** If the conch file does not exist, or it's contents do not match the
28227 ** host ID and/or proxy path, then the lock is escalated to an exclusive
28228 ** lock and the conch file contents is updated with the host ID and proxy
28229 ** path and the lock is downgraded to a shared lock again.  If the conch
28230 ** is held by another process (with a shared lock), the exclusive lock
28231 ** will fail and SQLITE_BUSY is returned.
28232 **
28233 ** The proxy file - a single-byte file used for all advisory file locks
28234 ** normally taken on the database file.   This allows for safe sharing
28235 ** of the database file for multiple readers and writers on the same
28236 ** host (the conch ensures that they all use the same local lock file).
28237 **
28238 ** Requesting the lock proxy does not immediately take the conch, it is
28239 ** only taken when the first request to lock database file is made.  
28240 ** This matches the semantics of the traditional locking behavior, where
28241 ** opening a connection to a database file does not take a lock on it.
28242 ** The shared lock and an open file descriptor are maintained until 
28243 ** the connection to the database is closed. 
28244 **
28245 ** The proxy file and the lock file are never deleted so they only need
28246 ** to be created the first time they are used.
28247 **
28248 ** Configuration options
28249 ** ---------------------
28250 **
28251 **  SQLITE_PREFER_PROXY_LOCKING
28252 **
28253 **       Database files accessed on non-local file systems are
28254 **       automatically configured for proxy locking, lock files are
28255 **       named automatically using the same logic as
28256 **       PRAGMA lock_proxy_file=":auto:"
28257 **    
28258 **  SQLITE_PROXY_DEBUG
28259 **
28260 **       Enables the logging of error messages during host id file
28261 **       retrieval and creation
28262 **
28263 **  LOCKPROXYDIR
28264 **
28265 **       Overrides the default directory used for lock proxy files that
28266 **       are named automatically via the ":auto:" setting
28267 **
28268 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
28269 **
28270 **       Permissions to use when creating a directory for storing the
28271 **       lock proxy files, only used when LOCKPROXYDIR is not set.
28272 **    
28273 **    
28274 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
28275 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
28276 ** force proxy locking to be used for every database file opened, and 0
28277 ** will force automatic proxy locking to be disabled for all database
28278 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
28279 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
28280 */
28281
28282 /*
28283 ** Proxy locking is only available on MacOSX 
28284 */
28285 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28286
28287 /*
28288 ** The proxyLockingContext has the path and file structures for the remote 
28289 ** and local proxy files in it
28290 */
28291 typedef struct proxyLockingContext proxyLockingContext;
28292 struct proxyLockingContext {
28293   unixFile *conchFile;         /* Open conch file */
28294   char *conchFilePath;         /* Name of the conch file */
28295   unixFile *lockProxy;         /* Open proxy lock file */
28296   char *lockProxyPath;         /* Name of the proxy lock file */
28297   char *dbPath;                /* Name of the open file */
28298   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
28299   void *oldLockingContext;     /* Original lockingcontext to restore on close */
28300   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
28301 };
28302
28303 /* 
28304 ** The proxy lock file path for the database at dbPath is written into lPath, 
28305 ** which must point to valid, writable memory large enough for a maxLen length
28306 ** file path. 
28307 */
28308 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
28309   int len;
28310   int dbLen;
28311   int i;
28312
28313 #ifdef LOCKPROXYDIR
28314   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
28315 #else
28316 # ifdef _CS_DARWIN_USER_TEMP_DIR
28317   {
28318     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
28319       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
28320                lPath, errno, getpid()));
28321       return SQLITE_IOERR_LOCK;
28322     }
28323     len = strlcat(lPath, "sqliteplocks", maxLen);    
28324   }
28325 # else
28326   len = strlcpy(lPath, "/tmp/", maxLen);
28327 # endif
28328 #endif
28329
28330   if( lPath[len-1]!='/' ){
28331     len = strlcat(lPath, "/", maxLen);
28332   }
28333   
28334   /* transform the db path to a unique cache name */
28335   dbLen = (int)strlen(dbPath);
28336   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
28337     char c = dbPath[i];
28338     lPath[i+len] = (c=='/')?'_':c;
28339   }
28340   lPath[i+len]='\0';
28341   strlcat(lPath, ":auto:", maxLen);
28342   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
28343   return SQLITE_OK;
28344 }
28345
28346 /* 
28347  ** Creates the lock file and any missing directories in lockPath
28348  */
28349 static int proxyCreateLockPath(const char *lockPath){
28350   int i, len;
28351   char buf[MAXPATHLEN];
28352   int start = 0;
28353   
28354   assert(lockPath!=NULL);
28355   /* try to create all the intermediate directories */
28356   len = (int)strlen(lockPath);
28357   buf[0] = lockPath[0];
28358   for( i=1; i<len; i++ ){
28359     if( lockPath[i] == '/' && (i - start > 0) ){
28360       /* only mkdir if leaf dir != "." or "/" or ".." */
28361       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') 
28362          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
28363         buf[i]='\0';
28364         if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
28365           int err=errno;
28366           if( err!=EEXIST ) {
28367             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
28368                      "'%s' proxy lock path=%s pid=%d\n",
28369                      buf, strerror(err), lockPath, getpid()));
28370             return err;
28371           }
28372         }
28373       }
28374       start=i+1;
28375     }
28376     buf[i] = lockPath[i];
28377   }
28378   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
28379   return 0;
28380 }
28381
28382 /*
28383 ** Create a new VFS file descriptor (stored in memory obtained from
28384 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
28385 **
28386 ** The caller is responsible not only for closing the file descriptor
28387 ** but also for freeing the memory associated with the file descriptor.
28388 */
28389 static int proxyCreateUnixFile(
28390     const char *path,        /* path for the new unixFile */
28391     unixFile **ppFile,       /* unixFile created and returned by ref */
28392     int islockfile           /* if non zero missing dirs will be created */
28393 ) {
28394   int fd = -1;
28395   int dirfd = -1;
28396   unixFile *pNew;
28397   int rc = SQLITE_OK;
28398   int openFlags = O_RDWR | O_CREAT;
28399   sqlite3_vfs dummyVfs;
28400   int terrno = 0;
28401   UnixUnusedFd *pUnused = NULL;
28402
28403   /* 1. first try to open/create the file
28404   ** 2. if that fails, and this is a lock file (not-conch), try creating
28405   ** the parent directories and then try again.
28406   ** 3. if that fails, try to open the file read-only
28407   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
28408   */
28409   pUnused = findReusableFd(path, openFlags);
28410   if( pUnused ){
28411     fd = pUnused->fd;
28412   }else{
28413     pUnused = sqlite3_malloc(sizeof(*pUnused));
28414     if( !pUnused ){
28415       return SQLITE_NOMEM;
28416     }
28417   }
28418   if( fd<0 ){
28419     fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
28420     terrno = errno;
28421     if( fd<0 && errno==ENOENT && islockfile ){
28422       if( proxyCreateLockPath(path) == SQLITE_OK ){
28423         fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
28424       }
28425     }
28426   }
28427   if( fd<0 ){
28428     openFlags = O_RDONLY;
28429     fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
28430     terrno = errno;
28431   }
28432   if( fd<0 ){
28433     if( islockfile ){
28434       return SQLITE_BUSY;
28435     }
28436     switch (terrno) {
28437       case EACCES:
28438         return SQLITE_PERM;
28439       case EIO: 
28440         return SQLITE_IOERR_LOCK; /* even though it is the conch */
28441       default:
28442         return SQLITE_CANTOPEN_BKPT;
28443     }
28444   }
28445   
28446   pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
28447   if( pNew==NULL ){
28448     rc = SQLITE_NOMEM;
28449     goto end_create_proxy;
28450   }
28451   memset(pNew, 0, sizeof(unixFile));
28452   pNew->openFlags = openFlags;
28453   dummyVfs.pAppData = (void*)&autolockIoFinder;
28454   pUnused->fd = fd;
28455   pUnused->flags = openFlags;
28456   pNew->pUnused = pUnused;
28457   
28458   rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
28459   if( rc==SQLITE_OK ){
28460     *ppFile = pNew;
28461     return SQLITE_OK;
28462   }
28463 end_create_proxy:    
28464   close(fd); /* silently leak fd if error, we're already in error */
28465   sqlite3_free(pNew);
28466   sqlite3_free(pUnused);
28467   return rc;
28468 }
28469
28470 #ifdef SQLITE_TEST
28471 /* simulate multiple hosts by creating unique hostid file paths */
28472 SQLITE_API int sqlite3_hostid_num = 0;
28473 #endif
28474
28475 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
28476
28477 /* Not always defined in the headers as it ought to be */
28478 extern int gethostuuid(uuid_t id, const struct timespec *wait);
28479
28480 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN 
28481 ** bytes of writable memory.
28482 */
28483 static int proxyGetHostID(unsigned char *pHostID, int *pError){
28484   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
28485   memset(pHostID, 0, PROXY_HOSTIDLEN);
28486 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
28487                && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
28488   {
28489     static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
28490     if( gethostuuid(pHostID, &timeout) ){
28491       int err = errno;
28492       if( pError ){
28493         *pError = err;
28494       }
28495       return SQLITE_IOERR;
28496     }
28497   }
28498 #endif
28499 #ifdef SQLITE_TEST
28500   /* simulate multiple hosts by creating unique hostid file paths */
28501   if( sqlite3_hostid_num != 0){
28502     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
28503   }
28504 #endif
28505   
28506   return SQLITE_OK;
28507 }
28508
28509 /* The conch file contains the header, host id and lock file path
28510  */
28511 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
28512 #define PROXY_HEADERLEN    1   /* conch file header length */
28513 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
28514 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
28515
28516 /* 
28517 ** Takes an open conch file, copies the contents to a new path and then moves 
28518 ** it back.  The newly created file's file descriptor is assigned to the
28519 ** conch file structure and finally the original conch file descriptor is 
28520 ** closed.  Returns zero if successful.
28521 */
28522 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
28523   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
28524   unixFile *conchFile = pCtx->conchFile;
28525   char tPath[MAXPATHLEN];
28526   char buf[PROXY_MAXCONCHLEN];
28527   char *cPath = pCtx->conchFilePath;
28528   size_t readLen = 0;
28529   size_t pathLen = 0;
28530   char errmsg[64] = "";
28531   int fd = -1;
28532   int rc = -1;
28533   UNUSED_PARAMETER(myHostID);
28534
28535   /* create a new path by replace the trailing '-conch' with '-break' */
28536   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
28537   if( pathLen>MAXPATHLEN || pathLen<6 || 
28538      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
28539     sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
28540     goto end_breaklock;
28541   }
28542   /* read the conch content */
28543   readLen = pread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
28544   if( readLen<PROXY_PATHINDEX ){
28545     sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
28546     goto end_breaklock;
28547   }
28548   /* write it out to the temporary break file */
28549   fd = open(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
28550   if( fd<0 ){
28551     sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
28552     goto end_breaklock;
28553   }
28554   if( pwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
28555     sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
28556     goto end_breaklock;
28557   }
28558   if( rename(tPath, cPath) ){
28559     sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
28560     goto end_breaklock;
28561   }
28562   rc = 0;
28563   fprintf(stderr, "broke stale lock on %s\n", cPath);
28564   close(conchFile->h);
28565   conchFile->h = fd;
28566   conchFile->openFlags = O_RDWR | O_CREAT;
28567
28568 end_breaklock:
28569   if( rc ){
28570     if( fd>=0 ){
28571       unlink(tPath);
28572       close(fd);
28573     }
28574     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
28575   }
28576   return rc;
28577 }
28578
28579 /* Take the requested lock on the conch file and break a stale lock if the 
28580 ** host id matches.
28581 */
28582 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
28583   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
28584   unixFile *conchFile = pCtx->conchFile;
28585   int rc = SQLITE_OK;
28586   int nTries = 0;
28587   struct timespec conchModTime;
28588   
28589   do {
28590     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
28591     nTries ++;
28592     if( rc==SQLITE_BUSY ){
28593       /* If the lock failed (busy):
28594        * 1st try: get the mod time of the conch, wait 0.5s and try again. 
28595        * 2nd try: fail if the mod time changed or host id is different, wait 
28596        *           10 sec and try again
28597        * 3rd try: break the lock unless the mod time has changed.
28598        */
28599       struct stat buf;
28600       if( fstat(conchFile->h, &buf) ){
28601         pFile->lastErrno = errno;
28602         return SQLITE_IOERR_LOCK;
28603       }
28604       
28605       if( nTries==1 ){
28606         conchModTime = buf.st_mtimespec;
28607         usleep(500000); /* wait 0.5 sec and try the lock again*/
28608         continue;  
28609       }
28610
28611       assert( nTries>1 );
28612       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || 
28613          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
28614         return SQLITE_BUSY;
28615       }
28616       
28617       if( nTries==2 ){  
28618         char tBuf[PROXY_MAXCONCHLEN];
28619         int len = pread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
28620         if( len<0 ){
28621           pFile->lastErrno = errno;
28622           return SQLITE_IOERR_LOCK;
28623         }
28624         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
28625           /* don't break the lock if the host id doesn't match */
28626           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
28627             return SQLITE_BUSY;
28628           }
28629         }else{
28630           /* don't break the lock on short read or a version mismatch */
28631           return SQLITE_BUSY;
28632         }
28633         usleep(10000000); /* wait 10 sec and try the lock again */
28634         continue; 
28635       }
28636       
28637       assert( nTries==3 );
28638       if( 0==proxyBreakConchLock(pFile, myHostID) ){
28639         rc = SQLITE_OK;
28640         if( lockType==EXCLUSIVE_LOCK ){
28641           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);          
28642         }
28643         if( !rc ){
28644           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
28645         }
28646       }
28647     }
28648   } while( rc==SQLITE_BUSY && nTries<3 );
28649   
28650   return rc;
28651 }
28652
28653 /* Takes the conch by taking a shared lock and read the contents conch, if 
28654 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL 
28655 ** lockPath means that the lockPath in the conch file will be used if the 
28656 ** host IDs match, or a new lock path will be generated automatically 
28657 ** and written to the conch file.
28658 */
28659 static int proxyTakeConch(unixFile *pFile){
28660   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
28661   
28662   if( pCtx->conchHeld!=0 ){
28663     return SQLITE_OK;
28664   }else{
28665     unixFile *conchFile = pCtx->conchFile;
28666     uuid_t myHostID;
28667     int pError = 0;
28668     char readBuf[PROXY_MAXCONCHLEN];
28669     char lockPath[MAXPATHLEN];
28670     char *tempLockPath = NULL;
28671     int rc = SQLITE_OK;
28672     int createConch = 0;
28673     int hostIdMatch = 0;
28674     int readLen = 0;
28675     int tryOldLockPath = 0;
28676     int forceNewLockPath = 0;
28677     
28678     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
28679              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
28680
28681     rc = proxyGetHostID(myHostID, &pError);
28682     if( (rc&0xff)==SQLITE_IOERR ){
28683       pFile->lastErrno = pError;
28684       goto end_takeconch;
28685     }
28686     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
28687     if( rc!=SQLITE_OK ){
28688       goto end_takeconch;
28689     }
28690     /* read the existing conch file */
28691     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
28692     if( readLen<0 ){
28693       /* I/O error: lastErrno set by seekAndRead */
28694       pFile->lastErrno = conchFile->lastErrno;
28695       rc = SQLITE_IOERR_READ;
28696       goto end_takeconch;
28697     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || 
28698              readBuf[0]!=(char)PROXY_CONCHVERSION ){
28699       /* a short read or version format mismatch means we need to create a new 
28700       ** conch file. 
28701       */
28702       createConch = 1;
28703     }
28704     /* if the host id matches and the lock path already exists in the conch
28705     ** we'll try to use the path there, if we can't open that path, we'll 
28706     ** retry with a new auto-generated path 
28707     */
28708     do { /* in case we need to try again for an :auto: named lock file */
28709
28710       if( !createConch && !forceNewLockPath ){
28711         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, 
28712                                   PROXY_HOSTIDLEN);
28713         /* if the conch has data compare the contents */
28714         if( !pCtx->lockProxyPath ){
28715           /* for auto-named local lock file, just check the host ID and we'll
28716            ** use the local lock file path that's already in there
28717            */
28718           if( hostIdMatch ){
28719             size_t pathLen = (readLen - PROXY_PATHINDEX);
28720             
28721             if( pathLen>=MAXPATHLEN ){
28722               pathLen=MAXPATHLEN-1;
28723             }
28724             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
28725             lockPath[pathLen] = 0;
28726             tempLockPath = lockPath;
28727             tryOldLockPath = 1;
28728             /* create a copy of the lock path if the conch is taken */
28729             goto end_takeconch;
28730           }
28731         }else if( hostIdMatch
28732                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
28733                            readLen-PROXY_PATHINDEX)
28734         ){
28735           /* conch host and lock path match */
28736           goto end_takeconch; 
28737         }
28738       }
28739       
28740       /* if the conch isn't writable and doesn't match, we can't take it */
28741       if( (conchFile->openFlags&O_RDWR) == 0 ){
28742         rc = SQLITE_BUSY;
28743         goto end_takeconch;
28744       }
28745       
28746       /* either the conch didn't match or we need to create a new one */
28747       if( !pCtx->lockProxyPath ){
28748         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
28749         tempLockPath = lockPath;
28750         /* create a copy of the lock path _only_ if the conch is taken */
28751       }
28752       
28753       /* update conch with host and path (this will fail if other process
28754       ** has a shared lock already), if the host id matches, use the big
28755       ** stick.
28756       */
28757       futimes(conchFile->h, NULL);
28758       if( hostIdMatch && !createConch ){
28759         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
28760           /* We are trying for an exclusive lock but another thread in this
28761            ** same process is still holding a shared lock. */
28762           rc = SQLITE_BUSY;
28763         } else {          
28764           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
28765         }
28766       }else{
28767         rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
28768       }
28769       if( rc==SQLITE_OK ){
28770         char writeBuffer[PROXY_MAXCONCHLEN];
28771         int writeSize = 0;
28772         
28773         writeBuffer[0] = (char)PROXY_CONCHVERSION;
28774         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
28775         if( pCtx->lockProxyPath!=NULL ){
28776           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
28777         }else{
28778           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
28779         }
28780         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
28781         ftruncate(conchFile->h, writeSize);
28782         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
28783         fsync(conchFile->h);
28784         /* If we created a new conch file (not just updated the contents of a 
28785          ** valid conch file), try to match the permissions of the database 
28786          */
28787         if( rc==SQLITE_OK && createConch ){
28788           struct stat buf;
28789           int err = fstat(pFile->h, &buf);
28790           if( err==0 ){
28791             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
28792                                         S_IROTH|S_IWOTH);
28793             /* try to match the database file R/W permissions, ignore failure */
28794 #ifndef SQLITE_PROXY_DEBUG
28795             fchmod(conchFile->h, cmode);
28796 #else
28797             if( fchmod(conchFile->h, cmode)!=0 ){
28798               int code = errno;
28799               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
28800                       cmode, code, strerror(code));
28801             } else {
28802               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
28803             }
28804           }else{
28805             int code = errno;
28806             fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 
28807                     err, code, strerror(code));
28808 #endif
28809           }
28810         }
28811       }
28812       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
28813       
28814     end_takeconch:
28815       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
28816       if( rc==SQLITE_OK && pFile->openFlags ){
28817         if( pFile->h>=0 ){
28818 #ifdef STRICT_CLOSE_ERROR
28819           if( close(pFile->h) ){
28820             pFile->lastErrno = errno;
28821             return SQLITE_IOERR_CLOSE;
28822           }
28823 #else
28824           close(pFile->h); /* silently leak fd if fail */
28825 #endif
28826         }
28827         pFile->h = -1;
28828         int fd = open(pCtx->dbPath, pFile->openFlags,
28829                       SQLITE_DEFAULT_FILE_PERMISSIONS);
28830         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
28831         if( fd>=0 ){
28832           pFile->h = fd;
28833         }else{
28834           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
28835            during locking */
28836         }
28837       }
28838       if( rc==SQLITE_OK && !pCtx->lockProxy ){
28839         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
28840         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
28841         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
28842           /* we couldn't create the proxy lock file with the old lock file path
28843            ** so try again via auto-naming 
28844            */
28845           forceNewLockPath = 1;
28846           tryOldLockPath = 0;
28847           continue; /* go back to the do {} while start point, try again */
28848         }
28849       }
28850       if( rc==SQLITE_OK ){
28851         /* Need to make a copy of path if we extracted the value
28852          ** from the conch file or the path was allocated on the stack
28853          */
28854         if( tempLockPath ){
28855           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
28856           if( !pCtx->lockProxyPath ){
28857             rc = SQLITE_NOMEM;
28858           }
28859         }
28860       }
28861       if( rc==SQLITE_OK ){
28862         pCtx->conchHeld = 1;
28863         
28864         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
28865           afpLockingContext *afpCtx;
28866           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
28867           afpCtx->dbPath = pCtx->lockProxyPath;
28868         }
28869       } else {
28870         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
28871       }
28872       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
28873                rc==SQLITE_OK?"ok":"failed"));
28874       return rc;
28875     } while (1); /* in case we need to retry the :auto: lock file - 
28876                  ** we should never get here except via the 'continue' call. */
28877   }
28878 }
28879
28880 /*
28881 ** If pFile holds a lock on a conch file, then release that lock.
28882 */
28883 static int proxyReleaseConch(unixFile *pFile){
28884   int rc = SQLITE_OK;         /* Subroutine return code */
28885   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
28886   unixFile *conchFile;        /* Name of the conch file */
28887
28888   pCtx = (proxyLockingContext *)pFile->lockingContext;
28889   conchFile = pCtx->conchFile;
28890   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
28891            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
28892            getpid()));
28893   if( pCtx->conchHeld>0 ){
28894     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
28895   }
28896   pCtx->conchHeld = 0;
28897   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
28898            (rc==SQLITE_OK ? "ok" : "failed")));
28899   return rc;
28900 }
28901
28902 /*
28903 ** Given the name of a database file, compute the name of its conch file.
28904 ** Store the conch filename in memory obtained from sqlite3_malloc().
28905 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
28906 ** or SQLITE_NOMEM if unable to obtain memory.
28907 **
28908 ** The caller is responsible for ensuring that the allocated memory
28909 ** space is eventually freed.
28910 **
28911 ** *pConchPath is set to NULL if a memory allocation error occurs.
28912 */
28913 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
28914   int i;                        /* Loop counter */
28915   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
28916   char *conchPath;              /* buffer in which to construct conch name */
28917
28918   /* Allocate space for the conch filename and initialize the name to
28919   ** the name of the original database file. */  
28920   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
28921   if( conchPath==0 ){
28922     return SQLITE_NOMEM;
28923   }
28924   memcpy(conchPath, dbPath, len+1);
28925   
28926   /* now insert a "." before the last / character */
28927   for( i=(len-1); i>=0; i-- ){
28928     if( conchPath[i]=='/' ){
28929       i++;
28930       break;
28931     }
28932   }
28933   conchPath[i]='.';
28934   while ( i<len ){
28935     conchPath[i+1]=dbPath[i];
28936     i++;
28937   }
28938
28939   /* append the "-conch" suffix to the file */
28940   memcpy(&conchPath[i+1], "-conch", 7);
28941   assert( (int)strlen(conchPath) == len+7 );
28942
28943   return SQLITE_OK;
28944 }
28945
28946
28947 /* Takes a fully configured proxy locking-style unix file and switches
28948 ** the local lock file path 
28949 */
28950 static int switchLockProxyPath(unixFile *pFile, const char *path) {
28951   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
28952   char *oldPath = pCtx->lockProxyPath;
28953   int rc = SQLITE_OK;
28954
28955   if( pFile->eFileLock!=NO_LOCK ){
28956     return SQLITE_BUSY;
28957   }  
28958
28959   /* nothing to do if the path is NULL, :auto: or matches the existing path */
28960   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
28961     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
28962     return SQLITE_OK;
28963   }else{
28964     unixFile *lockProxy = pCtx->lockProxy;
28965     pCtx->lockProxy=NULL;
28966     pCtx->conchHeld = 0;
28967     if( lockProxy!=NULL ){
28968       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
28969       if( rc ) return rc;
28970       sqlite3_free(lockProxy);
28971     }
28972     sqlite3_free(oldPath);
28973     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
28974   }
28975   
28976   return rc;
28977 }
28978
28979 /*
28980 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
28981 ** is a string buffer at least MAXPATHLEN+1 characters in size.
28982 **
28983 ** This routine find the filename associated with pFile and writes it
28984 ** int dbPath.
28985 */
28986 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
28987 #if defined(__APPLE__)
28988   if( pFile->pMethod == &afpIoMethods ){
28989     /* afp style keeps a reference to the db path in the filePath field 
28990     ** of the struct */
28991     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
28992     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
28993   } else
28994 #endif
28995   if( pFile->pMethod == &dotlockIoMethods ){
28996     /* dot lock style uses the locking context to store the dot lock
28997     ** file path */
28998     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
28999     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
29000   }else{
29001     /* all other styles use the locking context to store the db file path */
29002     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
29003     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
29004   }
29005   return SQLITE_OK;
29006 }
29007
29008 /*
29009 ** Takes an already filled in unix file and alters it so all file locking 
29010 ** will be performed on the local proxy lock file.  The following fields
29011 ** are preserved in the locking context so that they can be restored and 
29012 ** the unix structure properly cleaned up at close time:
29013 **  ->lockingContext
29014 **  ->pMethod
29015 */
29016 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
29017   proxyLockingContext *pCtx;
29018   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
29019   char *lockPath=NULL;
29020   int rc = SQLITE_OK;
29021   
29022   if( pFile->eFileLock!=NO_LOCK ){
29023     return SQLITE_BUSY;
29024   }
29025   proxyGetDbPathForUnixFile(pFile, dbPath);
29026   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
29027     lockPath=NULL;
29028   }else{
29029     lockPath=(char *)path;
29030   }
29031   
29032   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
29033            (lockPath ? lockPath : ":auto:"), getpid()));
29034
29035   pCtx = sqlite3_malloc( sizeof(*pCtx) );
29036   if( pCtx==0 ){
29037     return SQLITE_NOMEM;
29038   }
29039   memset(pCtx, 0, sizeof(*pCtx));
29040
29041   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
29042   if( rc==SQLITE_OK ){
29043     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
29044     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
29045       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
29046       ** (c) the file system is read-only, then enable no-locking access.
29047       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
29048       ** that openFlags will have only one of O_RDONLY or O_RDWR.
29049       */
29050       struct statfs fsInfo;
29051       struct stat conchInfo;
29052       int goLockless = 0;
29053
29054       if( stat(pCtx->conchFilePath, &conchInfo) == -1 ) {
29055         int err = errno;
29056         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
29057           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
29058         }
29059       }
29060       if( goLockless ){
29061         pCtx->conchHeld = -1; /* read only FS/ lockless */
29062         rc = SQLITE_OK;
29063       }
29064     }
29065   }  
29066   if( rc==SQLITE_OK && lockPath ){
29067     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
29068   }
29069
29070   if( rc==SQLITE_OK ){
29071     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
29072     if( pCtx->dbPath==NULL ){
29073       rc = SQLITE_NOMEM;
29074     }
29075   }
29076   if( rc==SQLITE_OK ){
29077     /* all memory is allocated, proxys are created and assigned, 
29078     ** switch the locking context and pMethod then return.
29079     */
29080     pCtx->oldLockingContext = pFile->lockingContext;
29081     pFile->lockingContext = pCtx;
29082     pCtx->pOldMethod = pFile->pMethod;
29083     pFile->pMethod = &proxyIoMethods;
29084   }else{
29085     if( pCtx->conchFile ){ 
29086       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
29087       sqlite3_free(pCtx->conchFile);
29088     }
29089     sqlite3DbFree(0, pCtx->lockProxyPath);
29090     sqlite3_free(pCtx->conchFilePath); 
29091     sqlite3_free(pCtx);
29092   }
29093   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
29094            (rc==SQLITE_OK ? "ok" : "failed")));
29095   return rc;
29096 }
29097
29098
29099 /*
29100 ** This routine handles sqlite3_file_control() calls that are specific
29101 ** to proxy locking.
29102 */
29103 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
29104   switch( op ){
29105     case SQLITE_GET_LOCKPROXYFILE: {
29106       unixFile *pFile = (unixFile*)id;
29107       if( pFile->pMethod == &proxyIoMethods ){
29108         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
29109         proxyTakeConch(pFile);
29110         if( pCtx->lockProxyPath ){
29111           *(const char **)pArg = pCtx->lockProxyPath;
29112         }else{
29113           *(const char **)pArg = ":auto: (not held)";
29114         }
29115       } else {
29116         *(const char **)pArg = NULL;
29117       }
29118       return SQLITE_OK;
29119     }
29120     case SQLITE_SET_LOCKPROXYFILE: {
29121       unixFile *pFile = (unixFile*)id;
29122       int rc = SQLITE_OK;
29123       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
29124       if( pArg==NULL || (const char *)pArg==0 ){
29125         if( isProxyStyle ){
29126           /* turn off proxy locking - not supported */
29127           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
29128         }else{
29129           /* turn off proxy locking - already off - NOOP */
29130           rc = SQLITE_OK;
29131         }
29132       }else{
29133         const char *proxyPath = (const char *)pArg;
29134         if( isProxyStyle ){
29135           proxyLockingContext *pCtx = 
29136             (proxyLockingContext*)pFile->lockingContext;
29137           if( !strcmp(pArg, ":auto:") 
29138            || (pCtx->lockProxyPath &&
29139                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
29140           ){
29141             rc = SQLITE_OK;
29142           }else{
29143             rc = switchLockProxyPath(pFile, proxyPath);
29144           }
29145         }else{
29146           /* turn on proxy file locking */
29147           rc = proxyTransformUnixFile(pFile, proxyPath);
29148         }
29149       }
29150       return rc;
29151     }
29152     default: {
29153       assert( 0 );  /* The call assures that only valid opcodes are sent */
29154     }
29155   }
29156   /*NOTREACHED*/
29157   return SQLITE_ERROR;
29158 }
29159
29160 /*
29161 ** Within this division (the proxying locking implementation) the procedures
29162 ** above this point are all utilities.  The lock-related methods of the
29163 ** proxy-locking sqlite3_io_method object follow.
29164 */
29165
29166
29167 /*
29168 ** This routine checks if there is a RESERVED lock held on the specified
29169 ** file by this or any other process. If such a lock is held, set *pResOut
29170 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
29171 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
29172 */
29173 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
29174   unixFile *pFile = (unixFile*)id;
29175   int rc = proxyTakeConch(pFile);
29176   if( rc==SQLITE_OK ){
29177     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29178     if( pCtx->conchHeld>0 ){
29179       unixFile *proxy = pCtx->lockProxy;
29180       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
29181     }else{ /* conchHeld < 0 is lockless */
29182       pResOut=0;
29183     }
29184   }
29185   return rc;
29186 }
29187
29188 /*
29189 ** Lock the file with the lock specified by parameter eFileLock - one
29190 ** of the following:
29191 **
29192 **     (1) SHARED_LOCK
29193 **     (2) RESERVED_LOCK
29194 **     (3) PENDING_LOCK
29195 **     (4) EXCLUSIVE_LOCK
29196 **
29197 ** Sometimes when requesting one lock state, additional lock states
29198 ** are inserted in between.  The locking might fail on one of the later
29199 ** transitions leaving the lock state different from what it started but
29200 ** still short of its goal.  The following chart shows the allowed
29201 ** transitions and the inserted intermediate states:
29202 **
29203 **    UNLOCKED -> SHARED
29204 **    SHARED -> RESERVED
29205 **    SHARED -> (PENDING) -> EXCLUSIVE
29206 **    RESERVED -> (PENDING) -> EXCLUSIVE
29207 **    PENDING -> EXCLUSIVE
29208 **
29209 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
29210 ** routine to lower a locking level.
29211 */
29212 static int proxyLock(sqlite3_file *id, int eFileLock) {
29213   unixFile *pFile = (unixFile*)id;
29214   int rc = proxyTakeConch(pFile);
29215   if( rc==SQLITE_OK ){
29216     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29217     if( pCtx->conchHeld>0 ){
29218       unixFile *proxy = pCtx->lockProxy;
29219       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
29220       pFile->eFileLock = proxy->eFileLock;
29221     }else{
29222       /* conchHeld < 0 is lockless */
29223     }
29224   }
29225   return rc;
29226 }
29227
29228
29229 /*
29230 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
29231 ** must be either NO_LOCK or SHARED_LOCK.
29232 **
29233 ** If the locking level of the file descriptor is already at or below
29234 ** the requested locking level, this routine is a no-op.
29235 */
29236 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
29237   unixFile *pFile = (unixFile*)id;
29238   int rc = proxyTakeConch(pFile);
29239   if( rc==SQLITE_OK ){
29240     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29241     if( pCtx->conchHeld>0 ){
29242       unixFile *proxy = pCtx->lockProxy;
29243       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
29244       pFile->eFileLock = proxy->eFileLock;
29245     }else{
29246       /* conchHeld < 0 is lockless */
29247     }
29248   }
29249   return rc;
29250 }
29251
29252 /*
29253 ** Close a file that uses proxy locks.
29254 */
29255 static int proxyClose(sqlite3_file *id) {
29256   if( id ){
29257     unixFile *pFile = (unixFile*)id;
29258     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29259     unixFile *lockProxy = pCtx->lockProxy;
29260     unixFile *conchFile = pCtx->conchFile;
29261     int rc = SQLITE_OK;
29262     
29263     if( lockProxy ){
29264       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
29265       if( rc ) return rc;
29266       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
29267       if( rc ) return rc;
29268       sqlite3_free(lockProxy);
29269       pCtx->lockProxy = 0;
29270     }
29271     if( conchFile ){
29272       if( pCtx->conchHeld ){
29273         rc = proxyReleaseConch(pFile);
29274         if( rc ) return rc;
29275       }
29276       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
29277       if( rc ) return rc;
29278       sqlite3_free(conchFile);
29279     }
29280     sqlite3DbFree(0, pCtx->lockProxyPath);
29281     sqlite3_free(pCtx->conchFilePath);
29282     sqlite3DbFree(0, pCtx->dbPath);
29283     /* restore the original locking context and pMethod then close it */
29284     pFile->lockingContext = pCtx->oldLockingContext;
29285     pFile->pMethod = pCtx->pOldMethod;
29286     sqlite3_free(pCtx);
29287     return pFile->pMethod->xClose(id);
29288   }
29289   return SQLITE_OK;
29290 }
29291
29292
29293
29294 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
29295 /*
29296 ** The proxy locking style is intended for use with AFP filesystems.
29297 ** And since AFP is only supported on MacOSX, the proxy locking is also
29298 ** restricted to MacOSX.
29299 ** 
29300 **
29301 ******************* End of the proxy lock implementation **********************
29302 ******************************************************************************/
29303
29304 /*
29305 ** Initialize the operating system interface.
29306 **
29307 ** This routine registers all VFS implementations for unix-like operating
29308 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
29309 ** should be the only routines in this file that are visible from other
29310 ** files.
29311 **
29312 ** This routine is called once during SQLite initialization and by a
29313 ** single thread.  The memory allocation and mutex subsystems have not
29314 ** necessarily been initialized when this routine is called, and so they
29315 ** should not be used.
29316 */
29317 SQLITE_API int sqlite3_os_init(void){ 
29318   /* 
29319   ** The following macro defines an initializer for an sqlite3_vfs object.
29320   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
29321   ** to the "finder" function.  (pAppData is a pointer to a pointer because
29322   ** silly C90 rules prohibit a void* from being cast to a function pointer
29323   ** and so we have to go through the intermediate pointer to avoid problems
29324   ** when compiling with -pedantic-errors on GCC.)
29325   **
29326   ** The FINDER parameter to this macro is the name of the pointer to the
29327   ** finder-function.  The finder-function returns a pointer to the
29328   ** sqlite_io_methods object that implements the desired locking
29329   ** behaviors.  See the division above that contains the IOMETHODS
29330   ** macro for addition information on finder-functions.
29331   **
29332   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
29333   ** object.  But the "autolockIoFinder" available on MacOSX does a little
29334   ** more than that; it looks at the filesystem type that hosts the 
29335   ** database file and tries to choose an locking method appropriate for
29336   ** that filesystem time.
29337   */
29338   #define UNIXVFS(VFSNAME, FINDER) {                        \
29339     2,                    /* iVersion */                    \
29340     sizeof(unixFile),     /* szOsFile */                    \
29341     MAX_PATHNAME,         /* mxPathname */                  \
29342     0,                    /* pNext */                       \
29343     VFSNAME,              /* zName */                       \
29344     (void*)&FINDER,       /* pAppData */                    \
29345     unixOpen,             /* xOpen */                       \
29346     unixDelete,           /* xDelete */                     \
29347     unixAccess,           /* xAccess */                     \
29348     unixFullPathname,     /* xFullPathname */               \
29349     unixDlOpen,           /* xDlOpen */                     \
29350     unixDlError,          /* xDlError */                    \
29351     unixDlSym,            /* xDlSym */                      \
29352     unixDlClose,          /* xDlClose */                    \
29353     unixRandomness,       /* xRandomness */                 \
29354     unixSleep,            /* xSleep */                      \
29355     unixCurrentTime,      /* xCurrentTime */                \
29356     unixGetLastError,     /* xGetLastError */               \
29357     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
29358   }
29359
29360   /*
29361   ** All default VFSes for unix are contained in the following array.
29362   **
29363   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
29364   ** by the SQLite core when the VFS is registered.  So the following
29365   ** array cannot be const.
29366   */
29367   static sqlite3_vfs aVfs[] = {
29368 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
29369     UNIXVFS("unix",          autolockIoFinder ),
29370 #else
29371     UNIXVFS("unix",          posixIoFinder ),
29372 #endif
29373     UNIXVFS("unix-none",     nolockIoFinder ),
29374     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
29375 #if OS_VXWORKS
29376     UNIXVFS("unix-namedsem", semIoFinder ),
29377 #endif
29378 #if SQLITE_ENABLE_LOCKING_STYLE
29379     UNIXVFS("unix-posix",    posixIoFinder ),
29380 #if !OS_VXWORKS
29381     UNIXVFS("unix-flock",    flockIoFinder ),
29382 #endif
29383 #endif
29384 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
29385     UNIXVFS("unix-afp",      afpIoFinder ),
29386     UNIXVFS("unix-nfs",      nfsIoFinder ),
29387     UNIXVFS("unix-proxy",    proxyIoFinder ),
29388 #endif
29389   };
29390   unsigned int i;          /* Loop counter */
29391
29392   /* Register all VFSes defined in the aVfs[] array */
29393   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
29394     sqlite3_vfs_register(&aVfs[i], i==0);
29395   }
29396   return SQLITE_OK; 
29397 }
29398
29399 /*
29400 ** Shutdown the operating system interface.
29401 **
29402 ** Some operating systems might need to do some cleanup in this routine,
29403 ** to release dynamically allocated objects.  But not on unix.
29404 ** This routine is a no-op for unix.
29405 */
29406 SQLITE_API int sqlite3_os_end(void){ 
29407   return SQLITE_OK; 
29408 }
29409  
29410 #endif /* SQLITE_OS_UNIX */
29411
29412 /************** End of os_unix.c *********************************************/
29413 /************** Begin file os_win.c ******************************************/
29414 /*
29415 ** 2004 May 22
29416 **
29417 ** The author disclaims copyright to this source code.  In place of
29418 ** a legal notice, here is a blessing:
29419 **
29420 **    May you do good and not evil.
29421 **    May you find forgiveness for yourself and forgive others.
29422 **    May you share freely, never taking more than you give.
29423 **
29424 ******************************************************************************
29425 **
29426 ** This file contains code that is specific to windows.
29427 */
29428 #if SQLITE_OS_WIN               /* This file is used for windows only */
29429
29430
29431 /*
29432 ** A Note About Memory Allocation:
29433 **
29434 ** This driver uses malloc()/free() directly rather than going through
29435 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
29436 ** are designed for use on embedded systems where memory is scarce and
29437 ** malloc failures happen frequently.  Win32 does not typically run on
29438 ** embedded systems, and when it does the developers normally have bigger
29439 ** problems to worry about than running out of memory.  So there is not
29440 ** a compelling need to use the wrappers.
29441 **
29442 ** But there is a good reason to not use the wrappers.  If we use the
29443 ** wrappers then we will get simulated malloc() failures within this
29444 ** driver.  And that causes all kinds of problems for our tests.  We
29445 ** could enhance SQLite to deal with simulated malloc failures within
29446 ** the OS driver, but the code to deal with those failure would not
29447 ** be exercised on Linux (which does not need to malloc() in the driver)
29448 ** and so we would have difficulty writing coverage tests for that
29449 ** code.  Better to leave the code out, we think.
29450 **
29451 ** The point of this discussion is as follows:  When creating a new
29452 ** OS layer for an embedded system, if you use this file as an example,
29453 ** avoid the use of malloc()/free().  Those routines work ok on windows
29454 ** desktops but not so well in embedded systems.
29455 */
29456
29457 #include <winbase.h>
29458
29459 #ifdef __CYGWIN__
29460 # include <sys/cygwin.h>
29461 #endif
29462
29463 /*
29464 ** Macros used to determine whether or not to use threads.
29465 */
29466 #if defined(THREADSAFE) && THREADSAFE
29467 # define SQLITE_W32_THREADS 1
29468 #endif
29469
29470 /*
29471 ** Include code that is common to all os_*.c files
29472 */
29473 /************** Include os_common.h in the middle of os_win.c ****************/
29474 /************** Begin file os_common.h ***************************************/
29475 /*
29476 ** 2004 May 22
29477 **
29478 ** The author disclaims copyright to this source code.  In place of
29479 ** a legal notice, here is a blessing:
29480 **
29481 **    May you do good and not evil.
29482 **    May you find forgiveness for yourself and forgive others.
29483 **    May you share freely, never taking more than you give.
29484 **
29485 ******************************************************************************
29486 **
29487 ** This file contains macros and a little bit of code that is common to
29488 ** all of the platform-specific files (os_*.c) and is #included into those
29489 ** files.
29490 **
29491 ** This file should be #included by the os_*.c files only.  It is not a
29492 ** general purpose header file.
29493 */
29494 #ifndef _OS_COMMON_H_
29495 #define _OS_COMMON_H_
29496
29497 /*
29498 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
29499 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
29500 ** switch.  The following code should catch this problem at compile-time.
29501 */
29502 #ifdef MEMORY_DEBUG
29503 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
29504 #endif
29505
29506 #ifdef SQLITE_DEBUG
29507 SQLITE_PRIVATE int sqlite3OSTrace = 0;
29508 #define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
29509 #else
29510 #define OSTRACE(X)
29511 #endif
29512
29513 /*
29514 ** Macros for performance tracing.  Normally turned off.  Only works
29515 ** on i486 hardware.
29516 */
29517 #ifdef SQLITE_PERFORMANCE_TRACE
29518
29519 /* 
29520 ** hwtime.h contains inline assembler code for implementing 
29521 ** high-performance timing routines.
29522 */
29523 /************** Include hwtime.h in the middle of os_common.h ****************/
29524 /************** Begin file hwtime.h ******************************************/
29525 /*
29526 ** 2008 May 27
29527 **
29528 ** The author disclaims copyright to this source code.  In place of
29529 ** a legal notice, here is a blessing:
29530 **
29531 **    May you do good and not evil.
29532 **    May you find forgiveness for yourself and forgive others.
29533 **    May you share freely, never taking more than you give.
29534 **
29535 ******************************************************************************
29536 **
29537 ** This file contains inline asm code for retrieving "high-performance"
29538 ** counters for x86 class CPUs.
29539 */
29540 #ifndef _HWTIME_H_
29541 #define _HWTIME_H_
29542
29543 /*
29544 ** The following routine only works on pentium-class (or newer) processors.
29545 ** It uses the RDTSC opcode to read the cycle count value out of the
29546 ** processor and returns that value.  This can be used for high-res
29547 ** profiling.
29548 */
29549 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
29550       (defined(i386) || defined(__i386__) || defined(_M_IX86))
29551
29552   #if defined(__GNUC__)
29553
29554   __inline__ sqlite_uint64 sqlite3Hwtime(void){
29555      unsigned int lo, hi;
29556      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
29557      return (sqlite_uint64)hi << 32 | lo;
29558   }
29559
29560   #elif defined(_MSC_VER)
29561
29562   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
29563      __asm {
29564         rdtsc
29565         ret       ; return value at EDX:EAX
29566      }
29567   }
29568
29569   #endif
29570
29571 #elif (defined(__GNUC__) && defined(__x86_64__))
29572
29573   __inline__ sqlite_uint64 sqlite3Hwtime(void){
29574       unsigned long val;
29575       __asm__ __volatile__ ("rdtsc" : "=A" (val));
29576       return val;
29577   }
29578  
29579 #elif (defined(__GNUC__) && defined(__ppc__))
29580
29581   __inline__ sqlite_uint64 sqlite3Hwtime(void){
29582       unsigned long long retval;
29583       unsigned long junk;
29584       __asm__ __volatile__ ("\n\
29585           1:      mftbu   %1\n\
29586                   mftb    %L0\n\
29587                   mftbu   %0\n\
29588                   cmpw    %0,%1\n\
29589                   bne     1b"
29590                   : "=r" (retval), "=r" (junk));
29591       return retval;
29592   }
29593
29594 #else
29595
29596   #error Need implementation of sqlite3Hwtime() for your platform.
29597
29598   /*
29599   ** To compile without implementing sqlite3Hwtime() for your platform,
29600   ** you can remove the above #error and use the following
29601   ** stub function.  You will lose timing support for many
29602   ** of the debugging and testing utilities, but it should at
29603   ** least compile and run.
29604   */
29605 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
29606
29607 #endif
29608
29609 #endif /* !defined(_HWTIME_H_) */
29610
29611 /************** End of hwtime.h **********************************************/
29612 /************** Continuing where we left off in os_common.h ******************/
29613
29614 static sqlite_uint64 g_start;
29615 static sqlite_uint64 g_elapsed;
29616 #define TIMER_START       g_start=sqlite3Hwtime()
29617 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
29618 #define TIMER_ELAPSED     g_elapsed
29619 #else
29620 #define TIMER_START
29621 #define TIMER_END
29622 #define TIMER_ELAPSED     ((sqlite_uint64)0)
29623 #endif
29624
29625 /*
29626 ** If we compile with the SQLITE_TEST macro set, then the following block
29627 ** of code will give us the ability to simulate a disk I/O error.  This
29628 ** is used for testing the I/O recovery logic.
29629 */
29630 #ifdef SQLITE_TEST
29631 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
29632 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
29633 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
29634 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
29635 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
29636 SQLITE_API int sqlite3_diskfull_pending = 0;
29637 SQLITE_API int sqlite3_diskfull = 0;
29638 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
29639 #define SimulateIOError(CODE)  \
29640   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
29641        || sqlite3_io_error_pending-- == 1 )  \
29642               { local_ioerr(); CODE; }
29643 static void local_ioerr(){
29644   IOTRACE(("IOERR\n"));
29645   sqlite3_io_error_hit++;
29646   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
29647 }
29648 #define SimulateDiskfullError(CODE) \
29649    if( sqlite3_diskfull_pending ){ \
29650      if( sqlite3_diskfull_pending == 1 ){ \
29651        local_ioerr(); \
29652        sqlite3_diskfull = 1; \
29653        sqlite3_io_error_hit = 1; \
29654        CODE; \
29655      }else{ \
29656        sqlite3_diskfull_pending--; \
29657      } \
29658    }
29659 #else
29660 #define SimulateIOErrorBenign(X)
29661 #define SimulateIOError(A)
29662 #define SimulateDiskfullError(A)
29663 #endif
29664
29665 /*
29666 ** When testing, keep a count of the number of open files.
29667 */
29668 #ifdef SQLITE_TEST
29669 SQLITE_API int sqlite3_open_file_count = 0;
29670 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
29671 #else
29672 #define OpenCounter(X)
29673 #endif
29674
29675 #endif /* !defined(_OS_COMMON_H_) */
29676
29677 /************** End of os_common.h *******************************************/
29678 /************** Continuing where we left off in os_win.c *********************/
29679
29680 /*
29681 ** Some microsoft compilers lack this definition.
29682 */
29683 #ifndef INVALID_FILE_ATTRIBUTES
29684 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
29685 #endif
29686
29687 /*
29688 ** Determine if we are dealing with WindowsCE - which has a much
29689 ** reduced API.
29690 */
29691 #if SQLITE_OS_WINCE
29692 # define AreFileApisANSI() 1
29693 # define FormatMessageW(a,b,c,d,e,f,g) 0
29694 #endif
29695
29696 /* Forward references */
29697 typedef struct winShm winShm;           /* A connection to shared-memory */
29698 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
29699
29700 /*
29701 ** WinCE lacks native support for file locking so we have to fake it
29702 ** with some code of our own.
29703 */
29704 #if SQLITE_OS_WINCE
29705 typedef struct winceLock {
29706   int nReaders;       /* Number of reader locks obtained */
29707   BOOL bPending;      /* Indicates a pending lock has been obtained */
29708   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
29709   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
29710 } winceLock;
29711 #endif
29712
29713 /*
29714 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
29715 ** portability layer.
29716 */
29717 typedef struct winFile winFile;
29718 struct winFile {
29719   const sqlite3_io_methods *pMethod; /*** Must be first ***/
29720   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
29721   HANDLE h;               /* Handle for accessing the file */
29722   unsigned char locktype; /* Type of lock currently held on this file */
29723   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
29724   DWORD lastErrno;        /* The Windows errno from the last I/O error */
29725   DWORD sectorSize;       /* Sector size of the device file is on */
29726   winShm *pShm;           /* Instance of shared memory on this file */
29727   const char *zPath;      /* Full pathname of this file */
29728   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
29729 #if SQLITE_OS_WINCE
29730   WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
29731   HANDLE hMutex;          /* Mutex used to control access to shared lock */  
29732   HANDLE hShared;         /* Shared memory segment used for locking */
29733   winceLock local;        /* Locks obtained by this instance of winFile */
29734   winceLock *shared;      /* Global shared lock memory for the file  */
29735 #endif
29736 };
29737
29738 /*
29739 ** Forward prototypes.
29740 */
29741 static int getSectorSize(
29742     sqlite3_vfs *pVfs,
29743     const char *zRelative     /* UTF-8 file name */
29744 );
29745
29746 /*
29747 ** The following variable is (normally) set once and never changes
29748 ** thereafter.  It records whether the operating system is Win95
29749 ** or WinNT.
29750 **
29751 ** 0:   Operating system unknown.
29752 ** 1:   Operating system is Win95.
29753 ** 2:   Operating system is WinNT.
29754 **
29755 ** In order to facilitate testing on a WinNT system, the test fixture
29756 ** can manually set this value to 1 to emulate Win98 behavior.
29757 */
29758 #ifdef SQLITE_TEST
29759 SQLITE_API int sqlite3_os_type = 0;
29760 #else
29761 static int sqlite3_os_type = 0;
29762 #endif
29763
29764 /*
29765 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
29766 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
29767 **
29768 ** Here is an interesting observation:  Win95, Win98, and WinME lack
29769 ** the LockFileEx() API.  But we can still statically link against that
29770 ** API as long as we don't call it when running Win95/98/ME.  A call to
29771 ** this routine is used to determine if the host is Win95/98/ME or
29772 ** WinNT/2K/XP so that we will know whether or not we can safely call
29773 ** the LockFileEx() API.
29774 */
29775 #if SQLITE_OS_WINCE
29776 # define isNT()  (1)
29777 #else
29778   static int isNT(void){
29779     if( sqlite3_os_type==0 ){
29780       OSVERSIONINFO sInfo;
29781       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
29782       GetVersionEx(&sInfo);
29783       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
29784     }
29785     return sqlite3_os_type==2;
29786   }
29787 #endif /* SQLITE_OS_WINCE */
29788
29789 /*
29790 ** Convert a UTF-8 string to microsoft unicode (UTF-16?). 
29791 **
29792 ** Space to hold the returned string is obtained from malloc.
29793 */
29794 static WCHAR *utf8ToUnicode(const char *zFilename){
29795   int nChar;
29796   WCHAR *zWideFilename;
29797
29798   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
29799   zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
29800   if( zWideFilename==0 ){
29801     return 0;
29802   }
29803   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
29804   if( nChar==0 ){
29805     free(zWideFilename);
29806     zWideFilename = 0;
29807   }
29808   return zWideFilename;
29809 }
29810
29811 /*
29812 ** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
29813 ** obtained from malloc().
29814 */
29815 static char *unicodeToUtf8(const WCHAR *zWideFilename){
29816   int nByte;
29817   char *zFilename;
29818
29819   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
29820   zFilename = malloc( nByte );
29821   if( zFilename==0 ){
29822     return 0;
29823   }
29824   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
29825                               0, 0);
29826   if( nByte == 0 ){
29827     free(zFilename);
29828     zFilename = 0;
29829   }
29830   return zFilename;
29831 }
29832
29833 /*
29834 ** Convert an ansi string to microsoft unicode, based on the
29835 ** current codepage settings for file apis.
29836 ** 
29837 ** Space to hold the returned string is obtained
29838 ** from malloc.
29839 */
29840 static WCHAR *mbcsToUnicode(const char *zFilename){
29841   int nByte;
29842   WCHAR *zMbcsFilename;
29843   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
29844
29845   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
29846   zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
29847   if( zMbcsFilename==0 ){
29848     return 0;
29849   }
29850   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
29851   if( nByte==0 ){
29852     free(zMbcsFilename);
29853     zMbcsFilename = 0;
29854   }
29855   return zMbcsFilename;
29856 }
29857
29858 /*
29859 ** Convert microsoft unicode to multibyte character string, based on the
29860 ** user's Ansi codepage.
29861 **
29862 ** Space to hold the returned string is obtained from
29863 ** malloc().
29864 */
29865 static char *unicodeToMbcs(const WCHAR *zWideFilename){
29866   int nByte;
29867   char *zFilename;
29868   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
29869
29870   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
29871   zFilename = malloc( nByte );
29872   if( zFilename==0 ){
29873     return 0;
29874   }
29875   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
29876                               0, 0);
29877   if( nByte == 0 ){
29878     free(zFilename);
29879     zFilename = 0;
29880   }
29881   return zFilename;
29882 }
29883
29884 /*
29885 ** Convert multibyte character string to UTF-8.  Space to hold the
29886 ** returned string is obtained from malloc().
29887 */
29888 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
29889   char *zFilenameUtf8;
29890   WCHAR *zTmpWide;
29891
29892   zTmpWide = mbcsToUnicode(zFilename);
29893   if( zTmpWide==0 ){
29894     return 0;
29895   }
29896   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
29897   free(zTmpWide);
29898   return zFilenameUtf8;
29899 }
29900
29901 /*
29902 ** Convert UTF-8 to multibyte character string.  Space to hold the 
29903 ** returned string is obtained from malloc().
29904 */
29905 static char *utf8ToMbcs(const char *zFilename){
29906   char *zFilenameMbcs;
29907   WCHAR *zTmpWide;
29908
29909   zTmpWide = utf8ToUnicode(zFilename);
29910   if( zTmpWide==0 ){
29911     return 0;
29912   }
29913   zFilenameMbcs = unicodeToMbcs(zTmpWide);
29914   free(zTmpWide);
29915   return zFilenameMbcs;
29916 }
29917
29918 #if SQLITE_OS_WINCE
29919 /*************************************************************************
29920 ** This section contains code for WinCE only.
29921 */
29922 /*
29923 ** WindowsCE does not have a localtime() function.  So create a
29924 ** substitute.
29925 */
29926 struct tm *__cdecl localtime(const time_t *t)
29927 {
29928   static struct tm y;
29929   FILETIME uTm, lTm;
29930   SYSTEMTIME pTm;
29931   sqlite3_int64 t64;
29932   t64 = *t;
29933   t64 = (t64 + 11644473600)*10000000;
29934   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
29935   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
29936   FileTimeToLocalFileTime(&uTm,&lTm);
29937   FileTimeToSystemTime(&lTm,&pTm);
29938   y.tm_year = pTm.wYear - 1900;
29939   y.tm_mon = pTm.wMonth - 1;
29940   y.tm_wday = pTm.wDayOfWeek;
29941   y.tm_mday = pTm.wDay;
29942   y.tm_hour = pTm.wHour;
29943   y.tm_min = pTm.wMinute;
29944   y.tm_sec = pTm.wSecond;
29945   return &y;
29946 }
29947
29948 /* This will never be called, but defined to make the code compile */
29949 #define GetTempPathA(a,b)
29950
29951 #define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
29952 #define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
29953 #define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
29954
29955 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
29956
29957 /*
29958 ** Acquire a lock on the handle h
29959 */
29960 static void winceMutexAcquire(HANDLE h){
29961    DWORD dwErr;
29962    do {
29963      dwErr = WaitForSingleObject(h, INFINITE);
29964    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
29965 }
29966 /*
29967 ** Release a lock acquired by winceMutexAcquire()
29968 */
29969 #define winceMutexRelease(h) ReleaseMutex(h)
29970
29971 /*
29972 ** Create the mutex and shared memory used for locking in the file
29973 ** descriptor pFile
29974 */
29975 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
29976   WCHAR *zTok;
29977   WCHAR *zName = utf8ToUnicode(zFilename);
29978   BOOL bInit = TRUE;
29979
29980   /* Initialize the local lockdata */
29981   ZeroMemory(&pFile->local, sizeof(pFile->local));
29982
29983   /* Replace the backslashes from the filename and lowercase it
29984   ** to derive a mutex name. */
29985   zTok = CharLowerW(zName);
29986   for (;*zTok;zTok++){
29987     if (*zTok == '\\') *zTok = '_';
29988   }
29989
29990   /* Create/open the named mutex */
29991   pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
29992   if (!pFile->hMutex){
29993     pFile->lastErrno = GetLastError();
29994     free(zName);
29995     return FALSE;
29996   }
29997
29998   /* Acquire the mutex before continuing */
29999   winceMutexAcquire(pFile->hMutex);
30000   
30001   /* Since the names of named mutexes, semaphores, file mappings etc are 
30002   ** case-sensitive, take advantage of that by uppercasing the mutex name
30003   ** and using that as the shared filemapping name.
30004   */
30005   CharUpperW(zName);
30006   pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
30007                                        PAGE_READWRITE, 0, sizeof(winceLock),
30008                                        zName);  
30009
30010   /* Set a flag that indicates we're the first to create the memory so it 
30011   ** must be zero-initialized */
30012   if (GetLastError() == ERROR_ALREADY_EXISTS){
30013     bInit = FALSE;
30014   }
30015
30016   free(zName);
30017
30018   /* If we succeeded in making the shared memory handle, map it. */
30019   if (pFile->hShared){
30020     pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared, 
30021              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
30022     /* If mapping failed, close the shared memory handle and erase it */
30023     if (!pFile->shared){
30024       pFile->lastErrno = GetLastError();
30025       CloseHandle(pFile->hShared);
30026       pFile->hShared = NULL;
30027     }
30028   }
30029
30030   /* If shared memory could not be created, then close the mutex and fail */
30031   if (pFile->hShared == NULL){
30032     winceMutexRelease(pFile->hMutex);
30033     CloseHandle(pFile->hMutex);
30034     pFile->hMutex = NULL;
30035     return FALSE;
30036   }
30037   
30038   /* Initialize the shared memory if we're supposed to */
30039   if (bInit) {
30040     ZeroMemory(pFile->shared, sizeof(winceLock));
30041   }
30042
30043   winceMutexRelease(pFile->hMutex);
30044   return TRUE;
30045 }
30046
30047 /*
30048 ** Destroy the part of winFile that deals with wince locks
30049 */
30050 static void winceDestroyLock(winFile *pFile){
30051   if (pFile->hMutex){
30052     /* Acquire the mutex */
30053     winceMutexAcquire(pFile->hMutex);
30054
30055     /* The following blocks should probably assert in debug mode, but they
30056        are to cleanup in case any locks remained open */
30057     if (pFile->local.nReaders){
30058       pFile->shared->nReaders --;
30059     }
30060     if (pFile->local.bReserved){
30061       pFile->shared->bReserved = FALSE;
30062     }
30063     if (pFile->local.bPending){
30064       pFile->shared->bPending = FALSE;
30065     }
30066     if (pFile->local.bExclusive){
30067       pFile->shared->bExclusive = FALSE;
30068     }
30069
30070     /* De-reference and close our copy of the shared memory handle */
30071     UnmapViewOfFile(pFile->shared);
30072     CloseHandle(pFile->hShared);
30073
30074     /* Done with the mutex */
30075     winceMutexRelease(pFile->hMutex);    
30076     CloseHandle(pFile->hMutex);
30077     pFile->hMutex = NULL;
30078   }
30079 }
30080
30081 /* 
30082 ** An implementation of the LockFile() API of windows for wince
30083 */
30084 static BOOL winceLockFile(
30085   HANDLE *phFile,
30086   DWORD dwFileOffsetLow,
30087   DWORD dwFileOffsetHigh,
30088   DWORD nNumberOfBytesToLockLow,
30089   DWORD nNumberOfBytesToLockHigh
30090 ){
30091   winFile *pFile = HANDLE_TO_WINFILE(phFile);
30092   BOOL bReturn = FALSE;
30093
30094   UNUSED_PARAMETER(dwFileOffsetHigh);
30095   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
30096
30097   if (!pFile->hMutex) return TRUE;
30098   winceMutexAcquire(pFile->hMutex);
30099
30100   /* Wanting an exclusive lock? */
30101   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
30102        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
30103     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
30104        pFile->shared->bExclusive = TRUE;
30105        pFile->local.bExclusive = TRUE;
30106        bReturn = TRUE;
30107     }
30108   }
30109
30110   /* Want a read-only lock? */
30111   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
30112            nNumberOfBytesToLockLow == 1){
30113     if (pFile->shared->bExclusive == 0){
30114       pFile->local.nReaders ++;
30115       if (pFile->local.nReaders == 1){
30116         pFile->shared->nReaders ++;
30117       }
30118       bReturn = TRUE;
30119     }
30120   }
30121
30122   /* Want a pending lock? */
30123   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
30124     /* If no pending lock has been acquired, then acquire it */
30125     if (pFile->shared->bPending == 0) {
30126       pFile->shared->bPending = TRUE;
30127       pFile->local.bPending = TRUE;
30128       bReturn = TRUE;
30129     }
30130   }
30131
30132   /* Want a reserved lock? */
30133   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
30134     if (pFile->shared->bReserved == 0) {
30135       pFile->shared->bReserved = TRUE;
30136       pFile->local.bReserved = TRUE;
30137       bReturn = TRUE;
30138     }
30139   }
30140
30141   winceMutexRelease(pFile->hMutex);
30142   return bReturn;
30143 }
30144
30145 /*
30146 ** An implementation of the UnlockFile API of windows for wince
30147 */
30148 static BOOL winceUnlockFile(
30149   HANDLE *phFile,
30150   DWORD dwFileOffsetLow,
30151   DWORD dwFileOffsetHigh,
30152   DWORD nNumberOfBytesToUnlockLow,
30153   DWORD nNumberOfBytesToUnlockHigh
30154 ){
30155   winFile *pFile = HANDLE_TO_WINFILE(phFile);
30156   BOOL bReturn = FALSE;
30157
30158   UNUSED_PARAMETER(dwFileOffsetHigh);
30159   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
30160
30161   if (!pFile->hMutex) return TRUE;
30162   winceMutexAcquire(pFile->hMutex);
30163
30164   /* Releasing a reader lock or an exclusive lock */
30165   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
30166     /* Did we have an exclusive lock? */
30167     if (pFile->local.bExclusive){
30168       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
30169       pFile->local.bExclusive = FALSE;
30170       pFile->shared->bExclusive = FALSE;
30171       bReturn = TRUE;
30172     }
30173
30174     /* Did we just have a reader lock? */
30175     else if (pFile->local.nReaders){
30176       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
30177       pFile->local.nReaders --;
30178       if (pFile->local.nReaders == 0)
30179       {
30180         pFile->shared->nReaders --;
30181       }
30182       bReturn = TRUE;
30183     }
30184   }
30185
30186   /* Releasing a pending lock */
30187   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
30188     if (pFile->local.bPending){
30189       pFile->local.bPending = FALSE;
30190       pFile->shared->bPending = FALSE;
30191       bReturn = TRUE;
30192     }
30193   }
30194   /* Releasing a reserved lock */
30195   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
30196     if (pFile->local.bReserved) {
30197       pFile->local.bReserved = FALSE;
30198       pFile->shared->bReserved = FALSE;
30199       bReturn = TRUE;
30200     }
30201   }
30202
30203   winceMutexRelease(pFile->hMutex);
30204   return bReturn;
30205 }
30206
30207 /*
30208 ** An implementation of the LockFileEx() API of windows for wince
30209 */
30210 static BOOL winceLockFileEx(
30211   HANDLE *phFile,
30212   DWORD dwFlags,
30213   DWORD dwReserved,
30214   DWORD nNumberOfBytesToLockLow,
30215   DWORD nNumberOfBytesToLockHigh,
30216   LPOVERLAPPED lpOverlapped
30217 ){
30218   UNUSED_PARAMETER(dwReserved);
30219   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
30220
30221   /* If the caller wants a shared read lock, forward this call
30222   ** to winceLockFile */
30223   if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
30224       dwFlags == 1 &&
30225       nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
30226     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
30227   }
30228   return FALSE;
30229 }
30230 /*
30231 ** End of the special code for wince
30232 *****************************************************************************/
30233 #endif /* SQLITE_OS_WINCE */
30234
30235 /*****************************************************************************
30236 ** The next group of routines implement the I/O methods specified
30237 ** by the sqlite3_io_methods object.
30238 ******************************************************************************/
30239
30240 /*
30241 ** Some microsoft compilers lack this definition.
30242 */
30243 #ifndef INVALID_SET_FILE_POINTER
30244 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
30245 #endif
30246
30247 /*
30248 ** Move the current position of the file handle passed as the first 
30249 ** argument to offset iOffset within the file. If successful, return 0. 
30250 ** Otherwise, set pFile->lastErrno and return non-zero.
30251 */
30252 static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
30253   LONG upperBits;                 /* Most sig. 32 bits of new offset */
30254   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
30255   DWORD dwRet;                    /* Value returned by SetFilePointer() */
30256
30257   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
30258   lowerBits = (LONG)(iOffset & 0xffffffff);
30259
30260   /* API oddity: If successful, SetFilePointer() returns a dword 
30261   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
30262   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN, 
30263   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine 
30264   ** whether an error has actually occured, it is also necessary to call 
30265   ** GetLastError().
30266   */
30267   dwRet = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
30268   if( (dwRet==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR) ){
30269     pFile->lastErrno = GetLastError();
30270     return 1;
30271   }
30272
30273   return 0;
30274 }
30275
30276 /*
30277 ** Close a file.
30278 **
30279 ** It is reported that an attempt to close a handle might sometimes
30280 ** fail.  This is a very unreasonable result, but windows is notorious
30281 ** for being unreasonable so I do not doubt that it might happen.  If
30282 ** the close fails, we pause for 100 milliseconds and try again.  As
30283 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
30284 ** giving up and returning an error.
30285 */
30286 #define MX_CLOSE_ATTEMPT 3
30287 static int winClose(sqlite3_file *id){
30288   int rc, cnt = 0;
30289   winFile *pFile = (winFile*)id;
30290
30291   assert( id!=0 );
30292   assert( pFile->pShm==0 );
30293   OSTRACE(("CLOSE %d\n", pFile->h));
30294   do{
30295     rc = CloseHandle(pFile->h);
30296     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
30297   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
30298 #if SQLITE_OS_WINCE
30299 #define WINCE_DELETION_ATTEMPTS 3
30300   winceDestroyLock(pFile);
30301   if( pFile->zDeleteOnClose ){
30302     int cnt = 0;
30303     while(
30304            DeleteFileW(pFile->zDeleteOnClose)==0
30305         && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
30306         && cnt++ < WINCE_DELETION_ATTEMPTS
30307     ){
30308        Sleep(100);  /* Wait a little before trying again */
30309     }
30310     free(pFile->zDeleteOnClose);
30311   }
30312 #endif
30313   OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
30314   OpenCounter(-1);
30315   return rc ? SQLITE_OK : SQLITE_IOERR;
30316 }
30317
30318 /*
30319 ** Read data from a file into a buffer.  Return SQLITE_OK if all
30320 ** bytes were read successfully and SQLITE_IOERR if anything goes
30321 ** wrong.
30322 */
30323 static int winRead(
30324   sqlite3_file *id,          /* File to read from */
30325   void *pBuf,                /* Write content into this buffer */
30326   int amt,                   /* Number of bytes to read */
30327   sqlite3_int64 offset       /* Begin reading at this offset */
30328 ){
30329   winFile *pFile = (winFile*)id;  /* file handle */
30330   DWORD nRead;                    /* Number of bytes actually read from file */
30331
30332   assert( id!=0 );
30333   SimulateIOError(return SQLITE_IOERR_READ);
30334   OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
30335
30336   if( seekWinFile(pFile, offset) ){
30337     return SQLITE_FULL;
30338   }
30339   if( !ReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
30340     pFile->lastErrno = GetLastError();
30341     return SQLITE_IOERR_READ;
30342   }
30343   if( nRead<(DWORD)amt ){
30344     /* Unread parts of the buffer must be zero-filled */
30345     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
30346     return SQLITE_IOERR_SHORT_READ;
30347   }
30348
30349   return SQLITE_OK;
30350 }
30351
30352 /*
30353 ** Write data from a buffer into a file.  Return SQLITE_OK on success
30354 ** or some other error code on failure.
30355 */
30356 static int winWrite(
30357   sqlite3_file *id,               /* File to write into */
30358   const void *pBuf,               /* The bytes to be written */
30359   int amt,                        /* Number of bytes to write */
30360   sqlite3_int64 offset            /* Offset into the file to begin writing at */
30361 ){
30362   int rc;                         /* True if error has occured, else false */
30363   winFile *pFile = (winFile*)id;  /* File handle */
30364
30365   assert( amt>0 );
30366   assert( pFile );
30367   SimulateIOError(return SQLITE_IOERR_WRITE);
30368   SimulateDiskfullError(return SQLITE_FULL);
30369
30370   OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
30371
30372   rc = seekWinFile(pFile, offset);
30373   if( rc==0 ){
30374     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
30375     int nRem = amt;               /* Number of bytes yet to be written */
30376     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
30377
30378     while( nRem>0 && WriteFile(pFile->h, aRem, nRem, &nWrite, 0) && nWrite>0 ){
30379       aRem += nWrite;
30380       nRem -= nWrite;
30381     }
30382     if( nRem>0 ){
30383       pFile->lastErrno = GetLastError();
30384       rc = 1;
30385     }
30386   }
30387
30388   if( rc ){
30389     if( pFile->lastErrno==ERROR_HANDLE_DISK_FULL ){
30390       return SQLITE_FULL;
30391     }
30392     return SQLITE_IOERR_WRITE;
30393   }
30394   return SQLITE_OK;
30395 }
30396
30397 /*
30398 ** Truncate an open file to a specified size
30399 */
30400 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
30401   winFile *pFile = (winFile*)id;  /* File handle object */
30402   int rc = SQLITE_OK;             /* Return code for this function */
30403
30404   assert( pFile );
30405
30406   OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
30407   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
30408
30409   /* If the user has configured a chunk-size for this file, truncate the
30410   ** file so that it consists of an integer number of chunks (i.e. the
30411   ** actual file size after the operation may be larger than the requested
30412   ** size).
30413   */
30414   if( pFile->szChunk ){
30415     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
30416   }
30417
30418   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
30419   if( seekWinFile(pFile, nByte) ){
30420     rc = SQLITE_IOERR_TRUNCATE;
30421   }else if( 0==SetEndOfFile(pFile->h) ){
30422     pFile->lastErrno = GetLastError();
30423     rc = SQLITE_IOERR_TRUNCATE;
30424   }
30425
30426   OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
30427   return rc;
30428 }
30429
30430 #ifdef SQLITE_TEST
30431 /*
30432 ** Count the number of fullsyncs and normal syncs.  This is used to test
30433 ** that syncs and fullsyncs are occuring at the right times.
30434 */
30435 SQLITE_API int sqlite3_sync_count = 0;
30436 SQLITE_API int sqlite3_fullsync_count = 0;
30437 #endif
30438
30439 /*
30440 ** Make sure all writes to a particular file are committed to disk.
30441 */
30442 static int winSync(sqlite3_file *id, int flags){
30443 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || defined(SQLITE_DEBUG)
30444   winFile *pFile = (winFile*)id;
30445 #else
30446   UNUSED_PARAMETER(id);
30447 #endif
30448
30449   assert( pFile );
30450   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
30451   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
30452       || (flags&0x0F)==SQLITE_SYNC_FULL
30453   );
30454
30455   OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
30456
30457 #ifndef SQLITE_TEST
30458   UNUSED_PARAMETER(flags);
30459 #else
30460   if( flags & SQLITE_SYNC_FULL ){
30461     sqlite3_fullsync_count++;
30462   }
30463   sqlite3_sync_count++;
30464 #endif
30465
30466   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
30467   ** line is to test that doing so does not cause any problems.
30468   */
30469   SimulateDiskfullError( return SQLITE_FULL );
30470   SimulateIOError( return SQLITE_IOERR; );
30471
30472   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
30473   ** no-op
30474   */
30475 #ifdef SQLITE_NO_SYNC
30476   return SQLITE_OK;
30477 #else
30478   if( FlushFileBuffers(pFile->h) ){
30479     return SQLITE_OK;
30480   }else{
30481     pFile->lastErrno = GetLastError();
30482     return SQLITE_IOERR;
30483   }
30484 #endif
30485 }
30486
30487 /*
30488 ** Determine the current size of a file in bytes
30489 */
30490 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
30491   DWORD upperBits;
30492   DWORD lowerBits;
30493   winFile *pFile = (winFile*)id;
30494   DWORD error;
30495
30496   assert( id!=0 );
30497   SimulateIOError(return SQLITE_IOERR_FSTAT);
30498   lowerBits = GetFileSize(pFile->h, &upperBits);
30499   if(   (lowerBits == INVALID_FILE_SIZE)
30500      && ((error = GetLastError()) != NO_ERROR) )
30501   {
30502     pFile->lastErrno = error;
30503     return SQLITE_IOERR_FSTAT;
30504   }
30505   *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
30506   return SQLITE_OK;
30507 }
30508
30509 /*
30510 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
30511 */
30512 #ifndef LOCKFILE_FAIL_IMMEDIATELY
30513 # define LOCKFILE_FAIL_IMMEDIATELY 1
30514 #endif
30515
30516 /*
30517 ** Acquire a reader lock.
30518 ** Different API routines are called depending on whether or not this
30519 ** is Win95 or WinNT.
30520 */
30521 static int getReadLock(winFile *pFile){
30522   int res;
30523   if( isNT() ){
30524     OVERLAPPED ovlp;
30525     ovlp.Offset = SHARED_FIRST;
30526     ovlp.OffsetHigh = 0;
30527     ovlp.hEvent = 0;
30528     res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
30529                      0, SHARED_SIZE, 0, &ovlp);
30530 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
30531 */
30532 #if SQLITE_OS_WINCE==0
30533   }else{
30534     int lk;
30535     sqlite3_randomness(sizeof(lk), &lk);
30536     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
30537     res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
30538 #endif
30539   }
30540   if( res == 0 ){
30541     pFile->lastErrno = GetLastError();
30542   }
30543   return res;
30544 }
30545
30546 /*
30547 ** Undo a readlock
30548 */
30549 static int unlockReadLock(winFile *pFile){
30550   int res;
30551   if( isNT() ){
30552     res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
30553 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
30554 */
30555 #if SQLITE_OS_WINCE==0
30556   }else{
30557     res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
30558 #endif
30559   }
30560   if( res == 0 ){
30561     pFile->lastErrno = GetLastError();
30562   }
30563   return res;
30564 }
30565
30566 /*
30567 ** Lock the file with the lock specified by parameter locktype - one
30568 ** of the following:
30569 **
30570 **     (1) SHARED_LOCK
30571 **     (2) RESERVED_LOCK
30572 **     (3) PENDING_LOCK
30573 **     (4) EXCLUSIVE_LOCK
30574 **
30575 ** Sometimes when requesting one lock state, additional lock states
30576 ** are inserted in between.  The locking might fail on one of the later
30577 ** transitions leaving the lock state different from what it started but
30578 ** still short of its goal.  The following chart shows the allowed
30579 ** transitions and the inserted intermediate states:
30580 **
30581 **    UNLOCKED -> SHARED
30582 **    SHARED -> RESERVED
30583 **    SHARED -> (PENDING) -> EXCLUSIVE
30584 **    RESERVED -> (PENDING) -> EXCLUSIVE
30585 **    PENDING -> EXCLUSIVE
30586 **
30587 ** This routine will only increase a lock.  The winUnlock() routine
30588 ** erases all locks at once and returns us immediately to locking level 0.
30589 ** It is not possible to lower the locking level one step at a time.  You
30590 ** must go straight to locking level 0.
30591 */
30592 static int winLock(sqlite3_file *id, int locktype){
30593   int rc = SQLITE_OK;    /* Return code from subroutines */
30594   int res = 1;           /* Result of a windows lock call */
30595   int newLocktype;       /* Set pFile->locktype to this value before exiting */
30596   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
30597   winFile *pFile = (winFile*)id;
30598   DWORD error = NO_ERROR;
30599
30600   assert( id!=0 );
30601   OSTRACE(("LOCK %d %d was %d(%d)\n",
30602            pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
30603
30604   /* If there is already a lock of this type or more restrictive on the
30605   ** OsFile, do nothing. Don't use the end_lock: exit path, as
30606   ** sqlite3OsEnterMutex() hasn't been called yet.
30607   */
30608   if( pFile->locktype>=locktype ){
30609     return SQLITE_OK;
30610   }
30611
30612   /* Make sure the locking sequence is correct
30613   */
30614   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
30615   assert( locktype!=PENDING_LOCK );
30616   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
30617
30618   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
30619   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
30620   ** the PENDING_LOCK byte is temporary.
30621   */
30622   newLocktype = pFile->locktype;
30623   if(   (pFile->locktype==NO_LOCK)
30624      || (   (locktype==EXCLUSIVE_LOCK)
30625          && (pFile->locktype==RESERVED_LOCK))
30626   ){
30627     int cnt = 3;
30628     while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
30629       /* Try 3 times to get the pending lock.  The pending lock might be
30630       ** held by another reader process who will release it momentarily.
30631       */
30632       OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
30633       Sleep(1);
30634     }
30635     gotPendingLock = res;
30636     if( !res ){
30637       error = GetLastError();
30638     }
30639   }
30640
30641   /* Acquire a shared lock
30642   */
30643   if( locktype==SHARED_LOCK && res ){
30644     assert( pFile->locktype==NO_LOCK );
30645     res = getReadLock(pFile);
30646     if( res ){
30647       newLocktype = SHARED_LOCK;
30648     }else{
30649       error = GetLastError();
30650     }
30651   }
30652
30653   /* Acquire a RESERVED lock
30654   */
30655   if( locktype==RESERVED_LOCK && res ){
30656     assert( pFile->locktype==SHARED_LOCK );
30657     res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
30658     if( res ){
30659       newLocktype = RESERVED_LOCK;
30660     }else{
30661       error = GetLastError();
30662     }
30663   }
30664
30665   /* Acquire a PENDING lock
30666   */
30667   if( locktype==EXCLUSIVE_LOCK && res ){
30668     newLocktype = PENDING_LOCK;
30669     gotPendingLock = 0;
30670   }
30671
30672   /* Acquire an EXCLUSIVE lock
30673   */
30674   if( locktype==EXCLUSIVE_LOCK && res ){
30675     assert( pFile->locktype>=SHARED_LOCK );
30676     res = unlockReadLock(pFile);
30677     OSTRACE(("unreadlock = %d\n", res));
30678     res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
30679     if( res ){
30680       newLocktype = EXCLUSIVE_LOCK;
30681     }else{
30682       error = GetLastError();
30683       OSTRACE(("error-code = %d\n", error));
30684       getReadLock(pFile);
30685     }
30686   }
30687
30688   /* If we are holding a PENDING lock that ought to be released, then
30689   ** release it now.
30690   */
30691   if( gotPendingLock && locktype==SHARED_LOCK ){
30692     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
30693   }
30694
30695   /* Update the state of the lock has held in the file descriptor then
30696   ** return the appropriate result code.
30697   */
30698   if( res ){
30699     rc = SQLITE_OK;
30700   }else{
30701     OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
30702            locktype, newLocktype));
30703     pFile->lastErrno = error;
30704     rc = SQLITE_BUSY;
30705   }
30706   pFile->locktype = (u8)newLocktype;
30707   return rc;
30708 }
30709
30710 /*
30711 ** This routine checks if there is a RESERVED lock held on the specified
30712 ** file by this or any other process. If such a lock is held, return
30713 ** non-zero, otherwise zero.
30714 */
30715 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
30716   int rc;
30717   winFile *pFile = (winFile*)id;
30718
30719   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
30720
30721   assert( id!=0 );
30722   if( pFile->locktype>=RESERVED_LOCK ){
30723     rc = 1;
30724     OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
30725   }else{
30726     rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
30727     if( rc ){
30728       UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
30729     }
30730     rc = !rc;
30731     OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
30732   }
30733   *pResOut = rc;
30734   return SQLITE_OK;
30735 }
30736
30737 /*
30738 ** Lower the locking level on file descriptor id to locktype.  locktype
30739 ** must be either NO_LOCK or SHARED_LOCK.
30740 **
30741 ** If the locking level of the file descriptor is already at or below
30742 ** the requested locking level, this routine is a no-op.
30743 **
30744 ** It is not possible for this routine to fail if the second argument
30745 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
30746 ** might return SQLITE_IOERR;
30747 */
30748 static int winUnlock(sqlite3_file *id, int locktype){
30749   int type;
30750   winFile *pFile = (winFile*)id;
30751   int rc = SQLITE_OK;
30752   assert( pFile!=0 );
30753   assert( locktype<=SHARED_LOCK );
30754   OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
30755           pFile->locktype, pFile->sharedLockByte));
30756   type = pFile->locktype;
30757   if( type>=EXCLUSIVE_LOCK ){
30758     UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
30759     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
30760       /* This should never happen.  We should always be able to
30761       ** reacquire the read lock */
30762       rc = SQLITE_IOERR_UNLOCK;
30763     }
30764   }
30765   if( type>=RESERVED_LOCK ){
30766     UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
30767   }
30768   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
30769     unlockReadLock(pFile);
30770   }
30771   if( type>=PENDING_LOCK ){
30772     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
30773   }
30774   pFile->locktype = (u8)locktype;
30775   return rc;
30776 }
30777
30778 /*
30779 ** Control and query of the open file handle.
30780 */
30781 static int winFileControl(sqlite3_file *id, int op, void *pArg){
30782   switch( op ){
30783     case SQLITE_FCNTL_LOCKSTATE: {
30784       *(int*)pArg = ((winFile*)id)->locktype;
30785       return SQLITE_OK;
30786     }
30787     case SQLITE_LAST_ERRNO: {
30788       *(int*)pArg = (int)((winFile*)id)->lastErrno;
30789       return SQLITE_OK;
30790     }
30791     case SQLITE_FCNTL_CHUNK_SIZE: {
30792       ((winFile*)id)->szChunk = *(int *)pArg;
30793       return SQLITE_OK;
30794     }
30795     case SQLITE_FCNTL_SIZE_HINT: {
30796       sqlite3_int64 sz = *(sqlite3_int64*)pArg;
30797       SimulateIOErrorBenign(1);
30798       winTruncate(id, sz);
30799       SimulateIOErrorBenign(0);
30800       return SQLITE_OK;
30801     }
30802     case SQLITE_FCNTL_SYNC_OMITTED: {
30803       return SQLITE_OK;
30804     }
30805   }
30806   return SQLITE_NOTFOUND;
30807 }
30808
30809 /*
30810 ** Return the sector size in bytes of the underlying block device for
30811 ** the specified file. This is almost always 512 bytes, but may be
30812 ** larger for some devices.
30813 **
30814 ** SQLite code assumes this function cannot fail. It also assumes that
30815 ** if two files are created in the same file-system directory (i.e.
30816 ** a database and its journal file) that the sector size will be the
30817 ** same for both.
30818 */
30819 static int winSectorSize(sqlite3_file *id){
30820   assert( id!=0 );
30821   return (int)(((winFile*)id)->sectorSize);
30822 }
30823
30824 /*
30825 ** Return a vector of device characteristics.
30826 */
30827 static int winDeviceCharacteristics(sqlite3_file *id){
30828   UNUSED_PARAMETER(id);
30829   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
30830 }
30831
30832 #ifndef SQLITE_OMIT_WAL
30833
30834 /* 
30835 ** Windows will only let you create file view mappings
30836 ** on allocation size granularity boundaries.
30837 ** During sqlite3_os_init() we do a GetSystemInfo()
30838 ** to get the granularity size.
30839 */
30840 SYSTEM_INFO winSysInfo;
30841
30842 /*
30843 ** Helper functions to obtain and relinquish the global mutex. The
30844 ** global mutex is used to protect the winLockInfo objects used by 
30845 ** this file, all of which may be shared by multiple threads.
30846 **
30847 ** Function winShmMutexHeld() is used to assert() that the global mutex 
30848 ** is held when required. This function is only used as part of assert() 
30849 ** statements. e.g.
30850 **
30851 **   winShmEnterMutex()
30852 **     assert( winShmMutexHeld() );
30853 **   winShmLeaveMutex()
30854 */
30855 static void winShmEnterMutex(void){
30856   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
30857 }
30858 static void winShmLeaveMutex(void){
30859   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
30860 }
30861 #ifdef SQLITE_DEBUG
30862 static int winShmMutexHeld(void) {
30863   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
30864 }
30865 #endif
30866
30867 /*
30868 ** Object used to represent a single file opened and mmapped to provide
30869 ** shared memory.  When multiple threads all reference the same
30870 ** log-summary, each thread has its own winFile object, but they all
30871 ** point to a single instance of this object.  In other words, each
30872 ** log-summary is opened only once per process.
30873 **
30874 ** winShmMutexHeld() must be true when creating or destroying
30875 ** this object or while reading or writing the following fields:
30876 **
30877 **      nRef
30878 **      pNext 
30879 **
30880 ** The following fields are read-only after the object is created:
30881 ** 
30882 **      fid
30883 **      zFilename
30884 **
30885 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
30886 ** winShmMutexHeld() is true when reading or writing any other field
30887 ** in this structure.
30888 **
30889 */
30890 struct winShmNode {
30891   sqlite3_mutex *mutex;      /* Mutex to access this object */
30892   char *zFilename;           /* Name of the file */
30893   winFile hFile;             /* File handle from winOpen */
30894
30895   int szRegion;              /* Size of shared-memory regions */
30896   int nRegion;               /* Size of array apRegion */
30897   struct ShmRegion {
30898     HANDLE hMap;             /* File handle from CreateFileMapping */
30899     void *pMap;
30900   } *aRegion;
30901   DWORD lastErrno;           /* The Windows errno from the last I/O error */
30902
30903   int nRef;                  /* Number of winShm objects pointing to this */
30904   winShm *pFirst;            /* All winShm objects pointing to this */
30905   winShmNode *pNext;         /* Next in list of all winShmNode objects */
30906 #ifdef SQLITE_DEBUG
30907   u8 nextShmId;              /* Next available winShm.id value */
30908 #endif
30909 };
30910
30911 /*
30912 ** A global array of all winShmNode objects.
30913 **
30914 ** The winShmMutexHeld() must be true while reading or writing this list.
30915 */
30916 static winShmNode *winShmNodeList = 0;
30917
30918 /*
30919 ** Structure used internally by this VFS to record the state of an
30920 ** open shared memory connection.
30921 **
30922 ** The following fields are initialized when this object is created and
30923 ** are read-only thereafter:
30924 **
30925 **    winShm.pShmNode
30926 **    winShm.id
30927 **
30928 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
30929 ** while accessing any read/write fields.
30930 */
30931 struct winShm {
30932   winShmNode *pShmNode;      /* The underlying winShmNode object */
30933   winShm *pNext;             /* Next winShm with the same winShmNode */
30934   u8 hasMutex;               /* True if holding the winShmNode mutex */
30935   u16 sharedMask;            /* Mask of shared locks held */
30936   u16 exclMask;              /* Mask of exclusive locks held */
30937 #ifdef SQLITE_DEBUG
30938   u8 id;                     /* Id of this connection with its winShmNode */
30939 #endif
30940 };
30941
30942 /*
30943 ** Constants used for locking
30944 */
30945 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
30946 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
30947
30948 /*
30949 ** Apply advisory locks for all n bytes beginning at ofst.
30950 */
30951 #define _SHM_UNLCK  1
30952 #define _SHM_RDLCK  2
30953 #define _SHM_WRLCK  3
30954 static int winShmSystemLock(
30955   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
30956   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
30957   int ofst,             /* Offset to first byte to be locked/unlocked */
30958   int nByte             /* Number of bytes to lock or unlock */
30959 ){
30960   OVERLAPPED ovlp;
30961   DWORD dwFlags;
30962   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
30963
30964   /* Access to the winShmNode object is serialized by the caller */
30965   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
30966
30967   /* Initialize the locking parameters */
30968   dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
30969   if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
30970
30971   memset(&ovlp, 0, sizeof(OVERLAPPED));
30972   ovlp.Offset = ofst;
30973
30974   /* Release/Acquire the system-level lock */
30975   if( lockType==_SHM_UNLCK ){
30976     rc = UnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
30977   }else{
30978     rc = LockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
30979   }
30980   
30981   if( rc!= 0 ){
30982     rc = SQLITE_OK;
30983   }else{
30984     pFile->lastErrno =  GetLastError();
30985     rc = SQLITE_BUSY;
30986   }
30987
30988   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n", 
30989            pFile->hFile.h,
30990            rc==SQLITE_OK ? "ok" : "failed",
30991            lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
30992            pFile->lastErrno));
30993
30994   return rc;
30995 }
30996
30997 /* Forward references to VFS methods */
30998 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
30999 static int winDelete(sqlite3_vfs *,const char*,int);
31000
31001 /*
31002 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
31003 **
31004 ** This is not a VFS shared-memory method; it is a utility function called
31005 ** by VFS shared-memory methods.
31006 */
31007 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
31008   winShmNode **pp;
31009   winShmNode *p;
31010   BOOL bRc;
31011   assert( winShmMutexHeld() );
31012   pp = &winShmNodeList;
31013   while( (p = *pp)!=0 ){
31014     if( p->nRef==0 ){
31015       int i;
31016       if( p->mutex ) sqlite3_mutex_free(p->mutex);
31017       for(i=0; i<p->nRegion; i++){
31018         bRc = UnmapViewOfFile(p->aRegion[i].pMap);
31019         OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
31020                  (int)GetCurrentProcessId(), i,
31021                  bRc ? "ok" : "failed"));
31022         bRc = CloseHandle(p->aRegion[i].hMap);
31023         OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
31024                  (int)GetCurrentProcessId(), i,
31025                  bRc ? "ok" : "failed"));
31026       }
31027       if( p->hFile.h != INVALID_HANDLE_VALUE ){
31028         SimulateIOErrorBenign(1);
31029         winClose((sqlite3_file *)&p->hFile);
31030         SimulateIOErrorBenign(0);
31031       }
31032       if( deleteFlag ){
31033         SimulateIOErrorBenign(1);
31034         winDelete(pVfs, p->zFilename, 0);
31035         SimulateIOErrorBenign(0);
31036       }
31037       *pp = p->pNext;
31038       sqlite3_free(p->aRegion);
31039       sqlite3_free(p);
31040     }else{
31041       pp = &p->pNext;
31042     }
31043   }
31044 }
31045
31046 /*
31047 ** Open the shared-memory area associated with database file pDbFd.
31048 **
31049 ** When opening a new shared-memory file, if no other instances of that
31050 ** file are currently open, in this process or in other processes, then
31051 ** the file must be truncated to zero length or have its header cleared.
31052 */
31053 static int winOpenSharedMemory(winFile *pDbFd){
31054   struct winShm *p;                  /* The connection to be opened */
31055   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
31056   int rc;                            /* Result code */
31057   struct winShmNode *pNew;           /* Newly allocated winShmNode */
31058   int nName;                         /* Size of zName in bytes */
31059
31060   assert( pDbFd->pShm==0 );    /* Not previously opened */
31061
31062   /* Allocate space for the new sqlite3_shm object.  Also speculatively
31063   ** allocate space for a new winShmNode and filename.
31064   */
31065   p = sqlite3_malloc( sizeof(*p) );
31066   if( p==0 ) return SQLITE_NOMEM;
31067   memset(p, 0, sizeof(*p));
31068   nName = sqlite3Strlen30(pDbFd->zPath);
31069   pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 15 );
31070   if( pNew==0 ){
31071     sqlite3_free(p);
31072     return SQLITE_NOMEM;
31073   }
31074   memset(pNew, 0, sizeof(*pNew));
31075   pNew->zFilename = (char*)&pNew[1];
31076   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
31077
31078   /* Look to see if there is an existing winShmNode that can be used.
31079   ** If no matching winShmNode currently exists, create a new one.
31080   */
31081   winShmEnterMutex();
31082   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
31083     /* TBD need to come up with better match here.  Perhaps
31084     ** use FILE_ID_BOTH_DIR_INFO Structure.
31085     */
31086     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
31087   }
31088   if( pShmNode ){
31089     sqlite3_free(pNew);
31090   }else{
31091     pShmNode = pNew;
31092     pNew = 0;
31093     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
31094     pShmNode->pNext = winShmNodeList;
31095     winShmNodeList = pShmNode;
31096
31097     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
31098     if( pShmNode->mutex==0 ){
31099       rc = SQLITE_NOMEM;
31100       goto shm_open_err;
31101     }
31102
31103     rc = winOpen(pDbFd->pVfs,
31104                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
31105                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
31106                  SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
31107                  0);
31108     if( SQLITE_OK!=rc ){
31109       rc = SQLITE_CANTOPEN_BKPT;
31110       goto shm_open_err;
31111     }
31112
31113     /* Check to see if another process is holding the dead-man switch.
31114     ** If not, truncate the file to zero length. 
31115     */
31116     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
31117       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
31118       if( rc!=SQLITE_OK ){
31119         rc = SQLITE_IOERR_SHMOPEN;
31120       }
31121     }
31122     if( rc==SQLITE_OK ){
31123       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
31124       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
31125     }
31126     if( rc ) goto shm_open_err;
31127   }
31128
31129   /* Make the new connection a child of the winShmNode */
31130   p->pShmNode = pShmNode;
31131 #ifdef SQLITE_DEBUG
31132   p->id = pShmNode->nextShmId++;
31133 #endif
31134   pShmNode->nRef++;
31135   pDbFd->pShm = p;
31136   winShmLeaveMutex();
31137
31138   /* The reference count on pShmNode has already been incremented under
31139   ** the cover of the winShmEnterMutex() mutex and the pointer from the
31140   ** new (struct winShm) object to the pShmNode has been set. All that is
31141   ** left to do is to link the new object into the linked list starting
31142   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
31143   ** mutex.
31144   */
31145   sqlite3_mutex_enter(pShmNode->mutex);
31146   p->pNext = pShmNode->pFirst;
31147   pShmNode->pFirst = p;
31148   sqlite3_mutex_leave(pShmNode->mutex);
31149   return SQLITE_OK;
31150
31151   /* Jump here on any error */
31152 shm_open_err:
31153   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
31154   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
31155   sqlite3_free(p);
31156   sqlite3_free(pNew);
31157   winShmLeaveMutex();
31158   return rc;
31159 }
31160
31161 /*
31162 ** Close a connection to shared-memory.  Delete the underlying 
31163 ** storage if deleteFlag is true.
31164 */
31165 static int winShmUnmap(
31166   sqlite3_file *fd,          /* Database holding shared memory */
31167   int deleteFlag             /* Delete after closing if true */
31168 ){
31169   winFile *pDbFd;       /* Database holding shared-memory */
31170   winShm *p;            /* The connection to be closed */
31171   winShmNode *pShmNode; /* The underlying shared-memory file */
31172   winShm **pp;          /* For looping over sibling connections */
31173
31174   pDbFd = (winFile*)fd;
31175   p = pDbFd->pShm;
31176   if( p==0 ) return SQLITE_OK;
31177   pShmNode = p->pShmNode;
31178
31179   /* Remove connection p from the set of connections associated
31180   ** with pShmNode */
31181   sqlite3_mutex_enter(pShmNode->mutex);
31182   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
31183   *pp = p->pNext;
31184
31185   /* Free the connection p */
31186   sqlite3_free(p);
31187   pDbFd->pShm = 0;
31188   sqlite3_mutex_leave(pShmNode->mutex);
31189
31190   /* If pShmNode->nRef has reached 0, then close the underlying
31191   ** shared-memory file, too */
31192   winShmEnterMutex();
31193   assert( pShmNode->nRef>0 );
31194   pShmNode->nRef--;
31195   if( pShmNode->nRef==0 ){
31196     winShmPurge(pDbFd->pVfs, deleteFlag);
31197   }
31198   winShmLeaveMutex();
31199
31200   return SQLITE_OK;
31201 }
31202
31203 /*
31204 ** Change the lock state for a shared-memory segment.
31205 */
31206 static int winShmLock(
31207   sqlite3_file *fd,          /* Database file holding the shared memory */
31208   int ofst,                  /* First lock to acquire or release */
31209   int n,                     /* Number of locks to acquire or release */
31210   int flags                  /* What to do with the lock */
31211 ){
31212   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
31213   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
31214   winShm *pX;                           /* For looping over all siblings */
31215   winShmNode *pShmNode = p->pShmNode;
31216   int rc = SQLITE_OK;                   /* Result code */
31217   u16 mask;                             /* Mask of locks to take or release */
31218
31219   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
31220   assert( n>=1 );
31221   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
31222        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
31223        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
31224        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
31225   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
31226
31227   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
31228   assert( n>1 || mask==(1<<ofst) );
31229   sqlite3_mutex_enter(pShmNode->mutex);
31230   if( flags & SQLITE_SHM_UNLOCK ){
31231     u16 allMask = 0; /* Mask of locks held by siblings */
31232
31233     /* See if any siblings hold this same lock */
31234     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
31235       if( pX==p ) continue;
31236       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
31237       allMask |= pX->sharedMask;
31238     }
31239
31240     /* Unlock the system-level locks */
31241     if( (mask & allMask)==0 ){
31242       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
31243     }else{
31244       rc = SQLITE_OK;
31245     }
31246
31247     /* Undo the local locks */
31248     if( rc==SQLITE_OK ){
31249       p->exclMask &= ~mask;
31250       p->sharedMask &= ~mask;
31251     } 
31252   }else if( flags & SQLITE_SHM_SHARED ){
31253     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
31254
31255     /* Find out which shared locks are already held by sibling connections.
31256     ** If any sibling already holds an exclusive lock, go ahead and return
31257     ** SQLITE_BUSY.
31258     */
31259     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
31260       if( (pX->exclMask & mask)!=0 ){
31261         rc = SQLITE_BUSY;
31262         break;
31263       }
31264       allShared |= pX->sharedMask;
31265     }
31266
31267     /* Get shared locks at the system level, if necessary */
31268     if( rc==SQLITE_OK ){
31269       if( (allShared & mask)==0 ){
31270         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
31271       }else{
31272         rc = SQLITE_OK;
31273       }
31274     }
31275
31276     /* Get the local shared locks */
31277     if( rc==SQLITE_OK ){
31278       p->sharedMask |= mask;
31279     }
31280   }else{
31281     /* Make sure no sibling connections hold locks that will block this
31282     ** lock.  If any do, return SQLITE_BUSY right away.
31283     */
31284     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
31285       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
31286         rc = SQLITE_BUSY;
31287         break;
31288       }
31289     }
31290   
31291     /* Get the exclusive locks at the system level.  Then if successful
31292     ** also mark the local connection as being locked.
31293     */
31294     if( rc==SQLITE_OK ){
31295       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
31296       if( rc==SQLITE_OK ){
31297         assert( (p->sharedMask & mask)==0 );
31298         p->exclMask |= mask;
31299       }
31300     }
31301   }
31302   sqlite3_mutex_leave(pShmNode->mutex);
31303   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
31304            p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
31305            rc ? "failed" : "ok"));
31306   return rc;
31307 }
31308
31309 /*
31310 ** Implement a memory barrier or memory fence on shared memory.  
31311 **
31312 ** All loads and stores begun before the barrier must complete before
31313 ** any load or store begun after the barrier.
31314 */
31315 static void winShmBarrier(
31316   sqlite3_file *fd          /* Database holding the shared memory */
31317 ){
31318   UNUSED_PARAMETER(fd);
31319   /* MemoryBarrier(); // does not work -- do not know why not */
31320   winShmEnterMutex();
31321   winShmLeaveMutex();
31322 }
31323
31324 /*
31325 ** This function is called to obtain a pointer to region iRegion of the 
31326 ** shared-memory associated with the database file fd. Shared-memory regions 
31327 ** are numbered starting from zero. Each shared-memory region is szRegion 
31328 ** bytes in size.
31329 **
31330 ** If an error occurs, an error code is returned and *pp is set to NULL.
31331 **
31332 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
31333 ** region has not been allocated (by any client, including one running in a
31334 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
31335 ** isWrite is non-zero and the requested shared-memory region has not yet 
31336 ** been allocated, it is allocated by this function.
31337 **
31338 ** If the shared-memory region has already been allocated or is allocated by
31339 ** this call as described above, then it is mapped into this processes 
31340 ** address space (if it is not already), *pp is set to point to the mapped 
31341 ** memory and SQLITE_OK returned.
31342 */
31343 static int winShmMap(
31344   sqlite3_file *fd,               /* Handle open on database file */
31345   int iRegion,                    /* Region to retrieve */
31346   int szRegion,                   /* Size of regions */
31347   int isWrite,                    /* True to extend file if necessary */
31348   void volatile **pp              /* OUT: Mapped memory */
31349 ){
31350   winFile *pDbFd = (winFile*)fd;
31351   winShm *p = pDbFd->pShm;
31352   winShmNode *pShmNode;
31353   int rc = SQLITE_OK;
31354
31355   if( !p ){
31356     rc = winOpenSharedMemory(pDbFd);
31357     if( rc!=SQLITE_OK ) return rc;
31358     p = pDbFd->pShm;
31359   }
31360   pShmNode = p->pShmNode;
31361
31362   sqlite3_mutex_enter(pShmNode->mutex);
31363   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
31364
31365   if( pShmNode->nRegion<=iRegion ){
31366     struct ShmRegion *apNew;           /* New aRegion[] array */
31367     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
31368     sqlite3_int64 sz;                  /* Current size of wal-index file */
31369
31370     pShmNode->szRegion = szRegion;
31371
31372     /* The requested region is not mapped into this processes address space.
31373     ** Check to see if it has been allocated (i.e. if the wal-index file is
31374     ** large enough to contain the requested region).
31375     */
31376     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
31377     if( rc!=SQLITE_OK ){
31378       rc = SQLITE_IOERR_SHMSIZE;
31379       goto shmpage_out;
31380     }
31381
31382     if( sz<nByte ){
31383       /* The requested memory region does not exist. If isWrite is set to
31384       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
31385       **
31386       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
31387       ** the requested memory region.
31388       */
31389       if( !isWrite ) goto shmpage_out;
31390       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
31391       if( rc!=SQLITE_OK ){
31392         rc = SQLITE_IOERR_SHMSIZE;
31393         goto shmpage_out;
31394       }
31395     }
31396
31397     /* Map the requested memory region into this processes address space. */
31398     apNew = (struct ShmRegion *)sqlite3_realloc(
31399         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
31400     );
31401     if( !apNew ){
31402       rc = SQLITE_IOERR_NOMEM;
31403       goto shmpage_out;
31404     }
31405     pShmNode->aRegion = apNew;
31406
31407     while( pShmNode->nRegion<=iRegion ){
31408       HANDLE hMap;                /* file-mapping handle */
31409       void *pMap = 0;             /* Mapped memory region */
31410      
31411       hMap = CreateFileMapping(pShmNode->hFile.h, 
31412           NULL, PAGE_READWRITE, 0, nByte, NULL
31413       );
31414       OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
31415                (int)GetCurrentProcessId(), pShmNode->nRegion, nByte,
31416                hMap ? "ok" : "failed"));
31417       if( hMap ){
31418         int iOffset = pShmNode->nRegion*szRegion;
31419         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
31420         pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
31421             0, iOffset - iOffsetShift, szRegion + iOffsetShift
31422         );
31423         OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
31424                  (int)GetCurrentProcessId(), pShmNode->nRegion, iOffset, szRegion,
31425                  pMap ? "ok" : "failed"));
31426       }
31427       if( !pMap ){
31428         pShmNode->lastErrno = GetLastError();
31429         rc = SQLITE_IOERR;
31430         if( hMap ) CloseHandle(hMap);
31431         goto shmpage_out;
31432       }
31433
31434       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
31435       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
31436       pShmNode->nRegion++;
31437     }
31438   }
31439
31440 shmpage_out:
31441   if( pShmNode->nRegion>iRegion ){
31442     int iOffset = iRegion*szRegion;
31443     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
31444     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
31445     *pp = (void *)&p[iOffsetShift];
31446   }else{
31447     *pp = 0;
31448   }
31449   sqlite3_mutex_leave(pShmNode->mutex);
31450   return rc;
31451 }
31452
31453 #else
31454 # define winShmMap     0
31455 # define winShmLock    0
31456 # define winShmBarrier 0
31457 # define winShmUnmap   0
31458 #endif /* #ifndef SQLITE_OMIT_WAL */
31459
31460 /*
31461 ** Here ends the implementation of all sqlite3_file methods.
31462 **
31463 ********************** End sqlite3_file Methods *******************************
31464 ******************************************************************************/
31465
31466 /*
31467 ** This vector defines all the methods that can operate on an
31468 ** sqlite3_file for win32.
31469 */
31470 static const sqlite3_io_methods winIoMethod = {
31471   2,                              /* iVersion */
31472   winClose,                       /* xClose */
31473   winRead,                        /* xRead */
31474   winWrite,                       /* xWrite */
31475   winTruncate,                    /* xTruncate */
31476   winSync,                        /* xSync */
31477   winFileSize,                    /* xFileSize */
31478   winLock,                        /* xLock */
31479   winUnlock,                      /* xUnlock */
31480   winCheckReservedLock,           /* xCheckReservedLock */
31481   winFileControl,                 /* xFileControl */
31482   winSectorSize,                  /* xSectorSize */
31483   winDeviceCharacteristics,       /* xDeviceCharacteristics */
31484   winShmMap,                      /* xShmMap */
31485   winShmLock,                     /* xShmLock */
31486   winShmBarrier,                  /* xShmBarrier */
31487   winShmUnmap                     /* xShmUnmap */
31488 };
31489
31490 /****************************************************************************
31491 **************************** sqlite3_vfs methods ****************************
31492 **
31493 ** This division contains the implementation of methods on the
31494 ** sqlite3_vfs object.
31495 */
31496
31497 /*
31498 ** Convert a UTF-8 filename into whatever form the underlying
31499 ** operating system wants filenames in.  Space to hold the result
31500 ** is obtained from malloc and must be freed by the calling
31501 ** function.
31502 */
31503 static void *convertUtf8Filename(const char *zFilename){
31504   void *zConverted = 0;
31505   if( isNT() ){
31506     zConverted = utf8ToUnicode(zFilename);
31507 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31508 */
31509 #if SQLITE_OS_WINCE==0
31510   }else{
31511     zConverted = utf8ToMbcs(zFilename);
31512 #endif
31513   }
31514   /* caller will handle out of memory */
31515   return zConverted;
31516 }
31517
31518 /*
31519 ** Create a temporary file name in zBuf.  zBuf must be big enough to
31520 ** hold at pVfs->mxPathname characters.
31521 */
31522 static int getTempname(int nBuf, char *zBuf){
31523   static char zChars[] =
31524     "abcdefghijklmnopqrstuvwxyz"
31525     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
31526     "0123456789";
31527   size_t i, j;
31528   char zTempPath[MAX_PATH+1];
31529
31530   /* It's odd to simulate an io-error here, but really this is just
31531   ** using the io-error infrastructure to test that SQLite handles this
31532   ** function failing. 
31533   */
31534   SimulateIOError( return SQLITE_IOERR );
31535
31536   if( sqlite3_temp_directory ){
31537     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
31538   }else if( isNT() ){
31539     char *zMulti;
31540     WCHAR zWidePath[MAX_PATH];
31541     GetTempPathW(MAX_PATH-30, zWidePath);
31542     zMulti = unicodeToUtf8(zWidePath);
31543     if( zMulti ){
31544       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
31545       free(zMulti);
31546     }else{
31547       return SQLITE_NOMEM;
31548     }
31549 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31550 ** Since the ASCII version of these Windows API do not exist for WINCE,
31551 ** it's important to not reference them for WINCE builds.
31552 */
31553 #if SQLITE_OS_WINCE==0
31554   }else{
31555     char *zUtf8;
31556     char zMbcsPath[MAX_PATH];
31557     GetTempPathA(MAX_PATH-30, zMbcsPath);
31558     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
31559     if( zUtf8 ){
31560       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
31561       free(zUtf8);
31562     }else{
31563       return SQLITE_NOMEM;
31564     }
31565 #endif
31566   }
31567
31568   /* Check that the output buffer is large enough for the temporary file 
31569   ** name. If it is not, return SQLITE_ERROR.
31570   */
31571   if( (sqlite3Strlen30(zTempPath) + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
31572     return SQLITE_ERROR;
31573   }
31574
31575   for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
31576   zTempPath[i] = 0;
31577
31578   sqlite3_snprintf(nBuf-17, zBuf,
31579                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
31580   j = sqlite3Strlen30(zBuf);
31581   sqlite3_randomness(15, &zBuf[j]);
31582   for(i=0; i<15; i++, j++){
31583     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
31584   }
31585   zBuf[j] = 0;
31586
31587   OSTRACE(("TEMP FILENAME: %s\n", zBuf));
31588   return SQLITE_OK; 
31589 }
31590
31591 /*
31592 ** The return value of getLastErrorMsg
31593 ** is zero if the error message fits in the buffer, or non-zero
31594 ** otherwise (if the message was truncated).
31595 */
31596 static int getLastErrorMsg(int nBuf, char *zBuf){
31597   /* FormatMessage returns 0 on failure.  Otherwise it
31598   ** returns the number of TCHARs written to the output
31599   ** buffer, excluding the terminating null char.
31600   */
31601   DWORD error = GetLastError();
31602   DWORD dwLen = 0;
31603   char *zOut = 0;
31604
31605   if( isNT() ){
31606     WCHAR *zTempWide = NULL;
31607     dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
31608                            NULL,
31609                            error,
31610                            0,
31611                            (LPWSTR) &zTempWide,
31612                            0,
31613                            0);
31614     if( dwLen > 0 ){
31615       /* allocate a buffer and convert to UTF8 */
31616       zOut = unicodeToUtf8(zTempWide);
31617       /* free the system buffer allocated by FormatMessage */
31618       LocalFree(zTempWide);
31619     }
31620 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31621 ** Since the ASCII version of these Windows API do not exist for WINCE,
31622 ** it's important to not reference them for WINCE builds.
31623 */
31624 #if SQLITE_OS_WINCE==0
31625   }else{
31626     char *zTemp = NULL;
31627     dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
31628                            NULL,
31629                            error,
31630                            0,
31631                            (LPSTR) &zTemp,
31632                            0,
31633                            0);
31634     if( dwLen > 0 ){
31635       /* allocate a buffer and convert to UTF8 */
31636       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
31637       /* free the system buffer allocated by FormatMessage */
31638       LocalFree(zTemp);
31639     }
31640 #endif
31641   }
31642   if( 0 == dwLen ){
31643     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
31644   }else{
31645     /* copy a maximum of nBuf chars to output buffer */
31646     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
31647     /* free the UTF8 buffer */
31648     free(zOut);
31649   }
31650   return 0;
31651 }
31652
31653 /*
31654 ** Open a file.
31655 */
31656 static int winOpen(
31657   sqlite3_vfs *pVfs,        /* Not used */
31658   const char *zName,        /* Name of the file (UTF-8) */
31659   sqlite3_file *id,         /* Write the SQLite file handle here */
31660   int flags,                /* Open mode flags */
31661   int *pOutFlags            /* Status return flags */
31662 ){
31663   HANDLE h;
31664   DWORD dwDesiredAccess;
31665   DWORD dwShareMode;
31666   DWORD dwCreationDisposition;
31667   DWORD dwFlagsAndAttributes = 0;
31668 #if SQLITE_OS_WINCE
31669   int isTemp = 0;
31670 #endif
31671   winFile *pFile = (winFile*)id;
31672   void *zConverted;              /* Filename in OS encoding */
31673   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
31674
31675   /* If argument zPath is a NULL pointer, this function is required to open
31676   ** a temporary file. Use this buffer to store the file name in.
31677   */
31678   char zTmpname[MAX_PATH+1];     /* Buffer used to create temp filename */
31679
31680   int rc = SQLITE_OK;            /* Function Return Code */
31681 #if !defined(NDEBUG) || SQLITE_OS_WINCE
31682   int eType = flags&0xFFFFFF00;  /* Type of file to open */
31683 #endif
31684
31685   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
31686   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
31687   int isCreate     = (flags & SQLITE_OPEN_CREATE);
31688 #ifndef NDEBUG
31689   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
31690 #endif
31691   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
31692
31693 #ifndef NDEBUG
31694   int isOpenJournal = (isCreate && (
31695         eType==SQLITE_OPEN_MASTER_JOURNAL 
31696      || eType==SQLITE_OPEN_MAIN_JOURNAL 
31697      || eType==SQLITE_OPEN_WAL
31698   ));
31699 #endif
31700
31701   /* Check the following statements are true: 
31702   **
31703   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
31704   **   (b) if CREATE is set, then READWRITE must also be set, and
31705   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
31706   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
31707   */
31708   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
31709   assert(isCreate==0 || isReadWrite);
31710   assert(isExclusive==0 || isCreate);
31711   assert(isDelete==0 || isCreate);
31712
31713   /* The main DB, main journal, WAL file and master journal are never 
31714   ** automatically deleted. Nor are they ever temporary files.  */
31715   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
31716   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
31717   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
31718   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
31719
31720   /* Assert that the upper layer has set one of the "file-type" flags. */
31721   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
31722        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
31723        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
31724        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
31725   );
31726
31727   assert( id!=0 );
31728   UNUSED_PARAMETER(pVfs);
31729
31730   pFile->h = INVALID_HANDLE_VALUE;
31731
31732   /* If the second argument to this function is NULL, generate a 
31733   ** temporary file name to use 
31734   */
31735   if( !zUtf8Name ){
31736     assert(isDelete && !isOpenJournal);
31737     rc = getTempname(MAX_PATH+1, zTmpname);
31738     if( rc!=SQLITE_OK ){
31739       return rc;
31740     }
31741     zUtf8Name = zTmpname;
31742   }
31743
31744   /* Convert the filename to the system encoding. */
31745   zConverted = convertUtf8Filename(zUtf8Name);
31746   if( zConverted==0 ){
31747     return SQLITE_NOMEM;
31748   }
31749
31750   if( isReadWrite ){
31751     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
31752   }else{
31753     dwDesiredAccess = GENERIC_READ;
31754   }
31755
31756   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is 
31757   ** created. SQLite doesn't use it to indicate "exclusive access" 
31758   ** as it is usually understood.
31759   */
31760   if( isExclusive ){
31761     /* Creates a new file, only if it does not already exist. */
31762     /* If the file exists, it fails. */
31763     dwCreationDisposition = CREATE_NEW;
31764   }else if( isCreate ){
31765     /* Open existing file, or create if it doesn't exist */
31766     dwCreationDisposition = OPEN_ALWAYS;
31767   }else{
31768     /* Opens a file, only if it exists. */
31769     dwCreationDisposition = OPEN_EXISTING;
31770   }
31771
31772   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
31773
31774   if( isDelete ){
31775 #if SQLITE_OS_WINCE
31776     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
31777     isTemp = 1;
31778 #else
31779     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
31780                                | FILE_ATTRIBUTE_HIDDEN
31781                                | FILE_FLAG_DELETE_ON_CLOSE;
31782 #endif
31783   }else{
31784     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
31785   }
31786   /* Reports from the internet are that performance is always
31787   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
31788 #if SQLITE_OS_WINCE
31789   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
31790 #endif
31791
31792   if( isNT() ){
31793     h = CreateFileW((WCHAR*)zConverted,
31794        dwDesiredAccess,
31795        dwShareMode,
31796        NULL,
31797        dwCreationDisposition,
31798        dwFlagsAndAttributes,
31799        NULL
31800     );
31801 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31802 ** Since the ASCII version of these Windows API do not exist for WINCE,
31803 ** it's important to not reference them for WINCE builds.
31804 */
31805 #if SQLITE_OS_WINCE==0
31806   }else{
31807     h = CreateFileA((char*)zConverted,
31808        dwDesiredAccess,
31809        dwShareMode,
31810        NULL,
31811        dwCreationDisposition,
31812        dwFlagsAndAttributes,
31813        NULL
31814     );
31815 #endif
31816   }
31817
31818   OSTRACE(("OPEN %d %s 0x%lx %s\n", 
31819            h, zName, dwDesiredAccess, 
31820            h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
31821
31822   if( h==INVALID_HANDLE_VALUE ){
31823     pFile->lastErrno = GetLastError();
31824     free(zConverted);
31825     if( isReadWrite ){
31826       return winOpen(pVfs, zName, id, 
31827              ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
31828     }else{
31829       return SQLITE_CANTOPEN_BKPT;
31830     }
31831   }
31832
31833   if( pOutFlags ){
31834     if( isReadWrite ){
31835       *pOutFlags = SQLITE_OPEN_READWRITE;
31836     }else{
31837       *pOutFlags = SQLITE_OPEN_READONLY;
31838     }
31839   }
31840
31841   memset(pFile, 0, sizeof(*pFile));
31842   pFile->pMethod = &winIoMethod;
31843   pFile->h = h;
31844   pFile->lastErrno = NO_ERROR;
31845   pFile->pVfs = pVfs;
31846   pFile->pShm = 0;
31847   pFile->zPath = zName;
31848   pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
31849
31850 #if SQLITE_OS_WINCE
31851   if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
31852        && !winceCreateLock(zName, pFile)
31853   ){
31854     CloseHandle(h);
31855     free(zConverted);
31856     return SQLITE_CANTOPEN_BKPT;
31857   }
31858   if( isTemp ){
31859     pFile->zDeleteOnClose = zConverted;
31860   }else
31861 #endif
31862   {
31863     free(zConverted);
31864   }
31865
31866   OpenCounter(+1);
31867   return rc;
31868 }
31869
31870 /*
31871 ** Delete the named file.
31872 **
31873 ** Note that windows does not allow a file to be deleted if some other
31874 ** process has it open.  Sometimes a virus scanner or indexing program
31875 ** will open a journal file shortly after it is created in order to do
31876 ** whatever it does.  While this other process is holding the
31877 ** file open, we will be unable to delete it.  To work around this
31878 ** problem, we delay 100 milliseconds and try to delete again.  Up
31879 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
31880 ** up and returning an error.
31881 */
31882 #define MX_DELETION_ATTEMPTS 5
31883 static int winDelete(
31884   sqlite3_vfs *pVfs,          /* Not used on win32 */
31885   const char *zFilename,      /* Name of file to delete */
31886   int syncDir                 /* Not used on win32 */
31887 ){
31888   int cnt = 0;
31889   DWORD rc;
31890   DWORD error = 0;
31891   void *zConverted;
31892   UNUSED_PARAMETER(pVfs);
31893   UNUSED_PARAMETER(syncDir);
31894
31895   SimulateIOError(return SQLITE_IOERR_DELETE);
31896   zConverted = convertUtf8Filename(zFilename);
31897   if( zConverted==0 ){
31898     return SQLITE_NOMEM;
31899   }
31900   if( isNT() ){
31901     do{
31902       DeleteFileW(zConverted);
31903     }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
31904                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
31905            && (++cnt < MX_DELETION_ATTEMPTS)
31906            && (Sleep(100), 1) );
31907 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31908 ** Since the ASCII version of these Windows API do not exist for WINCE,
31909 ** it's important to not reference them for WINCE builds.
31910 */
31911 #if SQLITE_OS_WINCE==0
31912   }else{
31913     do{
31914       DeleteFileA(zConverted);
31915     }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
31916                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
31917            && (++cnt < MX_DELETION_ATTEMPTS)
31918            && (Sleep(100), 1) );
31919 #endif
31920   }
31921   free(zConverted);
31922   OSTRACE(("DELETE \"%s\" %s\n", zFilename,
31923        ( (rc==INVALID_FILE_ATTRIBUTES) && (error==ERROR_FILE_NOT_FOUND)) ?
31924          "ok" : "failed" ));
31925  
31926   return (   (rc == INVALID_FILE_ATTRIBUTES) 
31927           && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
31928 }
31929
31930 /*
31931 ** Check the existance and status of a file.
31932 */
31933 static int winAccess(
31934   sqlite3_vfs *pVfs,         /* Not used on win32 */
31935   const char *zFilename,     /* Name of file to check */
31936   int flags,                 /* Type of test to make on this file */
31937   int *pResOut               /* OUT: Result */
31938 ){
31939   DWORD attr;
31940   int rc = 0;
31941   void *zConverted;
31942   UNUSED_PARAMETER(pVfs);
31943
31944   SimulateIOError( return SQLITE_IOERR_ACCESS; );
31945   zConverted = convertUtf8Filename(zFilename);
31946   if( zConverted==0 ){
31947     return SQLITE_NOMEM;
31948   }
31949   if( isNT() ){
31950     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
31951     memset(&sAttrData, 0, sizeof(sAttrData));
31952     if( GetFileAttributesExW((WCHAR*)zConverted,
31953                              GetFileExInfoStandard, 
31954                              &sAttrData) ){
31955       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
31956       ** as if it does not exist.
31957       */
31958       if(    flags==SQLITE_ACCESS_EXISTS
31959           && sAttrData.nFileSizeHigh==0 
31960           && sAttrData.nFileSizeLow==0 ){
31961         attr = INVALID_FILE_ATTRIBUTES;
31962       }else{
31963         attr = sAttrData.dwFileAttributes;
31964       }
31965     }else{
31966       if( GetLastError()!=ERROR_FILE_NOT_FOUND ){
31967         free(zConverted);
31968         return SQLITE_IOERR_ACCESS;
31969       }else{
31970         attr = INVALID_FILE_ATTRIBUTES;
31971       }
31972     }
31973 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31974 ** Since the ASCII version of these Windows API do not exist for WINCE,
31975 ** it's important to not reference them for WINCE builds.
31976 */
31977 #if SQLITE_OS_WINCE==0
31978   }else{
31979     attr = GetFileAttributesA((char*)zConverted);
31980 #endif
31981   }
31982   free(zConverted);
31983   switch( flags ){
31984     case SQLITE_ACCESS_READ:
31985     case SQLITE_ACCESS_EXISTS:
31986       rc = attr!=INVALID_FILE_ATTRIBUTES;
31987       break;
31988     case SQLITE_ACCESS_READWRITE:
31989       rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
31990       break;
31991     default:
31992       assert(!"Invalid flags argument");
31993   }
31994   *pResOut = rc;
31995   return SQLITE_OK;
31996 }
31997
31998
31999 /*
32000 ** Turn a relative pathname into a full pathname.  Write the full
32001 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
32002 ** bytes in size.
32003 */
32004 static int winFullPathname(
32005   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
32006   const char *zRelative,        /* Possibly relative input path */
32007   int nFull,                    /* Size of output buffer in bytes */
32008   char *zFull                   /* Output buffer */
32009 ){
32010   
32011 #if defined(__CYGWIN__)
32012   SimulateIOError( return SQLITE_ERROR );
32013   UNUSED_PARAMETER(nFull);
32014   cygwin_conv_to_full_win32_path(zRelative, zFull);
32015   return SQLITE_OK;
32016 #endif
32017
32018 #if SQLITE_OS_WINCE
32019   SimulateIOError( return SQLITE_ERROR );
32020   UNUSED_PARAMETER(nFull);
32021   /* WinCE has no concept of a relative pathname, or so I am told. */
32022   sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
32023   return SQLITE_OK;
32024 #endif
32025
32026 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
32027   int nByte;
32028   void *zConverted;
32029   char *zOut;
32030
32031   /* It's odd to simulate an io-error here, but really this is just
32032   ** using the io-error infrastructure to test that SQLite handles this
32033   ** function failing. This function could fail if, for example, the
32034   ** current working directory has been unlinked.
32035   */
32036   SimulateIOError( return SQLITE_ERROR );
32037   UNUSED_PARAMETER(nFull);
32038   zConverted = convertUtf8Filename(zRelative);
32039   if( isNT() ){
32040     WCHAR *zTemp;
32041     nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
32042     zTemp = malloc( nByte*sizeof(zTemp[0]) );
32043     if( zTemp==0 ){
32044       free(zConverted);
32045       return SQLITE_NOMEM;
32046     }
32047     GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
32048     free(zConverted);
32049     zOut = unicodeToUtf8(zTemp);
32050     free(zTemp);
32051 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
32052 ** Since the ASCII version of these Windows API do not exist for WINCE,
32053 ** it's important to not reference them for WINCE builds.
32054 */
32055 #if SQLITE_OS_WINCE==0
32056   }else{
32057     char *zTemp;
32058     nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
32059     zTemp = malloc( nByte*sizeof(zTemp[0]) );
32060     if( zTemp==0 ){
32061       free(zConverted);
32062       return SQLITE_NOMEM;
32063     }
32064     GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
32065     free(zConverted);
32066     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
32067     free(zTemp);
32068 #endif
32069   }
32070   if( zOut ){
32071     sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
32072     free(zOut);
32073     return SQLITE_OK;
32074   }else{
32075     return SQLITE_NOMEM;
32076   }
32077 #endif
32078 }
32079
32080 /*
32081 ** Get the sector size of the device used to store
32082 ** file.
32083 */
32084 static int getSectorSize(
32085     sqlite3_vfs *pVfs,
32086     const char *zRelative     /* UTF-8 file name */
32087 ){
32088   DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
32089   /* GetDiskFreeSpace is not supported under WINCE */
32090 #if SQLITE_OS_WINCE
32091   UNUSED_PARAMETER(pVfs);
32092   UNUSED_PARAMETER(zRelative);
32093 #else
32094   char zFullpath[MAX_PATH+1];
32095   int rc;
32096   DWORD dwRet = 0;
32097   DWORD dwDummy;
32098
32099   /*
32100   ** We need to get the full path name of the file
32101   ** to get the drive letter to look up the sector
32102   ** size.
32103   */
32104   SimulateIOErrorBenign(1);
32105   rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
32106   SimulateIOErrorBenign(0);
32107   if( rc == SQLITE_OK )
32108   {
32109     void *zConverted = convertUtf8Filename(zFullpath);
32110     if( zConverted ){
32111       if( isNT() ){
32112         /* trim path to just drive reference */
32113         WCHAR *p = zConverted;
32114         for(;*p;p++){
32115           if( *p == '\\' ){
32116             *p = '\0';
32117             break;
32118           }
32119         }
32120         dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
32121                                   &dwDummy,
32122                                   &bytesPerSector,
32123                                   &dwDummy,
32124                                   &dwDummy);
32125       }else{
32126         /* trim path to just drive reference */
32127         char *p = (char *)zConverted;
32128         for(;*p;p++){
32129           if( *p == '\\' ){
32130             *p = '\0';
32131             break;
32132           }
32133         }
32134         dwRet = GetDiskFreeSpaceA((char*)zConverted,
32135                                   &dwDummy,
32136                                   &bytesPerSector,
32137                                   &dwDummy,
32138                                   &dwDummy);
32139       }
32140       free(zConverted);
32141     }
32142     if( !dwRet ){
32143       bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
32144     }
32145   }
32146 #endif
32147   return (int) bytesPerSector; 
32148 }
32149
32150 #ifndef SQLITE_OMIT_LOAD_EXTENSION
32151 /*
32152 ** Interfaces for opening a shared library, finding entry points
32153 ** within the shared library, and closing the shared library.
32154 */
32155 /*
32156 ** Interfaces for opening a shared library, finding entry points
32157 ** within the shared library, and closing the shared library.
32158 */
32159 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
32160   HANDLE h;
32161   void *zConverted = convertUtf8Filename(zFilename);
32162   UNUSED_PARAMETER(pVfs);
32163   if( zConverted==0 ){
32164     return 0;
32165   }
32166   if( isNT() ){
32167     h = LoadLibraryW((WCHAR*)zConverted);
32168 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
32169 ** Since the ASCII version of these Windows API do not exist for WINCE,
32170 ** it's important to not reference them for WINCE builds.
32171 */
32172 #if SQLITE_OS_WINCE==0
32173   }else{
32174     h = LoadLibraryA((char*)zConverted);
32175 #endif
32176   }
32177   free(zConverted);
32178   return (void*)h;
32179 }
32180 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
32181   UNUSED_PARAMETER(pVfs);
32182   getLastErrorMsg(nBuf, zBufOut);
32183 }
32184 void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
32185   UNUSED_PARAMETER(pVfs);
32186 #if SQLITE_OS_WINCE
32187   /* The GetProcAddressA() routine is only available on wince. */
32188   return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
32189 #else
32190   /* All other windows platforms expect GetProcAddress() to take
32191   ** an Ansi string regardless of the _UNICODE setting */
32192   return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
32193 #endif
32194 }
32195 void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
32196   UNUSED_PARAMETER(pVfs);
32197   FreeLibrary((HANDLE)pHandle);
32198 }
32199 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
32200   #define winDlOpen  0
32201   #define winDlError 0
32202   #define winDlSym   0
32203   #define winDlClose 0
32204 #endif
32205
32206
32207 /*
32208 ** Write up to nBuf bytes of randomness into zBuf.
32209 */
32210 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
32211   int n = 0;
32212   UNUSED_PARAMETER(pVfs);
32213 #if defined(SQLITE_TEST)
32214   n = nBuf;
32215   memset(zBuf, 0, nBuf);
32216 #else
32217   if( sizeof(SYSTEMTIME)<=nBuf-n ){
32218     SYSTEMTIME x;
32219     GetSystemTime(&x);
32220     memcpy(&zBuf[n], &x, sizeof(x));
32221     n += sizeof(x);
32222   }
32223   if( sizeof(DWORD)<=nBuf-n ){
32224     DWORD pid = GetCurrentProcessId();
32225     memcpy(&zBuf[n], &pid, sizeof(pid));
32226     n += sizeof(pid);
32227   }
32228   if( sizeof(DWORD)<=nBuf-n ){
32229     DWORD cnt = GetTickCount();
32230     memcpy(&zBuf[n], &cnt, sizeof(cnt));
32231     n += sizeof(cnt);
32232   }
32233   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
32234     LARGE_INTEGER i;
32235     QueryPerformanceCounter(&i);
32236     memcpy(&zBuf[n], &i, sizeof(i));
32237     n += sizeof(i);
32238   }
32239 #endif
32240   return n;
32241 }
32242
32243
32244 /*
32245 ** Sleep for a little while.  Return the amount of time slept.
32246 */
32247 static int winSleep(sqlite3_vfs *pVfs, int microsec){
32248   Sleep((microsec+999)/1000);
32249   UNUSED_PARAMETER(pVfs);
32250   return ((microsec+999)/1000)*1000;
32251 }
32252
32253 /*
32254 ** The following variable, if set to a non-zero value, is interpreted as
32255 ** the number of seconds since 1970 and is used to set the result of
32256 ** sqlite3OsCurrentTime() during testing.
32257 */
32258 #ifdef SQLITE_TEST
32259 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
32260 #endif
32261
32262 /*
32263 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
32264 ** the current time and date as a Julian Day number times 86_400_000.  In
32265 ** other words, write into *piNow the number of milliseconds since the Julian
32266 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
32267 ** proleptic Gregorian calendar.
32268 **
32269 ** On success, return 0.  Return 1 if the time and date cannot be found.
32270 */
32271 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
32272   /* FILETIME structure is a 64-bit value representing the number of 
32273      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
32274   */
32275   FILETIME ft;
32276   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
32277 #ifdef SQLITE_TEST
32278   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
32279 #endif
32280   /* 2^32 - to avoid use of LL and warnings in gcc */
32281   static const sqlite3_int64 max32BitValue = 
32282       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
32283
32284 #if SQLITE_OS_WINCE
32285   SYSTEMTIME time;
32286   GetSystemTime(&time);
32287   /* if SystemTimeToFileTime() fails, it returns zero. */
32288   if (!SystemTimeToFileTime(&time,&ft)){
32289     return 1;
32290   }
32291 #else
32292   GetSystemTimeAsFileTime( &ft );
32293 #endif
32294
32295   *piNow = winFiletimeEpoch +
32296             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + 
32297                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
32298
32299 #ifdef SQLITE_TEST
32300   if( sqlite3_current_time ){
32301     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
32302   }
32303 #endif
32304   UNUSED_PARAMETER(pVfs);
32305   return 0;
32306 }
32307
32308 /*
32309 ** Find the current time (in Universal Coordinated Time).  Write the
32310 ** current time and date as a Julian Day number into *prNow and
32311 ** return 0.  Return 1 if the time and date cannot be found.
32312 */
32313 int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
32314   int rc;
32315   sqlite3_int64 i;
32316   rc = winCurrentTimeInt64(pVfs, &i);
32317   if( !rc ){
32318     *prNow = i/86400000.0;
32319   }
32320   return rc;
32321 }
32322
32323 /*
32324 ** The idea is that this function works like a combination of
32325 ** GetLastError() and FormatMessage() on windows (or errno and
32326 ** strerror_r() on unix). After an error is returned by an OS
32327 ** function, SQLite calls this function with zBuf pointing to
32328 ** a buffer of nBuf bytes. The OS layer should populate the
32329 ** buffer with a nul-terminated UTF-8 encoded error message
32330 ** describing the last IO error to have occurred within the calling
32331 ** thread.
32332 **
32333 ** If the error message is too large for the supplied buffer,
32334 ** it should be truncated. The return value of xGetLastError
32335 ** is zero if the error message fits in the buffer, or non-zero
32336 ** otherwise (if the message was truncated). If non-zero is returned,
32337 ** then it is not necessary to include the nul-terminator character
32338 ** in the output buffer.
32339 **
32340 ** Not supplying an error message will have no adverse effect
32341 ** on SQLite. It is fine to have an implementation that never
32342 ** returns an error message:
32343 **
32344 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
32345 **     assert(zBuf[0]=='\0');
32346 **     return 0;
32347 **   }
32348 **
32349 ** However if an error message is supplied, it will be incorporated
32350 ** by sqlite into the error message available to the user using
32351 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
32352 */
32353 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
32354   UNUSED_PARAMETER(pVfs);
32355   return getLastErrorMsg(nBuf, zBuf);
32356 }
32357
32358
32359
32360 /*
32361 ** Initialize and deinitialize the operating system interface.
32362 */
32363 SQLITE_API int sqlite3_os_init(void){
32364   static sqlite3_vfs winVfs = {
32365     2,                   /* iVersion */
32366     sizeof(winFile),     /* szOsFile */
32367     MAX_PATH,            /* mxPathname */
32368     0,                   /* pNext */
32369     "win32",             /* zName */
32370     0,                   /* pAppData */
32371     winOpen,             /* xOpen */
32372     winDelete,           /* xDelete */
32373     winAccess,           /* xAccess */
32374     winFullPathname,     /* xFullPathname */
32375     winDlOpen,           /* xDlOpen */
32376     winDlError,          /* xDlError */
32377     winDlSym,            /* xDlSym */
32378     winDlClose,          /* xDlClose */
32379     winRandomness,       /* xRandomness */
32380     winSleep,            /* xSleep */
32381     winCurrentTime,      /* xCurrentTime */
32382     winGetLastError,     /* xGetLastError */
32383     winCurrentTimeInt64, /* xCurrentTimeInt64 */
32384   };
32385
32386 #ifndef SQLITE_OMIT_WAL
32387   /* get memory map allocation granularity */
32388   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
32389   GetSystemInfo(&winSysInfo);
32390   assert(winSysInfo.dwAllocationGranularity > 0);
32391 #endif
32392
32393   sqlite3_vfs_register(&winVfs, 1);
32394   return SQLITE_OK; 
32395 }
32396 SQLITE_API int sqlite3_os_end(void){ 
32397   return SQLITE_OK;
32398 }
32399
32400 #endif /* SQLITE_OS_WIN */
32401
32402 /************** End of os_win.c **********************************************/
32403 /************** Begin file bitvec.c ******************************************/
32404 /*
32405 ** 2008 February 16
32406 **
32407 ** The author disclaims copyright to this source code.  In place of
32408 ** a legal notice, here is a blessing:
32409 **
32410 **    May you do good and not evil.
32411 **    May you find forgiveness for yourself and forgive others.
32412 **    May you share freely, never taking more than you give.
32413 **
32414 *************************************************************************
32415 ** This file implements an object that represents a fixed-length
32416 ** bitmap.  Bits are numbered starting with 1.
32417 **
32418 ** A bitmap is used to record which pages of a database file have been
32419 ** journalled during a transaction, or which pages have the "dont-write"
32420 ** property.  Usually only a few pages are meet either condition.
32421 ** So the bitmap is usually sparse and has low cardinality.
32422 ** But sometimes (for example when during a DROP of a large table) most
32423 ** or all of the pages in a database can get journalled.  In those cases, 
32424 ** the bitmap becomes dense with high cardinality.  The algorithm needs 
32425 ** to handle both cases well.
32426 **
32427 ** The size of the bitmap is fixed when the object is created.
32428 **
32429 ** All bits are clear when the bitmap is created.  Individual bits
32430 ** may be set or cleared one at a time.
32431 **
32432 ** Test operations are about 100 times more common that set operations.
32433 ** Clear operations are exceedingly rare.  There are usually between
32434 ** 5 and 500 set operations per Bitvec object, though the number of sets can
32435 ** sometimes grow into tens of thousands or larger.  The size of the
32436 ** Bitvec object is the number of pages in the database file at the
32437 ** start of a transaction, and is thus usually less than a few thousand,
32438 ** but can be as large as 2 billion for a really big database.
32439 */
32440
32441 /* Size of the Bitvec structure in bytes. */
32442 #define BITVEC_SZ        512
32443
32444 /* Round the union size down to the nearest pointer boundary, since that's how 
32445 ** it will be aligned within the Bitvec struct. */
32446 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
32447
32448 /* Type of the array "element" for the bitmap representation. 
32449 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. 
32450 ** Setting this to the "natural word" size of your CPU may improve
32451 ** performance. */
32452 #define BITVEC_TELEM     u8
32453 /* Size, in bits, of the bitmap element. */
32454 #define BITVEC_SZELEM    8
32455 /* Number of elements in a bitmap array. */
32456 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
32457 /* Number of bits in the bitmap array. */
32458 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
32459
32460 /* Number of u32 values in hash table. */
32461 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
32462 /* Maximum number of entries in hash table before 
32463 ** sub-dividing and re-hashing. */
32464 #define BITVEC_MXHASH    (BITVEC_NINT/2)
32465 /* Hashing function for the aHash representation.
32466 ** Empirical testing showed that the *37 multiplier 
32467 ** (an arbitrary prime)in the hash function provided 
32468 ** no fewer collisions than the no-op *1. */
32469 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
32470
32471 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
32472
32473
32474 /*
32475 ** A bitmap is an instance of the following structure.
32476 **
32477 ** This bitmap records the existance of zero or more bits
32478 ** with values between 1 and iSize, inclusive.
32479 **
32480 ** There are three possible representations of the bitmap.
32481 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
32482 ** bitmap.  The least significant bit is bit 1.
32483 **
32484 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
32485 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
32486 **
32487 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
32488 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
32489 ** handles up to iDivisor separate values of i.  apSub[0] holds
32490 ** values between 1 and iDivisor.  apSub[1] holds values between
32491 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
32492 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
32493 ** to hold deal with values between 1 and iDivisor.
32494 */
32495 struct Bitvec {
32496   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
32497   u32 nSet;       /* Number of bits that are set - only valid for aHash
32498                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
32499                   ** this would be 125. */
32500   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
32501                   /* Should >=0 for apSub element. */
32502                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
32503                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
32504   union {
32505     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
32506     u32 aHash[BITVEC_NINT];      /* Hash table representation */
32507     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
32508   } u;
32509 };
32510
32511 /*
32512 ** Create a new bitmap object able to handle bits between 0 and iSize,
32513 ** inclusive.  Return a pointer to the new object.  Return NULL if 
32514 ** malloc fails.
32515 */
32516 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
32517   Bitvec *p;
32518   assert( sizeof(*p)==BITVEC_SZ );
32519   p = sqlite3MallocZero( sizeof(*p) );
32520   if( p ){
32521     p->iSize = iSize;
32522   }
32523   return p;
32524 }
32525
32526 /*
32527 ** Check to see if the i-th bit is set.  Return true or false.
32528 ** If p is NULL (if the bitmap has not been created) or if
32529 ** i is out of range, then return false.
32530 */
32531 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
32532   if( p==0 ) return 0;
32533   if( i>p->iSize || i==0 ) return 0;
32534   i--;
32535   while( p->iDivisor ){
32536     u32 bin = i/p->iDivisor;
32537     i = i%p->iDivisor;
32538     p = p->u.apSub[bin];
32539     if (!p) {
32540       return 0;
32541     }
32542   }
32543   if( p->iSize<=BITVEC_NBIT ){
32544     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
32545   } else{
32546     u32 h = BITVEC_HASH(i++);
32547     while( p->u.aHash[h] ){
32548       if( p->u.aHash[h]==i ) return 1;
32549       h = (h+1) % BITVEC_NINT;
32550     }
32551     return 0;
32552   }
32553 }
32554
32555 /*
32556 ** Set the i-th bit.  Return 0 on success and an error code if
32557 ** anything goes wrong.
32558 **
32559 ** This routine might cause sub-bitmaps to be allocated.  Failing
32560 ** to get the memory needed to hold the sub-bitmap is the only
32561 ** that can go wrong with an insert, assuming p and i are valid.
32562 **
32563 ** The calling function must ensure that p is a valid Bitvec object
32564 ** and that the value for "i" is within range of the Bitvec object.
32565 ** Otherwise the behavior is undefined.
32566 */
32567 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
32568   u32 h;
32569   if( p==0 ) return SQLITE_OK;
32570   assert( i>0 );
32571   assert( i<=p->iSize );
32572   i--;
32573   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
32574     u32 bin = i/p->iDivisor;
32575     i = i%p->iDivisor;
32576     if( p->u.apSub[bin]==0 ){
32577       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
32578       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
32579     }
32580     p = p->u.apSub[bin];
32581   }
32582   if( p->iSize<=BITVEC_NBIT ){
32583     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
32584     return SQLITE_OK;
32585   }
32586   h = BITVEC_HASH(i++);
32587   /* if there wasn't a hash collision, and this doesn't */
32588   /* completely fill the hash, then just add it without */
32589   /* worring about sub-dividing and re-hashing. */
32590   if( !p->u.aHash[h] ){
32591     if (p->nSet<(BITVEC_NINT-1)) {
32592       goto bitvec_set_end;
32593     } else {
32594       goto bitvec_set_rehash;
32595     }
32596   }
32597   /* there was a collision, check to see if it's already */
32598   /* in hash, if not, try to find a spot for it */
32599   do {
32600     if( p->u.aHash[h]==i ) return SQLITE_OK;
32601     h++;
32602     if( h>=BITVEC_NINT ) h = 0;
32603   } while( p->u.aHash[h] );
32604   /* we didn't find it in the hash.  h points to the first */
32605   /* available free spot. check to see if this is going to */
32606   /* make our hash too "full".  */
32607 bitvec_set_rehash:
32608   if( p->nSet>=BITVEC_MXHASH ){
32609     unsigned int j;
32610     int rc;
32611     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
32612     if( aiValues==0 ){
32613       return SQLITE_NOMEM;
32614     }else{
32615       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
32616       memset(p->u.apSub, 0, sizeof(p->u.apSub));
32617       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
32618       rc = sqlite3BitvecSet(p, i);
32619       for(j=0; j<BITVEC_NINT; j++){
32620         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
32621       }
32622       sqlite3StackFree(0, aiValues);
32623       return rc;
32624     }
32625   }
32626 bitvec_set_end:
32627   p->nSet++;
32628   p->u.aHash[h] = i;
32629   return SQLITE_OK;
32630 }
32631
32632 /*
32633 ** Clear the i-th bit.
32634 **
32635 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
32636 ** that BitvecClear can use to rebuilt its hash table.
32637 */
32638 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
32639   if( p==0 ) return;
32640   assert( i>0 );
32641   i--;
32642   while( p->iDivisor ){
32643     u32 bin = i/p->iDivisor;
32644     i = i%p->iDivisor;
32645     p = p->u.apSub[bin];
32646     if (!p) {
32647       return;
32648     }
32649   }
32650   if( p->iSize<=BITVEC_NBIT ){
32651     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
32652   }else{
32653     unsigned int j;
32654     u32 *aiValues = pBuf;
32655     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
32656     memset(p->u.aHash, 0, sizeof(p->u.aHash));
32657     p->nSet = 0;
32658     for(j=0; j<BITVEC_NINT; j++){
32659       if( aiValues[j] && aiValues[j]!=(i+1) ){
32660         u32 h = BITVEC_HASH(aiValues[j]-1);
32661         p->nSet++;
32662         while( p->u.aHash[h] ){
32663           h++;
32664           if( h>=BITVEC_NINT ) h = 0;
32665         }
32666         p->u.aHash[h] = aiValues[j];
32667       }
32668     }
32669   }
32670 }
32671
32672 /*
32673 ** Destroy a bitmap object.  Reclaim all memory used.
32674 */
32675 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
32676   if( p==0 ) return;
32677   if( p->iDivisor ){
32678     unsigned int i;
32679     for(i=0; i<BITVEC_NPTR; i++){
32680       sqlite3BitvecDestroy(p->u.apSub[i]);
32681     }
32682   }
32683   sqlite3_free(p);
32684 }
32685
32686 /*
32687 ** Return the value of the iSize parameter specified when Bitvec *p
32688 ** was created.
32689 */
32690 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
32691   return p->iSize;
32692 }
32693
32694 #ifndef SQLITE_OMIT_BUILTIN_TEST
32695 /*
32696 ** Let V[] be an array of unsigned characters sufficient to hold
32697 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
32698 ** Then the following macros can be used to set, clear, or test
32699 ** individual bits within V.
32700 */
32701 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
32702 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
32703 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
32704
32705 /*
32706 ** This routine runs an extensive test of the Bitvec code.
32707 **
32708 ** The input is an array of integers that acts as a program
32709 ** to test the Bitvec.  The integers are opcodes followed
32710 ** by 0, 1, or 3 operands, depending on the opcode.  Another
32711 ** opcode follows immediately after the last operand.
32712 **
32713 ** There are 6 opcodes numbered from 0 through 5.  0 is the
32714 ** "halt" opcode and causes the test to end.
32715 **
32716 **    0          Halt and return the number of errors
32717 **    1 N S X    Set N bits beginning with S and incrementing by X
32718 **    2 N S X    Clear N bits beginning with S and incrementing by X
32719 **    3 N        Set N randomly chosen bits
32720 **    4 N        Clear N randomly chosen bits
32721 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
32722 **
32723 ** The opcodes 1 through 4 perform set and clear operations are performed
32724 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
32725 ** Opcode 5 works on the linear array only, not on the Bitvec.
32726 ** Opcode 5 is used to deliberately induce a fault in order to
32727 ** confirm that error detection works.
32728 **
32729 ** At the conclusion of the test the linear array is compared
32730 ** against the Bitvec object.  If there are any differences,
32731 ** an error is returned.  If they are the same, zero is returned.
32732 **
32733 ** If a memory allocation error occurs, return -1.
32734 */
32735 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
32736   Bitvec *pBitvec = 0;
32737   unsigned char *pV = 0;
32738   int rc = -1;
32739   int i, nx, pc, op;
32740   void *pTmpSpace;
32741
32742   /* Allocate the Bitvec to be tested and a linear array of
32743   ** bits to act as the reference */
32744   pBitvec = sqlite3BitvecCreate( sz );
32745   pV = sqlite3_malloc( (sz+7)/8 + 1 );
32746   pTmpSpace = sqlite3_malloc(BITVEC_SZ);
32747   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
32748   memset(pV, 0, (sz+7)/8 + 1);
32749
32750   /* NULL pBitvec tests */
32751   sqlite3BitvecSet(0, 1);
32752   sqlite3BitvecClear(0, 1, pTmpSpace);
32753
32754   /* Run the program */
32755   pc = 0;
32756   while( (op = aOp[pc])!=0 ){
32757     switch( op ){
32758       case 1:
32759       case 2:
32760       case 5: {
32761         nx = 4;
32762         i = aOp[pc+2] - 1;
32763         aOp[pc+2] += aOp[pc+3];
32764         break;
32765       }
32766       case 3:
32767       case 4: 
32768       default: {
32769         nx = 2;
32770         sqlite3_randomness(sizeof(i), &i);
32771         break;
32772       }
32773     }
32774     if( (--aOp[pc+1]) > 0 ) nx = 0;
32775     pc += nx;
32776     i = (i & 0x7fffffff)%sz;
32777     if( (op & 1)!=0 ){
32778       SETBIT(pV, (i+1));
32779       if( op!=5 ){
32780         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
32781       }
32782     }else{
32783       CLEARBIT(pV, (i+1));
32784       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
32785     }
32786   }
32787
32788   /* Test to make sure the linear array exactly matches the
32789   ** Bitvec object.  Start with the assumption that they do
32790   ** match (rc==0).  Change rc to non-zero if a discrepancy
32791   ** is found.
32792   */
32793   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
32794           + sqlite3BitvecTest(pBitvec, 0)
32795           + (sqlite3BitvecSize(pBitvec) - sz);
32796   for(i=1; i<=sz; i++){
32797     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
32798       rc = i;
32799       break;
32800     }
32801   }
32802
32803   /* Free allocated structure */
32804 bitvec_end:
32805   sqlite3_free(pTmpSpace);
32806   sqlite3_free(pV);
32807   sqlite3BitvecDestroy(pBitvec);
32808   return rc;
32809 }
32810 #endif /* SQLITE_OMIT_BUILTIN_TEST */
32811
32812 /************** End of bitvec.c **********************************************/
32813 /************** Begin file pcache.c ******************************************/
32814 /*
32815 ** 2008 August 05
32816 **
32817 ** The author disclaims copyright to this source code.  In place of
32818 ** a legal notice, here is a blessing:
32819 **
32820 **    May you do good and not evil.
32821 **    May you find forgiveness for yourself and forgive others.
32822 **    May you share freely, never taking more than you give.
32823 **
32824 *************************************************************************
32825 ** This file implements that page cache.
32826 */
32827
32828 /*
32829 ** A complete page cache is an instance of this structure.
32830 */
32831 struct PCache {
32832   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
32833   PgHdr *pSynced;                     /* Last synced page in dirty page list */
32834   int nRef;                           /* Number of referenced pages */
32835   int nMax;                           /* Configured cache size */
32836   int szPage;                         /* Size of every page in this cache */
32837   int szExtra;                        /* Size of extra space for each page */
32838   int bPurgeable;                     /* True if pages are on backing store */
32839   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
32840   void *pStress;                      /* Argument to xStress */
32841   sqlite3_pcache *pCache;             /* Pluggable cache module */
32842   PgHdr *pPage1;                      /* Reference to page 1 */
32843 };
32844
32845 /*
32846 ** Some of the assert() macros in this code are too expensive to run
32847 ** even during normal debugging.  Use them only rarely on long-running
32848 ** tests.  Enable the expensive asserts using the
32849 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
32850 */
32851 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
32852 # define expensive_assert(X)  assert(X)
32853 #else
32854 # define expensive_assert(X)
32855 #endif
32856
32857 /********************************** Linked List Management ********************/
32858
32859 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
32860 /*
32861 ** Check that the pCache->pSynced variable is set correctly. If it
32862 ** is not, either fail an assert or return zero. Otherwise, return
32863 ** non-zero. This is only used in debugging builds, as follows:
32864 **
32865 **   expensive_assert( pcacheCheckSynced(pCache) );
32866 */
32867 static int pcacheCheckSynced(PCache *pCache){
32868   PgHdr *p;
32869   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
32870     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
32871   }
32872   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
32873 }
32874 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
32875
32876 /*
32877 ** Remove page pPage from the list of dirty pages.
32878 */
32879 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
32880   PCache *p = pPage->pCache;
32881
32882   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
32883   assert( pPage->pDirtyPrev || pPage==p->pDirty );
32884
32885   /* Update the PCache1.pSynced variable if necessary. */
32886   if( p->pSynced==pPage ){
32887     PgHdr *pSynced = pPage->pDirtyPrev;
32888     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
32889       pSynced = pSynced->pDirtyPrev;
32890     }
32891     p->pSynced = pSynced;
32892   }
32893
32894   if( pPage->pDirtyNext ){
32895     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
32896   }else{
32897     assert( pPage==p->pDirtyTail );
32898     p->pDirtyTail = pPage->pDirtyPrev;
32899   }
32900   if( pPage->pDirtyPrev ){
32901     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
32902   }else{
32903     assert( pPage==p->pDirty );
32904     p->pDirty = pPage->pDirtyNext;
32905   }
32906   pPage->pDirtyNext = 0;
32907   pPage->pDirtyPrev = 0;
32908
32909   expensive_assert( pcacheCheckSynced(p) );
32910 }
32911
32912 /*
32913 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
32914 ** pPage).
32915 */
32916 static void pcacheAddToDirtyList(PgHdr *pPage){
32917   PCache *p = pPage->pCache;
32918
32919   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
32920
32921   pPage->pDirtyNext = p->pDirty;
32922   if( pPage->pDirtyNext ){
32923     assert( pPage->pDirtyNext->pDirtyPrev==0 );
32924     pPage->pDirtyNext->pDirtyPrev = pPage;
32925   }
32926   p->pDirty = pPage;
32927   if( !p->pDirtyTail ){
32928     p->pDirtyTail = pPage;
32929   }
32930   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
32931     p->pSynced = pPage;
32932   }
32933   expensive_assert( pcacheCheckSynced(p) );
32934 }
32935
32936 /*
32937 ** Wrapper around the pluggable caches xUnpin method. If the cache is
32938 ** being used for an in-memory database, this function is a no-op.
32939 */
32940 static void pcacheUnpin(PgHdr *p){
32941   PCache *pCache = p->pCache;
32942   if( pCache->bPurgeable ){
32943     if( p->pgno==1 ){
32944       pCache->pPage1 = 0;
32945     }
32946     sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
32947   }
32948 }
32949
32950 /*************************************************** General Interfaces ******
32951 **
32952 ** Initialize and shutdown the page cache subsystem. Neither of these 
32953 ** functions are threadsafe.
32954 */
32955 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
32956   if( sqlite3GlobalConfig.pcache.xInit==0 ){
32957     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
32958     ** built-in default page cache is used instead of the application defined
32959     ** page cache. */
32960     sqlite3PCacheSetDefault();
32961   }
32962   return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
32963 }
32964 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
32965   if( sqlite3GlobalConfig.pcache.xShutdown ){
32966     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
32967     sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
32968   }
32969 }
32970
32971 /*
32972 ** Return the size in bytes of a PCache object.
32973 */
32974 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
32975
32976 /*
32977 ** Create a new PCache object. Storage space to hold the object
32978 ** has already been allocated and is passed in as the p pointer. 
32979 ** The caller discovers how much space needs to be allocated by 
32980 ** calling sqlite3PcacheSize().
32981 */
32982 SQLITE_PRIVATE void sqlite3PcacheOpen(
32983   int szPage,                  /* Size of every page */
32984   int szExtra,                 /* Extra space associated with each page */
32985   int bPurgeable,              /* True if pages are on backing store */
32986   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
32987   void *pStress,               /* Argument to xStress */
32988   PCache *p                    /* Preallocated space for the PCache */
32989 ){
32990   memset(p, 0, sizeof(PCache));
32991   p->szPage = szPage;
32992   p->szExtra = szExtra;
32993   p->bPurgeable = bPurgeable;
32994   p->xStress = xStress;
32995   p->pStress = pStress;
32996   p->nMax = 100;
32997 }
32998
32999 /*
33000 ** Change the page size for PCache object. The caller must ensure that there
33001 ** are no outstanding page references when this function is called.
33002 */
33003 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
33004   assert( pCache->nRef==0 && pCache->pDirty==0 );
33005   if( pCache->pCache ){
33006     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
33007     pCache->pCache = 0;
33008     pCache->pPage1 = 0;
33009   }
33010   pCache->szPage = szPage;
33011 }
33012
33013 /*
33014 ** Try to obtain a page from the cache.
33015 */
33016 SQLITE_PRIVATE int sqlite3PcacheFetch(
33017   PCache *pCache,       /* Obtain the page from this cache */
33018   Pgno pgno,            /* Page number to obtain */
33019   int createFlag,       /* If true, create page if it does not exist already */
33020   PgHdr **ppPage        /* Write the page here */
33021 ){
33022   PgHdr *pPage = 0;
33023   int eCreate;
33024
33025   assert( pCache!=0 );
33026   assert( createFlag==1 || createFlag==0 );
33027   assert( pgno>0 );
33028
33029   /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
33030   ** allocate it now.
33031   */
33032   if( !pCache->pCache && createFlag ){
33033     sqlite3_pcache *p;
33034     int nByte;
33035     nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
33036     p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
33037     if( !p ){
33038       return SQLITE_NOMEM;
33039     }
33040     sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
33041     pCache->pCache = p;
33042   }
33043
33044   eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
33045   if( pCache->pCache ){
33046     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
33047   }
33048
33049   if( !pPage && eCreate==1 ){
33050     PgHdr *pPg;
33051
33052     /* Find a dirty page to write-out and recycle. First try to find a 
33053     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
33054     ** cleared), but if that is not possible settle for any other 
33055     ** unreferenced dirty page.
33056     */
33057     expensive_assert( pcacheCheckSynced(pCache) );
33058     for(pPg=pCache->pSynced; 
33059         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
33060         pPg=pPg->pDirtyPrev
33061     );
33062     pCache->pSynced = pPg;
33063     if( !pPg ){
33064       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
33065     }
33066     if( pPg ){
33067       int rc;
33068       rc = pCache->xStress(pCache->pStress, pPg);
33069       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
33070         return rc;
33071       }
33072     }
33073
33074     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
33075   }
33076
33077   if( pPage ){
33078     if( !pPage->pData ){
33079       memset(pPage, 0, sizeof(PgHdr));
33080       pPage->pData = (void *)&pPage[1];
33081       pPage->pExtra = (void*)&((char *)pPage->pData)[pCache->szPage];
33082       memset(pPage->pExtra, 0, pCache->szExtra);
33083       pPage->pCache = pCache;
33084       pPage->pgno = pgno;
33085     }
33086     assert( pPage->pCache==pCache );
33087     assert( pPage->pgno==pgno );
33088     assert( pPage->pData==(void *)&pPage[1] );
33089     assert( pPage->pExtra==(void *)&((char *)&pPage[1])[pCache->szPage] );
33090
33091     if( 0==pPage->nRef ){
33092       pCache->nRef++;
33093     }
33094     pPage->nRef++;
33095     if( pgno==1 ){
33096       pCache->pPage1 = pPage;
33097     }
33098   }
33099   *ppPage = pPage;
33100   return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
33101 }
33102
33103 /*
33104 ** Decrement the reference count on a page. If the page is clean and the
33105 ** reference count drops to 0, then it is made elible for recycling.
33106 */
33107 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
33108   assert( p->nRef>0 );
33109   p->nRef--;
33110   if( p->nRef==0 ){
33111     PCache *pCache = p->pCache;
33112     pCache->nRef--;
33113     if( (p->flags&PGHDR_DIRTY)==0 ){
33114       pcacheUnpin(p);
33115     }else{
33116       /* Move the page to the head of the dirty list. */
33117       pcacheRemoveFromDirtyList(p);
33118       pcacheAddToDirtyList(p);
33119     }
33120   }
33121 }
33122
33123 /*
33124 ** Increase the reference count of a supplied page by 1.
33125 */
33126 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
33127   assert(p->nRef>0);
33128   p->nRef++;
33129 }
33130
33131 /*
33132 ** Drop a page from the cache. There must be exactly one reference to the
33133 ** page. This function deletes that reference, so after it returns the
33134 ** page pointed to by p is invalid.
33135 */
33136 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
33137   PCache *pCache;
33138   assert( p->nRef==1 );
33139   if( p->flags&PGHDR_DIRTY ){
33140     pcacheRemoveFromDirtyList(p);
33141   }
33142   pCache = p->pCache;
33143   pCache->nRef--;
33144   if( p->pgno==1 ){
33145     pCache->pPage1 = 0;
33146   }
33147   sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
33148 }
33149
33150 /*
33151 ** Make sure the page is marked as dirty. If it isn't dirty already,
33152 ** make it so.
33153 */
33154 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
33155   p->flags &= ~PGHDR_DONT_WRITE;
33156   assert( p->nRef>0 );
33157   if( 0==(p->flags & PGHDR_DIRTY) ){
33158     p->flags |= PGHDR_DIRTY;
33159     pcacheAddToDirtyList( p);
33160   }
33161 }
33162
33163 /*
33164 ** Make sure the page is marked as clean. If it isn't clean already,
33165 ** make it so.
33166 */
33167 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
33168   if( (p->flags & PGHDR_DIRTY) ){
33169     pcacheRemoveFromDirtyList(p);
33170     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
33171     if( p->nRef==0 ){
33172       pcacheUnpin(p);
33173     }
33174   }
33175 }
33176
33177 /*
33178 ** Make every page in the cache clean.
33179 */
33180 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
33181   PgHdr *p;
33182   while( (p = pCache->pDirty)!=0 ){
33183     sqlite3PcacheMakeClean(p);
33184   }
33185 }
33186
33187 /*
33188 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
33189 */
33190 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
33191   PgHdr *p;
33192   for(p=pCache->pDirty; p; p=p->pDirtyNext){
33193     p->flags &= ~PGHDR_NEED_SYNC;
33194   }
33195   pCache->pSynced = pCache->pDirtyTail;
33196 }
33197
33198 /*
33199 ** Change the page number of page p to newPgno. 
33200 */
33201 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
33202   PCache *pCache = p->pCache;
33203   assert( p->nRef>0 );
33204   assert( newPgno>0 );
33205   sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
33206   p->pgno = newPgno;
33207   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
33208     pcacheRemoveFromDirtyList(p);
33209     pcacheAddToDirtyList(p);
33210   }
33211 }
33212
33213 /*
33214 ** Drop every cache entry whose page number is greater than "pgno". The
33215 ** caller must ensure that there are no outstanding references to any pages
33216 ** other than page 1 with a page number greater than pgno.
33217 **
33218 ** If there is a reference to page 1 and the pgno parameter passed to this
33219 ** function is 0, then the data area associated with page 1 is zeroed, but
33220 ** the page object is not dropped.
33221 */
33222 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
33223   if( pCache->pCache ){
33224     PgHdr *p;
33225     PgHdr *pNext;
33226     for(p=pCache->pDirty; p; p=pNext){
33227       pNext = p->pDirtyNext;
33228       /* This routine never gets call with a positive pgno except right
33229       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
33230       ** it must be that pgno==0.
33231       */
33232       assert( p->pgno>0 );
33233       if( ALWAYS(p->pgno>pgno) ){
33234         assert( p->flags&PGHDR_DIRTY );
33235         sqlite3PcacheMakeClean(p);
33236       }
33237     }
33238     if( pgno==0 && pCache->pPage1 ){
33239       memset(pCache->pPage1->pData, 0, pCache->szPage);
33240       pgno = 1;
33241     }
33242     sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
33243   }
33244 }
33245
33246 /*
33247 ** Close a cache.
33248 */
33249 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
33250   if( pCache->pCache ){
33251     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
33252   }
33253 }
33254
33255 /* 
33256 ** Discard the contents of the cache.
33257 */
33258 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
33259   sqlite3PcacheTruncate(pCache, 0);
33260 }
33261
33262 /*
33263 ** Merge two lists of pages connected by pDirty and in pgno order.
33264 ** Do not both fixing the pDirtyPrev pointers.
33265 */
33266 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
33267   PgHdr result, *pTail;
33268   pTail = &result;
33269   while( pA && pB ){
33270     if( pA->pgno<pB->pgno ){
33271       pTail->pDirty = pA;
33272       pTail = pA;
33273       pA = pA->pDirty;
33274     }else{
33275       pTail->pDirty = pB;
33276       pTail = pB;
33277       pB = pB->pDirty;
33278     }
33279   }
33280   if( pA ){
33281     pTail->pDirty = pA;
33282   }else if( pB ){
33283     pTail->pDirty = pB;
33284   }else{
33285     pTail->pDirty = 0;
33286   }
33287   return result.pDirty;
33288 }
33289
33290 /*
33291 ** Sort the list of pages in accending order by pgno.  Pages are
33292 ** connected by pDirty pointers.  The pDirtyPrev pointers are
33293 ** corrupted by this sort.
33294 **
33295 ** Since there cannot be more than 2^31 distinct pages in a database,
33296 ** there cannot be more than 31 buckets required by the merge sorter.
33297 ** One extra bucket is added to catch overflow in case something
33298 ** ever changes to make the previous sentence incorrect.
33299 */
33300 #define N_SORT_BUCKET  32
33301 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
33302   PgHdr *a[N_SORT_BUCKET], *p;
33303   int i;
33304   memset(a, 0, sizeof(a));
33305   while( pIn ){
33306     p = pIn;
33307     pIn = p->pDirty;
33308     p->pDirty = 0;
33309     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
33310       if( a[i]==0 ){
33311         a[i] = p;
33312         break;
33313       }else{
33314         p = pcacheMergeDirtyList(a[i], p);
33315         a[i] = 0;
33316       }
33317     }
33318     if( NEVER(i==N_SORT_BUCKET-1) ){
33319       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
33320       ** the input list.  But that is impossible.
33321       */
33322       a[i] = pcacheMergeDirtyList(a[i], p);
33323     }
33324   }
33325   p = a[0];
33326   for(i=1; i<N_SORT_BUCKET; i++){
33327     p = pcacheMergeDirtyList(p, a[i]);
33328   }
33329   return p;
33330 }
33331
33332 /*
33333 ** Return a list of all dirty pages in the cache, sorted by page number.
33334 */
33335 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
33336   PgHdr *p;
33337   for(p=pCache->pDirty; p; p=p->pDirtyNext){
33338     p->pDirty = p->pDirtyNext;
33339   }
33340   return pcacheSortDirtyList(pCache->pDirty);
33341 }
33342
33343 /* 
33344 ** Return the total number of referenced pages held by the cache.
33345 */
33346 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
33347   return pCache->nRef;
33348 }
33349
33350 /*
33351 ** Return the number of references to the page supplied as an argument.
33352 */
33353 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
33354   return p->nRef;
33355 }
33356
33357 /* 
33358 ** Return the total number of pages in the cache.
33359 */
33360 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
33361   int nPage = 0;
33362   if( pCache->pCache ){
33363     nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
33364   }
33365   return nPage;
33366 }
33367
33368 #ifdef SQLITE_TEST
33369 /*
33370 ** Get the suggested cache-size value.
33371 */
33372 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
33373   return pCache->nMax;
33374 }
33375 #endif
33376
33377 /*
33378 ** Set the suggested cache-size value.
33379 */
33380 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
33381   pCache->nMax = mxPage;
33382   if( pCache->pCache ){
33383     sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
33384   }
33385 }
33386
33387 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
33388 /*
33389 ** For all dirty pages currently in the cache, invoke the specified
33390 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
33391 ** defined.
33392 */
33393 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
33394   PgHdr *pDirty;
33395   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
33396     xIter(pDirty);
33397   }
33398 }
33399 #endif
33400
33401 /************** End of pcache.c **********************************************/
33402 /************** Begin file pcache1.c *****************************************/
33403 /*
33404 ** 2008 November 05
33405 **
33406 ** The author disclaims copyright to this source code.  In place of
33407 ** a legal notice, here is a blessing:
33408 **
33409 **    May you do good and not evil.
33410 **    May you find forgiveness for yourself and forgive others.
33411 **    May you share freely, never taking more than you give.
33412 **
33413 *************************************************************************
33414 **
33415 ** This file implements the default page cache implementation (the
33416 ** sqlite3_pcache interface). It also contains part of the implementation
33417 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
33418 ** If the default page cache implementation is overriden, then neither of
33419 ** these two features are available.
33420 */
33421
33422
33423 typedef struct PCache1 PCache1;
33424 typedef struct PgHdr1 PgHdr1;
33425 typedef struct PgFreeslot PgFreeslot;
33426 typedef struct PGroup PGroup;
33427
33428 /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set 
33429 ** of one or more PCaches that are able to recycle each others unpinned
33430 ** pages when they are under memory pressure.  A PGroup is an instance of
33431 ** the following object.
33432 **
33433 ** This page cache implementation works in one of two modes:
33434 **
33435 **   (1)  Every PCache is the sole member of its own PGroup.  There is
33436 **        one PGroup per PCache.
33437 **
33438 **   (2)  There is a single global PGroup that all PCaches are a member
33439 **        of.
33440 **
33441 ** Mode 1 uses more memory (since PCache instances are not able to rob
33442 ** unused pages from other PCaches) but it also operates without a mutex,
33443 ** and is therefore often faster.  Mode 2 requires a mutex in order to be
33444 ** threadsafe, but is able recycle pages more efficient.
33445 **
33446 ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
33447 ** PGroup which is the pcache1.grp global variable and its mutex is
33448 ** SQLITE_MUTEX_STATIC_LRU.
33449 */
33450 struct PGroup {
33451   sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
33452   int nMaxPage;                  /* Sum of nMax for purgeable caches */
33453   int nMinPage;                  /* Sum of nMin for purgeable caches */
33454   int mxPinned;                  /* nMaxpage + 10 - nMinPage */
33455   int nCurrentPage;              /* Number of purgeable pages allocated */
33456   PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
33457 };
33458
33459 /* Each page cache is an instance of the following object.  Every
33460 ** open database file (including each in-memory database and each
33461 ** temporary or transient database) has a single page cache which
33462 ** is an instance of this object.
33463 **
33464 ** Pointers to structures of this type are cast and returned as 
33465 ** opaque sqlite3_pcache* handles.
33466 */
33467 struct PCache1 {
33468   /* Cache configuration parameters. Page size (szPage) and the purgeable
33469   ** flag (bPurgeable) are set when the cache is created. nMax may be 
33470   ** modified at any time by a call to the pcache1CacheSize() method.
33471   ** The PGroup mutex must be held when accessing nMax.
33472   */
33473   PGroup *pGroup;                     /* PGroup this cache belongs to */
33474   int szPage;                         /* Size of allocated pages in bytes */
33475   int bPurgeable;                     /* True if cache is purgeable */
33476   unsigned int nMin;                  /* Minimum number of pages reserved */
33477   unsigned int nMax;                  /* Configured "cache_size" value */
33478   unsigned int n90pct;                /* nMax*9/10 */
33479
33480   /* Hash table of all pages. The following variables may only be accessed
33481   ** when the accessor is holding the PGroup mutex.
33482   */
33483   unsigned int nRecyclable;           /* Number of pages in the LRU list */
33484   unsigned int nPage;                 /* Total number of pages in apHash */
33485   unsigned int nHash;                 /* Number of slots in apHash[] */
33486   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
33487
33488   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
33489 };
33490
33491 /*
33492 ** Each cache entry is represented by an instance of the following 
33493 ** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated 
33494 ** directly before this structure in memory (see the PGHDR1_TO_PAGE() 
33495 ** macro below).
33496 */
33497 struct PgHdr1 {
33498   unsigned int iKey;             /* Key value (page number) */
33499   PgHdr1 *pNext;                 /* Next in hash table chain */
33500   PCache1 *pCache;               /* Cache that currently owns this page */
33501   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
33502   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
33503 };
33504
33505 /*
33506 ** Free slots in the allocator used to divide up the buffer provided using
33507 ** the SQLITE_CONFIG_PAGECACHE mechanism.
33508 */
33509 struct PgFreeslot {
33510   PgFreeslot *pNext;  /* Next free slot */
33511 };
33512
33513 /*
33514 ** Global data used by this cache.
33515 */
33516 static SQLITE_WSD struct PCacheGlobal {
33517   PGroup grp;                    /* The global PGroup for mode (2) */
33518
33519   /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
33520   ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
33521   ** fixed at sqlite3_initialize() time and do not require mutex protection.
33522   ** The nFreeSlot and pFree values do require mutex protection.
33523   */
33524   int isInit;                    /* True if initialized */
33525   int szSlot;                    /* Size of each free slot */
33526   int nSlot;                     /* The number of pcache slots */
33527   int nReserve;                  /* Try to keep nFreeSlot above this */
33528   void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
33529   /* Above requires no mutex.  Use mutex below for variable that follow. */
33530   sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
33531   int nFreeSlot;                 /* Number of unused pcache slots */
33532   PgFreeslot *pFree;             /* Free page blocks */
33533   /* The following value requires a mutex to change.  We skip the mutex on
33534   ** reading because (1) most platforms read a 32-bit integer atomically and
33535   ** (2) even if an incorrect value is read, no great harm is done since this
33536   ** is really just an optimization. */
33537   int bUnderPressure;            /* True if low on PAGECACHE memory */
33538 } pcache1_g;
33539
33540 /*
33541 ** All code in this file should access the global structure above via the
33542 ** alias "pcache1". This ensures that the WSD emulation is used when
33543 ** compiling for systems that do not support real WSD.
33544 */
33545 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
33546
33547 /*
33548 ** When a PgHdr1 structure is allocated, the associated PCache1.szPage
33549 ** bytes of data are located directly before it in memory (i.e. the total
33550 ** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
33551 ** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
33552 ** an argument and returns a pointer to the associated block of szPage
33553 ** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
33554 ** a pointer to a block of szPage bytes of data and the return value is
33555 ** a pointer to the associated PgHdr1 structure.
33556 **
33557 **   assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
33558 */
33559 #define PGHDR1_TO_PAGE(p)    (void*)(((char*)p) - p->pCache->szPage)
33560 #define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
33561
33562 /*
33563 ** Macros to enter and leave the PCache LRU mutex.
33564 */
33565 #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
33566 #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
33567
33568 /******************************************************************************/
33569 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
33570
33571 /*
33572 ** This function is called during initialization if a static buffer is 
33573 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
33574 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
33575 ** enough to contain 'n' buffers of 'sz' bytes each.
33576 **
33577 ** This routine is called from sqlite3_initialize() and so it is guaranteed
33578 ** to be serialized already.  There is no need for further mutexing.
33579 */
33580 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
33581   if( pcache1.isInit ){
33582     PgFreeslot *p;
33583     sz = ROUNDDOWN8(sz);
33584     pcache1.szSlot = sz;
33585     pcache1.nSlot = pcache1.nFreeSlot = n;
33586     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
33587     pcache1.pStart = pBuf;
33588     pcache1.pFree = 0;
33589     pcache1.bUnderPressure = 0;
33590     while( n-- ){
33591       p = (PgFreeslot*)pBuf;
33592       p->pNext = pcache1.pFree;
33593       pcache1.pFree = p;
33594       pBuf = (void*)&((char*)pBuf)[sz];
33595     }
33596     pcache1.pEnd = pBuf;
33597   }
33598 }
33599
33600 /*
33601 ** Malloc function used within this file to allocate space from the buffer
33602 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no 
33603 ** such buffer exists or there is no space left in it, this function falls 
33604 ** back to sqlite3Malloc().
33605 **
33606 ** Multiple threads can run this routine at the same time.  Global variables
33607 ** in pcache1 need to be protected via mutex.
33608 */
33609 static void *pcache1Alloc(int nByte){
33610   void *p = 0;
33611   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
33612   sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
33613   if( nByte<=pcache1.szSlot ){
33614     sqlite3_mutex_enter(pcache1.mutex);
33615     p = (PgHdr1 *)pcache1.pFree;
33616     if( p ){
33617       pcache1.pFree = pcache1.pFree->pNext;
33618       pcache1.nFreeSlot--;
33619       pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
33620       assert( pcache1.nFreeSlot>=0 );
33621       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
33622     }
33623     sqlite3_mutex_leave(pcache1.mutex);
33624   }
33625   if( p==0 ){
33626     /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
33627     ** it from sqlite3Malloc instead.
33628     */
33629     p = sqlite3Malloc(nByte);
33630     if( p ){
33631       int sz = sqlite3MallocSize(p);
33632       sqlite3_mutex_enter(pcache1.mutex);
33633       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
33634       sqlite3_mutex_leave(pcache1.mutex);
33635     }
33636     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
33637   }
33638   return p;
33639 }
33640
33641 /*
33642 ** Free an allocated buffer obtained from pcache1Alloc().
33643 */
33644 static void pcache1Free(void *p){
33645   if( p==0 ) return;
33646   if( p>=pcache1.pStart && p<pcache1.pEnd ){
33647     PgFreeslot *pSlot;
33648     sqlite3_mutex_enter(pcache1.mutex);
33649     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
33650     pSlot = (PgFreeslot*)p;
33651     pSlot->pNext = pcache1.pFree;
33652     pcache1.pFree = pSlot;
33653     pcache1.nFreeSlot++;
33654     pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
33655     assert( pcache1.nFreeSlot<=pcache1.nSlot );
33656     sqlite3_mutex_leave(pcache1.mutex);
33657   }else{
33658     int iSize;
33659     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
33660     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
33661     iSize = sqlite3MallocSize(p);
33662     sqlite3_mutex_enter(pcache1.mutex);
33663     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
33664     sqlite3_mutex_leave(pcache1.mutex);
33665     sqlite3_free(p);
33666   }
33667 }
33668
33669 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
33670 /*
33671 ** Return the size of a pcache allocation
33672 */
33673 static int pcache1MemSize(void *p){
33674   if( p>=pcache1.pStart && p<pcache1.pEnd ){
33675     return pcache1.szSlot;
33676   }else{
33677     int iSize;
33678     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
33679     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
33680     iSize = sqlite3MallocSize(p);
33681     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
33682     return iSize;
33683   }
33684 }
33685 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
33686
33687 /*
33688 ** Allocate a new page object initially associated with cache pCache.
33689 */
33690 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
33691   int nByte = sizeof(PgHdr1) + pCache->szPage;
33692   void *pPg = pcache1Alloc(nByte);
33693   PgHdr1 *p;
33694   if( pPg ){
33695     p = PAGE_TO_PGHDR1(pCache, pPg);
33696     if( pCache->bPurgeable ){
33697       pCache->pGroup->nCurrentPage++;
33698     }
33699   }else{
33700     p = 0;
33701   }
33702   return p;
33703 }
33704
33705 /*
33706 ** Free a page object allocated by pcache1AllocPage().
33707 **
33708 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
33709 ** that the current implementation happens to never call this routine
33710 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
33711 */
33712 static void pcache1FreePage(PgHdr1 *p){
33713   if( ALWAYS(p) ){
33714     PCache1 *pCache = p->pCache;
33715     if( pCache->bPurgeable ){
33716       pCache->pGroup->nCurrentPage--;
33717     }
33718     pcache1Free(PGHDR1_TO_PAGE(p));
33719   }
33720 }
33721
33722 /*
33723 ** Malloc function used by SQLite to obtain space from the buffer configured
33724 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
33725 ** exists, this function falls back to sqlite3Malloc().
33726 */
33727 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
33728   return pcache1Alloc(sz);
33729 }
33730
33731 /*
33732 ** Free an allocated buffer obtained from sqlite3PageMalloc().
33733 */
33734 SQLITE_PRIVATE void sqlite3PageFree(void *p){
33735   pcache1Free(p);
33736 }
33737
33738
33739 /*
33740 ** Return true if it desirable to avoid allocating a new page cache
33741 ** entry.
33742 **
33743 ** If memory was allocated specifically to the page cache using
33744 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
33745 ** it is desirable to avoid allocating a new page cache entry because
33746 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
33747 ** for all page cache needs and we should not need to spill the
33748 ** allocation onto the heap.
33749 **
33750 ** Or, the heap is used for all page cache memory put the heap is
33751 ** under memory pressure, then again it is desirable to avoid
33752 ** allocating a new page cache entry in order to avoid stressing
33753 ** the heap even further.
33754 */
33755 static int pcache1UnderMemoryPressure(PCache1 *pCache){
33756   if( pcache1.nSlot && pCache->szPage<=pcache1.szSlot ){
33757     return pcache1.bUnderPressure;
33758   }else{
33759     return sqlite3HeapNearlyFull();
33760   }
33761 }
33762
33763 /******************************************************************************/
33764 /******** General Implementation Functions ************************************/
33765
33766 /*
33767 ** This function is used to resize the hash table used by the cache passed
33768 ** as the first argument.
33769 **
33770 ** The PCache mutex must be held when this function is called.
33771 */
33772 static int pcache1ResizeHash(PCache1 *p){
33773   PgHdr1 **apNew;
33774   unsigned int nNew;
33775   unsigned int i;
33776
33777   assert( sqlite3_mutex_held(p->pGroup->mutex) );
33778
33779   nNew = p->nHash*2;
33780   if( nNew<256 ){
33781     nNew = 256;
33782   }
33783
33784   pcache1LeaveMutex(p->pGroup);
33785   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
33786   apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
33787   if( p->nHash ){ sqlite3EndBenignMalloc(); }
33788   pcache1EnterMutex(p->pGroup);
33789   if( apNew ){
33790     memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
33791     for(i=0; i<p->nHash; i++){
33792       PgHdr1 *pPage;
33793       PgHdr1 *pNext = p->apHash[i];
33794       while( (pPage = pNext)!=0 ){
33795         unsigned int h = pPage->iKey % nNew;
33796         pNext = pPage->pNext;
33797         pPage->pNext = apNew[h];
33798         apNew[h] = pPage;
33799       }
33800     }
33801     sqlite3_free(p->apHash);
33802     p->apHash = apNew;
33803     p->nHash = nNew;
33804   }
33805
33806   return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
33807 }
33808
33809 /*
33810 ** This function is used internally to remove the page pPage from the 
33811 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
33812 ** LRU list, then this function is a no-op.
33813 **
33814 ** The PGroup mutex must be held when this function is called.
33815 **
33816 ** If pPage is NULL then this routine is a no-op.
33817 */
33818 static void pcache1PinPage(PgHdr1 *pPage){
33819   PCache1 *pCache;
33820   PGroup *pGroup;
33821
33822   if( pPage==0 ) return;
33823   pCache = pPage->pCache;
33824   pGroup = pCache->pGroup;
33825   assert( sqlite3_mutex_held(pGroup->mutex) );
33826   if( pPage->pLruNext || pPage==pGroup->pLruTail ){
33827     if( pPage->pLruPrev ){
33828       pPage->pLruPrev->pLruNext = pPage->pLruNext;
33829     }
33830     if( pPage->pLruNext ){
33831       pPage->pLruNext->pLruPrev = pPage->pLruPrev;
33832     }
33833     if( pGroup->pLruHead==pPage ){
33834       pGroup->pLruHead = pPage->pLruNext;
33835     }
33836     if( pGroup->pLruTail==pPage ){
33837       pGroup->pLruTail = pPage->pLruPrev;
33838     }
33839     pPage->pLruNext = 0;
33840     pPage->pLruPrev = 0;
33841     pPage->pCache->nRecyclable--;
33842   }
33843 }
33844
33845
33846 /*
33847 ** Remove the page supplied as an argument from the hash table 
33848 ** (PCache1.apHash structure) that it is currently stored in.
33849 **
33850 ** The PGroup mutex must be held when this function is called.
33851 */
33852 static void pcache1RemoveFromHash(PgHdr1 *pPage){
33853   unsigned int h;
33854   PCache1 *pCache = pPage->pCache;
33855   PgHdr1 **pp;
33856
33857   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
33858   h = pPage->iKey % pCache->nHash;
33859   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
33860   *pp = (*pp)->pNext;
33861
33862   pCache->nPage--;
33863 }
33864
33865 /*
33866 ** If there are currently more than nMaxPage pages allocated, try
33867 ** to recycle pages to reduce the number allocated to nMaxPage.
33868 */
33869 static void pcache1EnforceMaxPage(PGroup *pGroup){
33870   assert( sqlite3_mutex_held(pGroup->mutex) );
33871   while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
33872     PgHdr1 *p = pGroup->pLruTail;
33873     assert( p->pCache->pGroup==pGroup );
33874     pcache1PinPage(p);
33875     pcache1RemoveFromHash(p);
33876     pcache1FreePage(p);
33877   }
33878 }
33879
33880 /*
33881 ** Discard all pages from cache pCache with a page number (key value) 
33882 ** greater than or equal to iLimit. Any pinned pages that meet this 
33883 ** criteria are unpinned before they are discarded.
33884 **
33885 ** The PCache mutex must be held when this function is called.
33886 */
33887 static void pcache1TruncateUnsafe(
33888   PCache1 *pCache,             /* The cache to truncate */
33889   unsigned int iLimit          /* Drop pages with this pgno or larger */
33890 ){
33891   TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
33892   unsigned int h;
33893   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
33894   for(h=0; h<pCache->nHash; h++){
33895     PgHdr1 **pp = &pCache->apHash[h]; 
33896     PgHdr1 *pPage;
33897     while( (pPage = *pp)!=0 ){
33898       if( pPage->iKey>=iLimit ){
33899         pCache->nPage--;
33900         *pp = pPage->pNext;
33901         pcache1PinPage(pPage);
33902         pcache1FreePage(pPage);
33903       }else{
33904         pp = &pPage->pNext;
33905         TESTONLY( nPage++; )
33906       }
33907     }
33908   }
33909   assert( pCache->nPage==nPage );
33910 }
33911
33912 /******************************************************************************/
33913 /******** sqlite3_pcache Methods **********************************************/
33914
33915 /*
33916 ** Implementation of the sqlite3_pcache.xInit method.
33917 */
33918 static int pcache1Init(void *NotUsed){
33919   UNUSED_PARAMETER(NotUsed);
33920   assert( pcache1.isInit==0 );
33921   memset(&pcache1, 0, sizeof(pcache1));
33922   if( sqlite3GlobalConfig.bCoreMutex ){
33923     pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
33924     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
33925   }
33926   pcache1.grp.mxPinned = 10;
33927   pcache1.isInit = 1;
33928   return SQLITE_OK;
33929 }
33930
33931 /*
33932 ** Implementation of the sqlite3_pcache.xShutdown method.
33933 ** Note that the static mutex allocated in xInit does 
33934 ** not need to be freed.
33935 */
33936 static void pcache1Shutdown(void *NotUsed){
33937   UNUSED_PARAMETER(NotUsed);
33938   assert( pcache1.isInit!=0 );
33939   memset(&pcache1, 0, sizeof(pcache1));
33940 }
33941
33942 /*
33943 ** Implementation of the sqlite3_pcache.xCreate method.
33944 **
33945 ** Allocate a new cache.
33946 */
33947 static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
33948   PCache1 *pCache;      /* The newly created page cache */
33949   PGroup *pGroup;       /* The group the new page cache will belong to */
33950   int sz;               /* Bytes of memory required to allocate the new cache */
33951
33952   /*
33953   ** The seperateCache variable is true if each PCache has its own private
33954   ** PGroup.  In other words, separateCache is true for mode (1) where no
33955   ** mutexing is required.
33956   **
33957   **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
33958   **
33959   **   *  Always use a unified cache in single-threaded applications
33960   **
33961   **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
33962   **      use separate caches (mode-1)
33963   */
33964 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
33965   const int separateCache = 0;
33966 #else
33967   int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
33968 #endif
33969
33970   sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
33971   pCache = (PCache1 *)sqlite3_malloc(sz);
33972   if( pCache ){
33973     memset(pCache, 0, sz);
33974     if( separateCache ){
33975       pGroup = (PGroup*)&pCache[1];
33976       pGroup->mxPinned = 10;
33977     }else{
33978       pGroup = &pcache1_g.grp;
33979     }
33980     pCache->pGroup = pGroup;
33981     pCache->szPage = szPage;
33982     pCache->bPurgeable = (bPurgeable ? 1 : 0);
33983     if( bPurgeable ){
33984       pCache->nMin = 10;
33985       pcache1EnterMutex(pGroup);
33986       pGroup->nMinPage += pCache->nMin;
33987       pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
33988       pcache1LeaveMutex(pGroup);
33989     }
33990   }
33991   return (sqlite3_pcache *)pCache;
33992 }
33993
33994 /*
33995 ** Implementation of the sqlite3_pcache.xCachesize method. 
33996 **
33997 ** Configure the cache_size limit for a cache.
33998 */
33999 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
34000   PCache1 *pCache = (PCache1 *)p;
34001   if( pCache->bPurgeable ){
34002     PGroup *pGroup = pCache->pGroup;
34003     pcache1EnterMutex(pGroup);
34004     pGroup->nMaxPage += (nMax - pCache->nMax);
34005     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
34006     pCache->nMax = nMax;
34007     pCache->n90pct = pCache->nMax*9/10;
34008     pcache1EnforceMaxPage(pGroup);
34009     pcache1LeaveMutex(pGroup);
34010   }
34011 }
34012
34013 /*
34014 ** Implementation of the sqlite3_pcache.xPagecount method. 
34015 */
34016 static int pcache1Pagecount(sqlite3_pcache *p){
34017   int n;
34018   PCache1 *pCache = (PCache1*)p;
34019   pcache1EnterMutex(pCache->pGroup);
34020   n = pCache->nPage;
34021   pcache1LeaveMutex(pCache->pGroup);
34022   return n;
34023 }
34024
34025 /*
34026 ** Implementation of the sqlite3_pcache.xFetch method. 
34027 **
34028 ** Fetch a page by key value.
34029 **
34030 ** Whether or not a new page may be allocated by this function depends on
34031 ** the value of the createFlag argument.  0 means do not allocate a new
34032 ** page.  1 means allocate a new page if space is easily available.  2 
34033 ** means to try really hard to allocate a new page.
34034 **
34035 ** For a non-purgeable cache (a cache used as the storage for an in-memory
34036 ** database) there is really no difference between createFlag 1 and 2.  So
34037 ** the calling function (pcache.c) will never have a createFlag of 1 on
34038 ** a non-purgable cache.
34039 **
34040 ** There are three different approaches to obtaining space for a page,
34041 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
34042 **
34043 **   1. Regardless of the value of createFlag, the cache is searched for a 
34044 **      copy of the requested page. If one is found, it is returned.
34045 **
34046 **   2. If createFlag==0 and the page is not already in the cache, NULL is
34047 **      returned.
34048 **
34049 **   3. If createFlag is 1, and the page is not already in the cache, then
34050 **      return NULL (do not allocate a new page) if any of the following
34051 **      conditions are true:
34052 **
34053 **       (a) the number of pages pinned by the cache is greater than
34054 **           PCache1.nMax, or
34055 **
34056 **       (b) the number of pages pinned by the cache is greater than
34057 **           the sum of nMax for all purgeable caches, less the sum of 
34058 **           nMin for all other purgeable caches, or
34059 **
34060 **   4. If none of the first three conditions apply and the cache is marked
34061 **      as purgeable, and if one of the following is true:
34062 **
34063 **       (a) The number of pages allocated for the cache is already 
34064 **           PCache1.nMax, or
34065 **
34066 **       (b) The number of pages allocated for all purgeable caches is
34067 **           already equal to or greater than the sum of nMax for all
34068 **           purgeable caches,
34069 **
34070 **       (c) The system is under memory pressure and wants to avoid
34071 **           unnecessary pages cache entry allocations
34072 **
34073 **      then attempt to recycle a page from the LRU list. If it is the right
34074 **      size, return the recycled buffer. Otherwise, free the buffer and
34075 **      proceed to step 5. 
34076 **
34077 **   5. Otherwise, allocate and return a new page buffer.
34078 */
34079 static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
34080   int nPinned;
34081   PCache1 *pCache = (PCache1 *)p;
34082   PGroup *pGroup;
34083   PgHdr1 *pPage = 0;
34084
34085   assert( pCache->bPurgeable || createFlag!=1 );
34086   assert( pCache->bPurgeable || pCache->nMin==0 );
34087   assert( pCache->bPurgeable==0 || pCache->nMin==10 );
34088   assert( pCache->nMin==0 || pCache->bPurgeable );
34089   pcache1EnterMutex(pGroup = pCache->pGroup);
34090
34091   /* Step 1: Search the hash table for an existing entry. */
34092   if( pCache->nHash>0 ){
34093     unsigned int h = iKey % pCache->nHash;
34094     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
34095   }
34096
34097   /* Step 2: Abort if no existing page is found and createFlag is 0 */
34098   if( pPage || createFlag==0 ){
34099     pcache1PinPage(pPage);
34100     goto fetch_out;
34101   }
34102
34103   /* The pGroup local variable will normally be initialized by the
34104   ** pcache1EnterMutex() macro above.  But if SQLITE_MUTEX_OMIT is defined,
34105   ** then pcache1EnterMutex() is a no-op, so we have to initialize the
34106   ** local variable here.  Delaying the initialization of pGroup is an
34107   ** optimization:  The common case is to exit the module before reaching
34108   ** this point.
34109   */
34110 #ifdef SQLITE_MUTEX_OMIT
34111   pGroup = pCache->pGroup;
34112 #endif
34113
34114
34115   /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
34116   nPinned = pCache->nPage - pCache->nRecyclable;
34117   assert( nPinned>=0 );
34118   assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
34119   assert( pCache->n90pct == pCache->nMax*9/10 );
34120   if( createFlag==1 && (
34121         nPinned>=pGroup->mxPinned
34122      || nPinned>=(int)pCache->n90pct
34123      || pcache1UnderMemoryPressure(pCache)
34124   )){
34125     goto fetch_out;
34126   }
34127
34128   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
34129     goto fetch_out;
34130   }
34131
34132   /* Step 4. Try to recycle a page. */
34133   if( pCache->bPurgeable && pGroup->pLruTail && (
34134          (pCache->nPage+1>=pCache->nMax)
34135       || pGroup->nCurrentPage>=pGroup->nMaxPage
34136       || pcache1UnderMemoryPressure(pCache)
34137   )){
34138     PCache1 *pOtherCache;
34139     pPage = pGroup->pLruTail;
34140     pcache1RemoveFromHash(pPage);
34141     pcache1PinPage(pPage);
34142     if( (pOtherCache = pPage->pCache)->szPage!=pCache->szPage ){
34143       pcache1FreePage(pPage);
34144       pPage = 0;
34145     }else{
34146       pGroup->nCurrentPage -= 
34147                (pOtherCache->bPurgeable - pCache->bPurgeable);
34148     }
34149   }
34150
34151   /* Step 5. If a usable page buffer has still not been found, 
34152   ** attempt to allocate a new one. 
34153   */
34154   if( !pPage ){
34155     if( createFlag==1 ) sqlite3BeginBenignMalloc();
34156     pcache1LeaveMutex(pGroup);
34157     pPage = pcache1AllocPage(pCache);
34158     pcache1EnterMutex(pGroup);
34159     if( createFlag==1 ) sqlite3EndBenignMalloc();
34160   }
34161
34162   if( pPage ){
34163     unsigned int h = iKey % pCache->nHash;
34164     pCache->nPage++;
34165     pPage->iKey = iKey;
34166     pPage->pNext = pCache->apHash[h];
34167     pPage->pCache = pCache;
34168     pPage->pLruPrev = 0;
34169     pPage->pLruNext = 0;
34170     *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
34171     pCache->apHash[h] = pPage;
34172   }
34173
34174 fetch_out:
34175   if( pPage && iKey>pCache->iMaxKey ){
34176     pCache->iMaxKey = iKey;
34177   }
34178   pcache1LeaveMutex(pGroup);
34179   return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
34180 }
34181
34182
34183 /*
34184 ** Implementation of the sqlite3_pcache.xUnpin method.
34185 **
34186 ** Mark a page as unpinned (eligible for asynchronous recycling).
34187 */
34188 static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
34189   PCache1 *pCache = (PCache1 *)p;
34190   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
34191   PGroup *pGroup = pCache->pGroup;
34192  
34193   assert( pPage->pCache==pCache );
34194   pcache1EnterMutex(pGroup);
34195
34196   /* It is an error to call this function if the page is already 
34197   ** part of the PGroup LRU list.
34198   */
34199   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
34200   assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
34201
34202   if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
34203     pcache1RemoveFromHash(pPage);
34204     pcache1FreePage(pPage);
34205   }else{
34206     /* Add the page to the PGroup LRU list. */
34207     if( pGroup->pLruHead ){
34208       pGroup->pLruHead->pLruPrev = pPage;
34209       pPage->pLruNext = pGroup->pLruHead;
34210       pGroup->pLruHead = pPage;
34211     }else{
34212       pGroup->pLruTail = pPage;
34213       pGroup->pLruHead = pPage;
34214     }
34215     pCache->nRecyclable++;
34216   }
34217
34218   pcache1LeaveMutex(pCache->pGroup);
34219 }
34220
34221 /*
34222 ** Implementation of the sqlite3_pcache.xRekey method. 
34223 */
34224 static void pcache1Rekey(
34225   sqlite3_pcache *p,
34226   void *pPg,
34227   unsigned int iOld,
34228   unsigned int iNew
34229 ){
34230   PCache1 *pCache = (PCache1 *)p;
34231   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
34232   PgHdr1 **pp;
34233   unsigned int h; 
34234   assert( pPage->iKey==iOld );
34235   assert( pPage->pCache==pCache );
34236
34237   pcache1EnterMutex(pCache->pGroup);
34238
34239   h = iOld%pCache->nHash;
34240   pp = &pCache->apHash[h];
34241   while( (*pp)!=pPage ){
34242     pp = &(*pp)->pNext;
34243   }
34244   *pp = pPage->pNext;
34245
34246   h = iNew%pCache->nHash;
34247   pPage->iKey = iNew;
34248   pPage->pNext = pCache->apHash[h];
34249   pCache->apHash[h] = pPage;
34250   if( iNew>pCache->iMaxKey ){
34251     pCache->iMaxKey = iNew;
34252   }
34253
34254   pcache1LeaveMutex(pCache->pGroup);
34255 }
34256
34257 /*
34258 ** Implementation of the sqlite3_pcache.xTruncate method. 
34259 **
34260 ** Discard all unpinned pages in the cache with a page number equal to
34261 ** or greater than parameter iLimit. Any pinned pages with a page number
34262 ** equal to or greater than iLimit are implicitly unpinned.
34263 */
34264 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
34265   PCache1 *pCache = (PCache1 *)p;
34266   pcache1EnterMutex(pCache->pGroup);
34267   if( iLimit<=pCache->iMaxKey ){
34268     pcache1TruncateUnsafe(pCache, iLimit);
34269     pCache->iMaxKey = iLimit-1;
34270   }
34271   pcache1LeaveMutex(pCache->pGroup);
34272 }
34273
34274 /*
34275 ** Implementation of the sqlite3_pcache.xDestroy method. 
34276 **
34277 ** Destroy a cache allocated using pcache1Create().
34278 */
34279 static void pcache1Destroy(sqlite3_pcache *p){
34280   PCache1 *pCache = (PCache1 *)p;
34281   PGroup *pGroup = pCache->pGroup;
34282   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
34283   pcache1EnterMutex(pGroup);
34284   pcache1TruncateUnsafe(pCache, 0);
34285   pGroup->nMaxPage -= pCache->nMax;
34286   pGroup->nMinPage -= pCache->nMin;
34287   pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
34288   pcache1EnforceMaxPage(pGroup);
34289   pcache1LeaveMutex(pGroup);
34290   sqlite3_free(pCache->apHash);
34291   sqlite3_free(pCache);
34292 }
34293
34294 /*
34295 ** This function is called during initialization (sqlite3_initialize()) to
34296 ** install the default pluggable cache module, assuming the user has not
34297 ** already provided an alternative.
34298 */
34299 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
34300   static const sqlite3_pcache_methods defaultMethods = {
34301     0,                       /* pArg */
34302     pcache1Init,             /* xInit */
34303     pcache1Shutdown,         /* xShutdown */
34304     pcache1Create,           /* xCreate */
34305     pcache1Cachesize,        /* xCachesize */
34306     pcache1Pagecount,        /* xPagecount */
34307     pcache1Fetch,            /* xFetch */
34308     pcache1Unpin,            /* xUnpin */
34309     pcache1Rekey,            /* xRekey */
34310     pcache1Truncate,         /* xTruncate */
34311     pcache1Destroy           /* xDestroy */
34312   };
34313   sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
34314 }
34315
34316 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
34317 /*
34318 ** This function is called to free superfluous dynamically allocated memory
34319 ** held by the pager system. Memory in use by any SQLite pager allocated
34320 ** by the current thread may be sqlite3_free()ed.
34321 **
34322 ** nReq is the number of bytes of memory required. Once this much has
34323 ** been released, the function returns. The return value is the total number 
34324 ** of bytes of memory released.
34325 */
34326 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
34327   int nFree = 0;
34328   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
34329   assert( sqlite3_mutex_notheld(pcache1.mutex) );
34330   if( pcache1.pStart==0 ){
34331     PgHdr1 *p;
34332     pcache1EnterMutex(&pcache1.grp);
34333     while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
34334       nFree += pcache1MemSize(PGHDR1_TO_PAGE(p));
34335       pcache1PinPage(p);
34336       pcache1RemoveFromHash(p);
34337       pcache1FreePage(p);
34338     }
34339     pcache1LeaveMutex(&pcache1.grp);
34340   }
34341   return nFree;
34342 }
34343 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
34344
34345 #ifdef SQLITE_TEST
34346 /*
34347 ** This function is used by test procedures to inspect the internal state
34348 ** of the global cache.
34349 */
34350 SQLITE_PRIVATE void sqlite3PcacheStats(
34351   int *pnCurrent,      /* OUT: Total number of pages cached */
34352   int *pnMax,          /* OUT: Global maximum cache size */
34353   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
34354   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
34355 ){
34356   PgHdr1 *p;
34357   int nRecyclable = 0;
34358   for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
34359     nRecyclable++;
34360   }
34361   *pnCurrent = pcache1.grp.nCurrentPage;
34362   *pnMax = pcache1.grp.nMaxPage;
34363   *pnMin = pcache1.grp.nMinPage;
34364   *pnRecyclable = nRecyclable;
34365 }
34366 #endif
34367
34368 /************** End of pcache1.c *********************************************/
34369 /************** Begin file rowset.c ******************************************/
34370 /*
34371 ** 2008 December 3
34372 **
34373 ** The author disclaims copyright to this source code.  In place of
34374 ** a legal notice, here is a blessing:
34375 **
34376 **    May you do good and not evil.
34377 **    May you find forgiveness for yourself and forgive others.
34378 **    May you share freely, never taking more than you give.
34379 **
34380 *************************************************************************
34381 **
34382 ** This module implements an object we call a "RowSet".
34383 **
34384 ** The RowSet object is a collection of rowids.  Rowids
34385 ** are inserted into the RowSet in an arbitrary order.  Inserts
34386 ** can be intermixed with tests to see if a given rowid has been
34387 ** previously inserted into the RowSet.
34388 **
34389 ** After all inserts are finished, it is possible to extract the
34390 ** elements of the RowSet in sorted order.  Once this extraction
34391 ** process has started, no new elements may be inserted.
34392 **
34393 ** Hence, the primitive operations for a RowSet are:
34394 **
34395 **    CREATE
34396 **    INSERT
34397 **    TEST
34398 **    SMALLEST
34399 **    DESTROY
34400 **
34401 ** The CREATE and DESTROY primitives are the constructor and destructor,
34402 ** obviously.  The INSERT primitive adds a new element to the RowSet.
34403 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
34404 ** extracts the least value from the RowSet.
34405 **
34406 ** The INSERT primitive might allocate additional memory.  Memory is
34407 ** allocated in chunks so most INSERTs do no allocation.  There is an 
34408 ** upper bound on the size of allocated memory.  No memory is freed
34409 ** until DESTROY.
34410 **
34411 ** The TEST primitive includes a "batch" number.  The TEST primitive
34412 ** will only see elements that were inserted before the last change
34413 ** in the batch number.  In other words, if an INSERT occurs between
34414 ** two TESTs where the TESTs have the same batch nubmer, then the
34415 ** value added by the INSERT will not be visible to the second TEST.
34416 ** The initial batch number is zero, so if the very first TEST contains
34417 ** a non-zero batch number, it will see all prior INSERTs.
34418 **
34419 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
34420 ** that is attempted.
34421 **
34422 ** The cost of an INSERT is roughly constant.  (Sometime new memory
34423 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
34424 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
34425 ** The cost of a TEST using the same batch number is O(logN).  The cost
34426 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
34427 ** primitives are constant time.  The cost of DESTROY is O(N).
34428 **
34429 ** There is an added cost of O(N) when switching between TEST and
34430 ** SMALLEST primitives.
34431 */
34432
34433
34434 /*
34435 ** Target size for allocation chunks.
34436 */
34437 #define ROWSET_ALLOCATION_SIZE 1024
34438
34439 /*
34440 ** The number of rowset entries per allocation chunk.
34441 */
34442 #define ROWSET_ENTRY_PER_CHUNK  \
34443                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
34444
34445 /*
34446 ** Each entry in a RowSet is an instance of the following object.
34447 */
34448 struct RowSetEntry {            
34449   i64 v;                        /* ROWID value for this entry */
34450   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
34451   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
34452 };
34453
34454 /*
34455 ** RowSetEntry objects are allocated in large chunks (instances of the
34456 ** following structure) to reduce memory allocation overhead.  The
34457 ** chunks are kept on a linked list so that they can be deallocated
34458 ** when the RowSet is destroyed.
34459 */
34460 struct RowSetChunk {
34461   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
34462   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
34463 };
34464
34465 /*
34466 ** A RowSet in an instance of the following structure.
34467 **
34468 ** A typedef of this structure if found in sqliteInt.h.
34469 */
34470 struct RowSet {
34471   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
34472   sqlite3 *db;                   /* The database connection */
34473   struct RowSetEntry *pEntry;    /* List of entries using pRight */
34474   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
34475   struct RowSetEntry *pFresh;    /* Source of new entry objects */
34476   struct RowSetEntry *pTree;     /* Binary tree of entries */
34477   u16 nFresh;                    /* Number of objects on pFresh */
34478   u8 isSorted;                   /* True if pEntry is sorted */
34479   u8 iBatch;                     /* Current insert batch */
34480 };
34481
34482 /*
34483 ** Turn bulk memory into a RowSet object.  N bytes of memory
34484 ** are available at pSpace.  The db pointer is used as a memory context
34485 ** for any subsequent allocations that need to occur.
34486 ** Return a pointer to the new RowSet object.
34487 **
34488 ** It must be the case that N is sufficient to make a Rowset.  If not
34489 ** an assertion fault occurs.
34490 ** 
34491 ** If N is larger than the minimum, use the surplus as an initial
34492 ** allocation of entries available to be filled.
34493 */
34494 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
34495   RowSet *p;
34496   assert( N >= ROUND8(sizeof(*p)) );
34497   p = pSpace;
34498   p->pChunk = 0;
34499   p->db = db;
34500   p->pEntry = 0;
34501   p->pLast = 0;
34502   p->pTree = 0;
34503   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
34504   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
34505   p->isSorted = 1;
34506   p->iBatch = 0;
34507   return p;
34508 }
34509
34510 /*
34511 ** Deallocate all chunks from a RowSet.  This frees all memory that
34512 ** the RowSet has allocated over its lifetime.  This routine is
34513 ** the destructor for the RowSet.
34514 */
34515 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
34516   struct RowSetChunk *pChunk, *pNextChunk;
34517   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
34518     pNextChunk = pChunk->pNextChunk;
34519     sqlite3DbFree(p->db, pChunk);
34520   }
34521   p->pChunk = 0;
34522   p->nFresh = 0;
34523   p->pEntry = 0;
34524   p->pLast = 0;
34525   p->pTree = 0;
34526   p->isSorted = 1;
34527 }
34528
34529 /*
34530 ** Insert a new value into a RowSet.
34531 **
34532 ** The mallocFailed flag of the database connection is set if a
34533 ** memory allocation fails.
34534 */
34535 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
34536   struct RowSetEntry *pEntry;  /* The new entry */
34537   struct RowSetEntry *pLast;   /* The last prior entry */
34538   assert( p!=0 );
34539   if( p->nFresh==0 ){
34540     struct RowSetChunk *pNew;
34541     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
34542     if( pNew==0 ){
34543       return;
34544     }
34545     pNew->pNextChunk = p->pChunk;
34546     p->pChunk = pNew;
34547     p->pFresh = pNew->aEntry;
34548     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
34549   }
34550   pEntry = p->pFresh++;
34551   p->nFresh--;
34552   pEntry->v = rowid;
34553   pEntry->pRight = 0;
34554   pLast = p->pLast;
34555   if( pLast ){
34556     if( p->isSorted && rowid<=pLast->v ){
34557       p->isSorted = 0;
34558     }
34559     pLast->pRight = pEntry;
34560   }else{
34561     assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
34562     p->pEntry = pEntry;
34563   }
34564   p->pLast = pEntry;
34565 }
34566
34567 /*
34568 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
34569 **
34570 ** The input lists are connected via pRight pointers and are 
34571 ** assumed to each already be in sorted order.
34572 */
34573 static struct RowSetEntry *rowSetMerge(
34574   struct RowSetEntry *pA,    /* First sorted list to be merged */
34575   struct RowSetEntry *pB     /* Second sorted list to be merged */
34576 ){
34577   struct RowSetEntry head;
34578   struct RowSetEntry *pTail;
34579
34580   pTail = &head;
34581   while( pA && pB ){
34582     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
34583     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
34584     if( pA->v<pB->v ){
34585       pTail->pRight = pA;
34586       pA = pA->pRight;
34587       pTail = pTail->pRight;
34588     }else if( pB->v<pA->v ){
34589       pTail->pRight = pB;
34590       pB = pB->pRight;
34591       pTail = pTail->pRight;
34592     }else{
34593       pA = pA->pRight;
34594     }
34595   }
34596   if( pA ){
34597     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
34598     pTail->pRight = pA;
34599   }else{
34600     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
34601     pTail->pRight = pB;
34602   }
34603   return head.pRight;
34604 }
34605
34606 /*
34607 ** Sort all elements on the pEntry list of the RowSet into ascending order.
34608 */ 
34609 static void rowSetSort(RowSet *p){
34610   unsigned int i;
34611   struct RowSetEntry *pEntry;
34612   struct RowSetEntry *aBucket[40];
34613
34614   assert( p->isSorted==0 );
34615   memset(aBucket, 0, sizeof(aBucket));
34616   while( p->pEntry ){
34617     pEntry = p->pEntry;
34618     p->pEntry = pEntry->pRight;
34619     pEntry->pRight = 0;
34620     for(i=0; aBucket[i]; i++){
34621       pEntry = rowSetMerge(aBucket[i], pEntry);
34622       aBucket[i] = 0;
34623     }
34624     aBucket[i] = pEntry;
34625   }
34626   pEntry = 0;
34627   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
34628     pEntry = rowSetMerge(pEntry, aBucket[i]);
34629   }
34630   p->pEntry = pEntry;
34631   p->pLast = 0;
34632   p->isSorted = 1;
34633 }
34634
34635
34636 /*
34637 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
34638 ** Convert this tree into a linked list connected by the pRight pointers
34639 ** and return pointers to the first and last elements of the new list.
34640 */
34641 static void rowSetTreeToList(
34642   struct RowSetEntry *pIn,         /* Root of the input tree */
34643   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
34644   struct RowSetEntry **ppLast      /* Write tail of the output list here */
34645 ){
34646   assert( pIn!=0 );
34647   if( pIn->pLeft ){
34648     struct RowSetEntry *p;
34649     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
34650     p->pRight = pIn;
34651   }else{
34652     *ppFirst = pIn;
34653   }
34654   if( pIn->pRight ){
34655     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
34656   }else{
34657     *ppLast = pIn;
34658   }
34659   assert( (*ppLast)->pRight==0 );
34660 }
34661
34662
34663 /*
34664 ** Convert a sorted list of elements (connected by pRight) into a binary
34665 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
34666 ** node taken from the head of *ppList.  A depth of 2 means a tree with
34667 ** three nodes.  And so forth.
34668 **
34669 ** Use as many entries from the input list as required and update the
34670 ** *ppList to point to the unused elements of the list.  If the input
34671 ** list contains too few elements, then construct an incomplete tree
34672 ** and leave *ppList set to NULL.
34673 **
34674 ** Return a pointer to the root of the constructed binary tree.
34675 */
34676 static struct RowSetEntry *rowSetNDeepTree(
34677   struct RowSetEntry **ppList,
34678   int iDepth
34679 ){
34680   struct RowSetEntry *p;         /* Root of the new tree */
34681   struct RowSetEntry *pLeft;     /* Left subtree */
34682   if( *ppList==0 ){
34683     return 0;
34684   }
34685   if( iDepth==1 ){
34686     p = *ppList;
34687     *ppList = p->pRight;
34688     p->pLeft = p->pRight = 0;
34689     return p;
34690   }
34691   pLeft = rowSetNDeepTree(ppList, iDepth-1);
34692   p = *ppList;
34693   if( p==0 ){
34694     return pLeft;
34695   }
34696   p->pLeft = pLeft;
34697   *ppList = p->pRight;
34698   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
34699   return p;
34700 }
34701
34702 /*
34703 ** Convert a sorted list of elements into a binary tree. Make the tree
34704 ** as deep as it needs to be in order to contain the entire list.
34705 */
34706 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
34707   int iDepth;           /* Depth of the tree so far */
34708   struct RowSetEntry *p;       /* Current tree root */
34709   struct RowSetEntry *pLeft;   /* Left subtree */
34710
34711   assert( pList!=0 );
34712   p = pList;
34713   pList = p->pRight;
34714   p->pLeft = p->pRight = 0;
34715   for(iDepth=1; pList; iDepth++){
34716     pLeft = p;
34717     p = pList;
34718     pList = p->pRight;
34719     p->pLeft = pLeft;
34720     p->pRight = rowSetNDeepTree(&pList, iDepth);
34721   }
34722   return p;
34723 }
34724
34725 /*
34726 ** Convert the list in p->pEntry into a sorted list if it is not
34727 ** sorted already.  If there is a binary tree on p->pTree, then
34728 ** convert it into a list too and merge it into the p->pEntry list.
34729 */
34730 static void rowSetToList(RowSet *p){
34731   if( !p->isSorted ){
34732     rowSetSort(p);
34733   }
34734   if( p->pTree ){
34735     struct RowSetEntry *pHead, *pTail;
34736     rowSetTreeToList(p->pTree, &pHead, &pTail);
34737     p->pTree = 0;
34738     p->pEntry = rowSetMerge(p->pEntry, pHead);
34739   }
34740 }
34741
34742 /*
34743 ** Extract the smallest element from the RowSet.
34744 ** Write the element into *pRowid.  Return 1 on success.  Return
34745 ** 0 if the RowSet is already empty.
34746 **
34747 ** After this routine has been called, the sqlite3RowSetInsert()
34748 ** routine may not be called again.  
34749 */
34750 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
34751   rowSetToList(p);
34752   if( p->pEntry ){
34753     *pRowid = p->pEntry->v;
34754     p->pEntry = p->pEntry->pRight;
34755     if( p->pEntry==0 ){
34756       sqlite3RowSetClear(p);
34757     }
34758     return 1;
34759   }else{
34760     return 0;
34761   }
34762 }
34763
34764 /*
34765 ** Check to see if element iRowid was inserted into the the rowset as
34766 ** part of any insert batch prior to iBatch.  Return 1 or 0.
34767 */
34768 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
34769   struct RowSetEntry *p;
34770   if( iBatch!=pRowSet->iBatch ){
34771     if( pRowSet->pEntry ){
34772       rowSetToList(pRowSet);
34773       pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
34774       pRowSet->pEntry = 0;
34775       pRowSet->pLast = 0;
34776     }
34777     pRowSet->iBatch = iBatch;
34778   }
34779   p = pRowSet->pTree;
34780   while( p ){
34781     if( p->v<iRowid ){
34782       p = p->pRight;
34783     }else if( p->v>iRowid ){
34784       p = p->pLeft;
34785     }else{
34786       return 1;
34787     }
34788   }
34789   return 0;
34790 }
34791
34792 /************** End of rowset.c **********************************************/
34793 /************** Begin file pager.c *******************************************/
34794 /*
34795 ** 2001 September 15
34796 **
34797 ** The author disclaims copyright to this source code.  In place of
34798 ** a legal notice, here is a blessing:
34799 **
34800 **    May you do good and not evil.
34801 **    May you find forgiveness for yourself and forgive others.
34802 **    May you share freely, never taking more than you give.
34803 **
34804 *************************************************************************
34805 ** This is the implementation of the page cache subsystem or "pager".
34806 ** 
34807 ** The pager is used to access a database disk file.  It implements
34808 ** atomic commit and rollback through the use of a journal file that
34809 ** is separate from the database file.  The pager also implements file
34810 ** locking to prevent two processes from writing the same database
34811 ** file simultaneously, or one process from reading the database while
34812 ** another is writing.
34813 */
34814 #ifndef SQLITE_OMIT_DISKIO
34815 /************** Include wal.h in the middle of pager.c ***********************/
34816 /************** Begin file wal.h *********************************************/
34817 /*
34818 ** 2010 February 1
34819 **
34820 ** The author disclaims copyright to this source code.  In place of
34821 ** a legal notice, here is a blessing:
34822 **
34823 **    May you do good and not evil.
34824 **    May you find forgiveness for yourself and forgive others.
34825 **    May you share freely, never taking more than you give.
34826 **
34827 *************************************************************************
34828 ** This header file defines the interface to the write-ahead logging 
34829 ** system. Refer to the comments below and the header comment attached to 
34830 ** the implementation of each function in log.c for further details.
34831 */
34832
34833 #ifndef _WAL_H_
34834 #define _WAL_H_
34835
34836
34837 #ifdef SQLITE_OMIT_WAL
34838 # define sqlite3WalOpen(x,y,z)                 0
34839 # define sqlite3WalClose(w,x,y,z)              0
34840 # define sqlite3WalBeginReadTransaction(y,z)   0
34841 # define sqlite3WalEndReadTransaction(z)
34842 # define sqlite3WalRead(v,w,x,y,z)             0
34843 # define sqlite3WalDbsize(y)                   0
34844 # define sqlite3WalBeginWriteTransaction(y)    0
34845 # define sqlite3WalEndWriteTransaction(x)      0
34846 # define sqlite3WalUndo(x,y,z)                 0
34847 # define sqlite3WalSavepoint(y,z)
34848 # define sqlite3WalSavepointUndo(y,z)          0
34849 # define sqlite3WalFrames(u,v,w,x,y,z)         0
34850 # define sqlite3WalCheckpoint(u,v,w,x)         0
34851 # define sqlite3WalCallback(z)                 0
34852 # define sqlite3WalExclusiveMode(y,z)          0
34853 # define sqlite3WalHeapMemory(z)               0
34854 #else
34855
34856 #define WAL_SAVEPOINT_NDATA 4
34857
34858 /* Connection to a write-ahead log (WAL) file. 
34859 ** There is one object of this type for each pager. 
34860 */
34861 typedef struct Wal Wal;
34862
34863 /* Open and close a connection to a write-ahead log. */
34864 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *zName, int, Wal**);
34865 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
34866
34867 /* Used by readers to open (lock) and close (unlock) a snapshot.  A 
34868 ** snapshot is like a read-transaction.  It is the state of the database
34869 ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
34870 ** preserves the current state even if the other threads or processes
34871 ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
34872 ** transaction and releases the lock.
34873 */
34874 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
34875 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
34876
34877 /* Read a page from the write-ahead log, if it is present. */
34878 SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
34879
34880 /* If the WAL is not empty, return the size of the database. */
34881 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
34882
34883 /* Obtain or release the WRITER lock. */
34884 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
34885 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
34886
34887 /* Undo any frames written (but not committed) to the log */
34888 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
34889
34890 /* Return an integer that records the current (uncommitted) write
34891 ** position in the WAL */
34892 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
34893
34894 /* Move the write position of the WAL back to iFrame.  Called in
34895 ** response to a ROLLBACK TO command. */
34896 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
34897
34898 /* Write a frame or frames to the log. */
34899 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
34900
34901 /* Copy pages from the log to the database file */ 
34902 SQLITE_PRIVATE int sqlite3WalCheckpoint(
34903   Wal *pWal,                      /* Write-ahead log connection */
34904   int sync_flags,                 /* Flags to sync db file with (or 0) */
34905   int nBuf,                       /* Size of buffer nBuf */
34906   u8 *zBuf                        /* Temporary buffer to use */
34907 );
34908
34909 /* Return the value to pass to a sqlite3_wal_hook callback, the
34910 ** number of frames in the WAL at the point of the last commit since
34911 ** sqlite3WalCallback() was called.  If no commits have occurred since
34912 ** the last call, then return 0.
34913 */
34914 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
34915
34916 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
34917 ** by the pager layer on the database file.
34918 */
34919 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
34920
34921 /* Return true if the argument is non-NULL and the WAL module is using
34922 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
34923 ** WAL module is using shared-memory, return false. 
34924 */
34925 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
34926
34927 #endif /* ifndef SQLITE_OMIT_WAL */
34928 #endif /* _WAL_H_ */
34929
34930 /************** End of wal.h *************************************************/
34931 /************** Continuing where we left off in pager.c **********************/
34932
34933
34934 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
34935 **
34936 ** This comment block describes invariants that hold when using a rollback
34937 ** journal.  These invariants do not apply for journal_mode=WAL,
34938 ** journal_mode=MEMORY, or journal_mode=OFF.
34939 **
34940 ** Within this comment block, a page is deemed to have been synced
34941 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
34942 ** Otherwise, the page is not synced until the xSync method of the VFS
34943 ** is called successfully on the file containing the page.
34944 **
34945 ** Definition:  A page of the database file is said to be "overwriteable" if
34946 ** one or more of the following are true about the page:
34947 ** 
34948 **     (a)  The original content of the page as it was at the beginning of
34949 **          the transaction has been written into the rollback journal and
34950 **          synced.
34951 ** 
34952 **     (b)  The page was a freelist leaf page at the start of the transaction.
34953 ** 
34954 **     (c)  The page number is greater than the largest page that existed in
34955 **          the database file at the start of the transaction.
34956 ** 
34957 ** (1) A page of the database file is never overwritten unless one of the
34958 **     following are true:
34959 ** 
34960 **     (a) The page and all other pages on the same sector are overwriteable.
34961 ** 
34962 **     (b) The atomic page write optimization is enabled, and the entire
34963 **         transaction other than the update of the transaction sequence
34964 **         number consists of a single page change.
34965 ** 
34966 ** (2) The content of a page written into the rollback journal exactly matches
34967 **     both the content in the database when the rollback journal was written
34968 **     and the content in the database at the beginning of the current
34969 **     transaction.
34970 ** 
34971 ** (3) Writes to the database file are an integer multiple of the page size
34972 **     in length and are aligned on a page boundary.
34973 ** 
34974 ** (4) Reads from the database file are either aligned on a page boundary and
34975 **     an integer multiple of the page size in length or are taken from the
34976 **     first 100 bytes of the database file.
34977 ** 
34978 ** (5) All writes to the database file are synced prior to the rollback journal
34979 **     being deleted, truncated, or zeroed.
34980 ** 
34981 ** (6) If a master journal file is used, then all writes to the database file
34982 **     are synced prior to the master journal being deleted.
34983 ** 
34984 ** Definition: Two databases (or the same database at two points it time)
34985 ** are said to be "logically equivalent" if they give the same answer to
34986 ** all queries.  Note in particular the the content of freelist leaf
34987 ** pages can be changed arbitarily without effecting the logical equivalence
34988 ** of the database.
34989 ** 
34990 ** (7) At any time, if any subset, including the empty set and the total set,
34991 **     of the unsynced changes to a rollback journal are removed and the 
34992 **     journal is rolled back, the resulting database file will be logical
34993 **     equivalent to the database file at the beginning of the transaction.
34994 ** 
34995 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
34996 **     is called to restore the database file to the same size it was at
34997 **     the beginning of the transaction.  (In some VFSes, the xTruncate
34998 **     method is a no-op, but that does not change the fact the SQLite will
34999 **     invoke it.)
35000 ** 
35001 ** (9) Whenever the database file is modified, at least one bit in the range
35002 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
35003 **     the EXCLUSIVE lock, thus signaling other connections on the same
35004 **     database to flush their caches.
35005 **
35006 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
35007 **      than one billion transactions.
35008 **
35009 ** (11) A database file is well-formed at the beginning and at the conclusion
35010 **      of every transaction.
35011 **
35012 ** (12) An EXCLUSIVE lock is held on the database file when writing to
35013 **      the database file.
35014 **
35015 ** (13) A SHARED lock is held on the database file while reading any
35016 **      content out of the database file.
35017 **
35018 ******************************************************************************/
35019
35020 /*
35021 ** Macros for troubleshooting.  Normally turned off
35022 */
35023 #if 0
35024 int sqlite3PagerTrace=1;  /* True to enable tracing */
35025 #define sqlite3DebugPrintf printf
35026 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
35027 #else
35028 #define PAGERTRACE(X)
35029 #endif
35030
35031 /*
35032 ** The following two macros are used within the PAGERTRACE() macros above
35033 ** to print out file-descriptors. 
35034 **
35035 ** PAGERID() takes a pointer to a Pager struct as its argument. The
35036 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
35037 ** struct as its argument.
35038 */
35039 #define PAGERID(p) ((int)(p->fd))
35040 #define FILEHANDLEID(fd) ((int)fd)
35041
35042 /*
35043 ** The Pager.eState variable stores the current 'state' of a pager. A
35044 ** pager may be in any one of the seven states shown in the following
35045 ** state diagram.
35046 **
35047 **                            OPEN <------+------+
35048 **                              |         |      |
35049 **                              V         |      |
35050 **               +---------> READER-------+      |
35051 **               |              |                |
35052 **               |              V                |
35053 **               |<-------WRITER_LOCKED------> ERROR
35054 **               |              |                ^  
35055 **               |              V                |
35056 **               |<------WRITER_CACHEMOD-------->|
35057 **               |              |                |
35058 **               |              V                |
35059 **               |<-------WRITER_DBMOD---------->|
35060 **               |              |                |
35061 **               |              V                |
35062 **               +<------WRITER_FINISHED-------->+
35063 **
35064 **
35065 ** List of state transitions and the C [function] that performs each:
35066 ** 
35067 **   OPEN              -> READER              [sqlite3PagerSharedLock]
35068 **   READER            -> OPEN                [pager_unlock]
35069 **
35070 **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
35071 **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
35072 **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
35073 **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
35074 **   WRITER_***        -> READER              [pager_end_transaction]
35075 **
35076 **   WRITER_***        -> ERROR               [pager_error]
35077 **   ERROR             -> OPEN                [pager_unlock]
35078 ** 
35079 **
35080 **  OPEN:
35081 **
35082 **    The pager starts up in this state. Nothing is guaranteed in this
35083 **    state - the file may or may not be locked and the database size is
35084 **    unknown. The database may not be read or written.
35085 **
35086 **    * No read or write transaction is active.
35087 **    * Any lock, or no lock at all, may be held on the database file.
35088 **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
35089 **
35090 **  READER:
35091 **
35092 **    In this state all the requirements for reading the database in 
35093 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
35094 **    was) in exclusive-locking mode, a user-level read transaction is 
35095 **    open. The database size is known in this state.
35096 **
35097 **    A connection running with locking_mode=normal enters this state when
35098 **    it opens a read-transaction on the database and returns to state
35099 **    OPEN after the read-transaction is completed. However a connection
35100 **    running in locking_mode=exclusive (including temp databases) remains in
35101 **    this state even after the read-transaction is closed. The only way
35102 **    a locking_mode=exclusive connection can transition from READER to OPEN
35103 **    is via the ERROR state (see below).
35104 ** 
35105 **    * A read transaction may be active (but a write-transaction cannot).
35106 **    * A SHARED or greater lock is held on the database file.
35107 **    * The dbSize variable may be trusted (even if a user-level read 
35108 **      transaction is not active). The dbOrigSize and dbFileSize variables
35109 **      may not be trusted at this point.
35110 **    * If the database is a WAL database, then the WAL connection is open.
35111 **    * Even if a read-transaction is not open, it is guaranteed that 
35112 **      there is no hot-journal in the file-system.
35113 **
35114 **  WRITER_LOCKED:
35115 **
35116 **    The pager moves to this state from READER when a write-transaction
35117 **    is first opened on the database. In WRITER_LOCKED state, all locks 
35118 **    required to start a write-transaction are held, but no actual 
35119 **    modifications to the cache or database have taken place.
35120 **
35121 **    In rollback mode, a RESERVED or (if the transaction was opened with 
35122 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
35123 **    moving to this state, but the journal file is not written to or opened 
35124 **    to in this state. If the transaction is committed or rolled back while 
35125 **    in WRITER_LOCKED state, all that is required is to unlock the database 
35126 **    file.
35127 **
35128 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
35129 **    If the connection is running with locking_mode=exclusive, an attempt
35130 **    is made to obtain an EXCLUSIVE lock on the database file.
35131 **
35132 **    * A write transaction is active.
35133 **    * If the connection is open in rollback-mode, a RESERVED or greater 
35134 **      lock is held on the database file.
35135 **    * If the connection is open in WAL-mode, a WAL write transaction
35136 **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
35137 **      called).
35138 **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
35139 **    * The contents of the pager cache have not been modified.
35140 **    * The journal file may or may not be open.
35141 **    * Nothing (not even the first header) has been written to the journal.
35142 **
35143 **  WRITER_CACHEMOD:
35144 **
35145 **    A pager moves from WRITER_LOCKED state to this state when a page is
35146 **    first modified by the upper layer. In rollback mode the journal file
35147 **    is opened (if it is not already open) and a header written to the
35148 **    start of it. The database file on disk has not been modified.
35149 **
35150 **    * A write transaction is active.
35151 **    * A RESERVED or greater lock is held on the database file.
35152 **    * The journal file is open and the first header has been written 
35153 **      to it, but the header has not been synced to disk.
35154 **    * The contents of the page cache have been modified.
35155 **
35156 **  WRITER_DBMOD:
35157 **
35158 **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
35159 **    when it modifies the contents of the database file. WAL connections
35160 **    never enter this state (since they do not modify the database file,
35161 **    just the log file).
35162 **
35163 **    * A write transaction is active.
35164 **    * An EXCLUSIVE or greater lock is held on the database file.
35165 **    * The journal file is open and the first header has been written 
35166 **      and synced to disk.
35167 **    * The contents of the page cache have been modified (and possibly
35168 **      written to disk).
35169 **
35170 **  WRITER_FINISHED:
35171 **
35172 **    It is not possible for a WAL connection to enter this state.
35173 **
35174 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
35175 **    state after the entire transaction has been successfully written into the
35176 **    database file. In this state the transaction may be committed simply
35177 **    by finalizing the journal file. Once in WRITER_FINISHED state, it is 
35178 **    not possible to modify the database further. At this point, the upper 
35179 **    layer must either commit or rollback the transaction.
35180 **
35181 **    * A write transaction is active.
35182 **    * An EXCLUSIVE or greater lock is held on the database file.
35183 **    * All writing and syncing of journal and database data has finished.
35184 **      If no error occured, all that remains is to finalize the journal to
35185 **      commit the transaction. If an error did occur, the caller will need
35186 **      to rollback the transaction. 
35187 **
35188 **  ERROR:
35189 **
35190 **    The ERROR state is entered when an IO or disk-full error (including
35191 **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it 
35192 **    difficult to be sure that the in-memory pager state (cache contents, 
35193 **    db size etc.) are consistent with the contents of the file-system.
35194 **
35195 **    Temporary pager files may enter the ERROR state, but in-memory pagers
35196 **    cannot.
35197 **
35198 **    For example, if an IO error occurs while performing a rollback, 
35199 **    the contents of the page-cache may be left in an inconsistent state.
35200 **    At this point it would be dangerous to change back to READER state
35201 **    (as usually happens after a rollback). Any subsequent readers might
35202 **    report database corruption (due to the inconsistent cache), and if
35203 **    they upgrade to writers, they may inadvertently corrupt the database
35204 **    file. To avoid this hazard, the pager switches into the ERROR state
35205 **    instead of READER following such an error.
35206 **
35207 **    Once it has entered the ERROR state, any attempt to use the pager
35208 **    to read or write data returns an error. Eventually, once all 
35209 **    outstanding transactions have been abandoned, the pager is able to
35210 **    transition back to OPEN state, discarding the contents of the 
35211 **    page-cache and any other in-memory state at the same time. Everything
35212 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
35213 **    when a read-transaction is next opened on the pager (transitioning
35214 **    the pager into READER state). At that point the system has recovered 
35215 **    from the error.
35216 **
35217 **    Specifically, the pager jumps into the ERROR state if:
35218 **
35219 **      1. An error occurs while attempting a rollback. This happens in
35220 **         function sqlite3PagerRollback().
35221 **
35222 **      2. An error occurs while attempting to finalize a journal file
35223 **         following a commit in function sqlite3PagerCommitPhaseTwo().
35224 **
35225 **      3. An error occurs while attempting to write to the journal or
35226 **         database file in function pagerStress() in order to free up
35227 **         memory.
35228 **
35229 **    In other cases, the error is returned to the b-tree layer. The b-tree
35230 **    layer then attempts a rollback operation. If the error condition 
35231 **    persists, the pager enters the ERROR state via condition (1) above.
35232 **
35233 **    Condition (3) is necessary because it can be triggered by a read-only
35234 **    statement executed within a transaction. In this case, if the error
35235 **    code were simply returned to the user, the b-tree layer would not
35236 **    automatically attempt a rollback, as it assumes that an error in a
35237 **    read-only statement cannot leave the pager in an internally inconsistent 
35238 **    state.
35239 **
35240 **    * The Pager.errCode variable is set to something other than SQLITE_OK.
35241 **    * There are one or more outstanding references to pages (after the
35242 **      last reference is dropped the pager should move back to OPEN state).
35243 **    * The pager is not an in-memory pager.
35244 **    
35245 **
35246 ** Notes:
35247 **
35248 **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
35249 **     connection is open in WAL mode. A WAL connection is always in one
35250 **     of the first four states.
35251 **
35252 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
35253 **     state. There are two exceptions: immediately after exclusive-mode has
35254 **     been turned on (and before any read or write transactions are 
35255 **     executed), and when the pager is leaving the "error state".
35256 **
35257 **   * See also: assert_pager_state().
35258 */
35259 #define PAGER_OPEN                  0
35260 #define PAGER_READER                1
35261 #define PAGER_WRITER_LOCKED         2
35262 #define PAGER_WRITER_CACHEMOD       3
35263 #define PAGER_WRITER_DBMOD          4
35264 #define PAGER_WRITER_FINISHED       5
35265 #define PAGER_ERROR                 6
35266
35267 /*
35268 ** The Pager.eLock variable is almost always set to one of the 
35269 ** following locking-states, according to the lock currently held on
35270 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
35271 ** This variable is kept up to date as locks are taken and released by
35272 ** the pagerLockDb() and pagerUnlockDb() wrappers.
35273 **
35274 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
35275 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
35276 ** the operation was successful. In these circumstances pagerLockDb() and
35277 ** pagerUnlockDb() take a conservative approach - eLock is always updated
35278 ** when unlocking the file, and only updated when locking the file if the
35279 ** VFS call is successful. This way, the Pager.eLock variable may be set
35280 ** to a less exclusive (lower) value than the lock that is actually held
35281 ** at the system level, but it is never set to a more exclusive value.
35282 **
35283 ** This is usually safe. If an xUnlock fails or appears to fail, there may 
35284 ** be a few redundant xLock() calls or a lock may be held for longer than
35285 ** required, but nothing really goes wrong.
35286 **
35287 ** The exception is when the database file is unlocked as the pager moves
35288 ** from ERROR to OPEN state. At this point there may be a hot-journal file 
35289 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
35290 ** transition, by the same pager or any other). If the call to xUnlock()
35291 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
35292 ** can confuse the call to xCheckReservedLock() call made later as part
35293 ** of hot-journal detection.
35294 **
35295 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED 
35296 ** lock held by this process or any others". So xCheckReservedLock may 
35297 ** return true because the caller itself is holding an EXCLUSIVE lock (but
35298 ** doesn't know it because of a previous error in xUnlock). If this happens
35299 ** a hot-journal may be mistaken for a journal being created by an active
35300 ** transaction in another process, causing SQLite to read from the database
35301 ** without rolling it back.
35302 **
35303 ** To work around this, if a call to xUnlock() fails when unlocking the
35304 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
35305 ** is only changed back to a real locking state after a successful call
35306 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
35307 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK 
35308 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
35309 ** lock on the database file before attempting to roll it back. See function
35310 ** PagerSharedLock() for more detail.
35311 **
35312 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in 
35313 ** PAGER_OPEN state.
35314 */
35315 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
35316
35317 /*
35318 ** A macro used for invoking the codec if there is one
35319 */
35320 #ifdef SQLITE_HAS_CODEC
35321 # define CODEC1(P,D,N,X,E) \
35322     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
35323 # define CODEC2(P,D,N,X,E,O) \
35324     if( P->xCodec==0 ){ O=(char*)D; }else \
35325     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
35326 #else
35327 # define CODEC1(P,D,N,X,E)   /* NO-OP */
35328 # define CODEC2(P,D,N,X,E,O) O=(char*)D
35329 #endif
35330
35331 /*
35332 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method 
35333 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
35334 ** This could conceivably cause corruption following a power failure on
35335 ** such a system. This is currently an undocumented limit.
35336 */
35337 #define MAX_SECTOR_SIZE 0x10000
35338
35339 /*
35340 ** An instance of the following structure is allocated for each active
35341 ** savepoint and statement transaction in the system. All such structures
35342 ** are stored in the Pager.aSavepoint[] array, which is allocated and
35343 ** resized using sqlite3Realloc().
35344 **
35345 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
35346 ** set to 0. If a journal-header is written into the main journal while
35347 ** the savepoint is active, then iHdrOffset is set to the byte offset 
35348 ** immediately following the last journal record written into the main
35349 ** journal before the journal-header. This is required during savepoint
35350 ** rollback (see pagerPlaybackSavepoint()).
35351 */
35352 typedef struct PagerSavepoint PagerSavepoint;
35353 struct PagerSavepoint {
35354   i64 iOffset;                 /* Starting offset in main journal */
35355   i64 iHdrOffset;              /* See above */
35356   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
35357   Pgno nOrig;                  /* Original number of pages in file */
35358   Pgno iSubRec;                /* Index of first record in sub-journal */
35359 #ifndef SQLITE_OMIT_WAL
35360   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
35361 #endif
35362 };
35363
35364 /*
35365 ** A open page cache is an instance of struct Pager. A description of
35366 ** some of the more important member variables follows:
35367 **
35368 ** eState
35369 **
35370 **   The current 'state' of the pager object. See the comment and state
35371 **   diagram above for a description of the pager state.
35372 **
35373 ** eLock
35374 **
35375 **   For a real on-disk database, the current lock held on the database file -
35376 **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
35377 **
35378 **   For a temporary or in-memory database (neither of which require any
35379 **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
35380 **   databases always have Pager.exclusiveMode==1, this tricks the pager
35381 **   logic into thinking that it already has all the locks it will ever
35382 **   need (and no reason to release them).
35383 **
35384 **   In some (obscure) circumstances, this variable may also be set to
35385 **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
35386 **   details.
35387 **
35388 ** changeCountDone
35389 **
35390 **   This boolean variable is used to make sure that the change-counter 
35391 **   (the 4-byte header field at byte offset 24 of the database file) is 
35392 **   not updated more often than necessary. 
35393 **
35394 **   It is set to true when the change-counter field is updated, which 
35395 **   can only happen if an exclusive lock is held on the database file.
35396 **   It is cleared (set to false) whenever an exclusive lock is 
35397 **   relinquished on the database file. Each time a transaction is committed,
35398 **   The changeCountDone flag is inspected. If it is true, the work of
35399 **   updating the change-counter is omitted for the current transaction.
35400 **
35401 **   This mechanism means that when running in exclusive mode, a connection 
35402 **   need only update the change-counter once, for the first transaction
35403 **   committed.
35404 **
35405 ** setMaster
35406 **
35407 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
35408 **   (or may not) specify a master-journal name to be written into the 
35409 **   journal file before it is synced to disk.
35410 **
35411 **   Whether or not a journal file contains a master-journal pointer affects 
35412 **   the way in which the journal file is finalized after the transaction is 
35413 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
35414 **   If a journal file does not contain a master-journal pointer, it is
35415 **   finalized by overwriting the first journal header with zeroes. If
35416 **   it does contain a master-journal pointer the journal file is finalized 
35417 **   by truncating it to zero bytes, just as if the connection were 
35418 **   running in "journal_mode=truncate" mode.
35419 **
35420 **   Journal files that contain master journal pointers cannot be finalized
35421 **   simply by overwriting the first journal-header with zeroes, as the
35422 **   master journal pointer could interfere with hot-journal rollback of any
35423 **   subsequently interrupted transaction that reuses the journal file.
35424 **
35425 **   The flag is cleared as soon as the journal file is finalized (either
35426 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
35427 **   journal file from being successfully finalized, the setMaster flag
35428 **   is cleared anyway (and the pager will move to ERROR state).
35429 **
35430 ** doNotSpill, doNotSyncSpill
35431 **
35432 **   These two boolean variables control the behaviour of cache-spills
35433 **   (calls made by the pcache module to the pagerStress() routine to
35434 **   write cached data to the file-system in order to free up memory).
35435 **
35436 **   When doNotSpill is non-zero, writing to the database from pagerStress()
35437 **   is disabled altogether. This is done in a very obscure case that
35438 **   comes up during savepoint rollback that requires the pcache module
35439 **   to allocate a new page to prevent the journal file from being written
35440 **   while it is being traversed by code in pager_playback().
35441 ** 
35442 **   If doNotSyncSpill is non-zero, writing to the database from pagerStress()
35443 **   is permitted, but syncing the journal file is not. This flag is set
35444 **   by sqlite3PagerWrite() when the file-system sector-size is larger than
35445 **   the database page-size in order to prevent a journal sync from happening 
35446 **   in between the journalling of two pages on the same sector. 
35447 **
35448 ** subjInMemory
35449 **
35450 **   This is a boolean variable. If true, then any required sub-journal
35451 **   is opened as an in-memory journal file. If false, then in-memory
35452 **   sub-journals are only used for in-memory pager files.
35453 **
35454 **   This variable is updated by the upper layer each time a new 
35455 **   write-transaction is opened.
35456 **
35457 ** dbSize, dbOrigSize, dbFileSize
35458 **
35459 **   Variable dbSize is set to the number of pages in the database file.
35460 **   It is valid in PAGER_READER and higher states (all states except for
35461 **   OPEN and ERROR). 
35462 **
35463 **   dbSize is set based on the size of the database file, which may be 
35464 **   larger than the size of the database (the value stored at offset
35465 **   28 of the database header by the btree). If the size of the file
35466 **   is not an integer multiple of the page-size, the value stored in
35467 **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
35468 **   Except, any file that is greater than 0 bytes in size is considered
35469 **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
35470 **   to dbSize==1).
35471 **
35472 **   During a write-transaction, if pages with page-numbers greater than
35473 **   dbSize are modified in the cache, dbSize is updated accordingly.
35474 **   Similarly, if the database is truncated using PagerTruncateImage(), 
35475 **   dbSize is updated.
35476 **
35477 **   Variables dbOrigSize and dbFileSize are valid in states 
35478 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
35479 **   variable at the start of the transaction. It is used during rollback,
35480 **   and to determine whether or not pages need to be journalled before
35481 **   being modified.
35482 **
35483 **   Throughout a write-transaction, dbFileSize contains the size of
35484 **   the file on disk in pages. It is set to a copy of dbSize when the
35485 **   write-transaction is first opened, and updated when VFS calls are made
35486 **   to write or truncate the database file on disk. 
35487 **
35488 **   The only reason the dbFileSize variable is required is to suppress 
35489 **   unnecessary calls to xTruncate() after committing a transaction. If, 
35490 **   when a transaction is committed, the dbFileSize variable indicates 
35491 **   that the database file is larger than the database image (Pager.dbSize), 
35492 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
35493 **   to measure the database file on disk, and then truncates it if required.
35494 **   dbFileSize is not used when rolling back a transaction. In this case
35495 **   pager_truncate() is called unconditionally (which means there may be
35496 **   a call to xFilesize() that is not strictly required). In either case,
35497 **   pager_truncate() may cause the file to become smaller or larger.
35498 **
35499 ** dbHintSize
35500 **
35501 **   The dbHintSize variable is used to limit the number of calls made to
35502 **   the VFS xFileControl(FCNTL_SIZE_HINT) method. 
35503 **
35504 **   dbHintSize is set to a copy of the dbSize variable when a
35505 **   write-transaction is opened (at the same time as dbFileSize and
35506 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
35507 **   dbHintSize is increased to the number of pages that correspond to the
35508 **   size-hint passed to the method call. See pager_write_pagelist() for 
35509 **   details.
35510 **
35511 ** errCode
35512 **
35513 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
35514 **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode 
35515 **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX 
35516 **   sub-codes.
35517 */
35518 struct Pager {
35519   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
35520   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
35521   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
35522   u8 useJournal;              /* Use a rollback journal on this file */
35523   u8 noReadlock;              /* Do not bother to obtain readlocks */
35524   u8 noSync;                  /* Do not sync the journal if true */
35525   u8 fullSync;                /* Do extra syncs of the journal for robustness */
35526   u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
35527   u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
35528   u8 tempFile;                /* zFilename is a temporary file */
35529   u8 readOnly;                /* True for a read-only database */
35530   u8 memDb;                   /* True to inhibit all file I/O */
35531
35532   /**************************************************************************
35533   ** The following block contains those class members that change during
35534   ** routine opertion.  Class members not in this block are either fixed
35535   ** when the pager is first created or else only change when there is a
35536   ** significant mode change (such as changing the page_size, locking_mode,
35537   ** or the journal_mode).  From another view, these class members describe
35538   ** the "state" of the pager, while other class members describe the
35539   ** "configuration" of the pager.
35540   */
35541   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
35542   u8 eLock;                   /* Current lock held on database file */
35543   u8 changeCountDone;         /* Set after incrementing the change-counter */
35544   u8 setMaster;               /* True if a m-j name has been written to jrnl */
35545   u8 doNotSpill;              /* Do not spill the cache when non-zero */
35546   u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
35547   u8 subjInMemory;            /* True to use in-memory sub-journals */
35548   Pgno dbSize;                /* Number of pages in the database */
35549   Pgno dbOrigSize;            /* dbSize before the current transaction */
35550   Pgno dbFileSize;            /* Number of pages in the database file */
35551   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
35552   int errCode;                /* One of several kinds of errors */
35553   int nRec;                   /* Pages journalled since last j-header written */
35554   u32 cksumInit;              /* Quasi-random value added to every checksum */
35555   u32 nSubRec;                /* Number of records written to sub-journal */
35556   Bitvec *pInJournal;         /* One bit for each page in the database file */
35557   sqlite3_file *fd;           /* File descriptor for database */
35558   sqlite3_file *jfd;          /* File descriptor for main journal */
35559   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
35560   i64 journalOff;             /* Current write offset in the journal file */
35561   i64 journalHdr;             /* Byte offset to previous journal header */
35562   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
35563   PagerSavepoint *aSavepoint; /* Array of active savepoints */
35564   int nSavepoint;             /* Number of elements in aSavepoint[] */
35565   char dbFileVers[16];        /* Changes whenever database file changes */
35566   /*
35567   ** End of the routinely-changing class members
35568   ***************************************************************************/
35569
35570   u16 nExtra;                 /* Add this many bytes to each in-memory page */
35571   i16 nReserve;               /* Number of unused bytes at end of each page */
35572   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
35573   u32 sectorSize;             /* Assumed sector size during rollback */
35574   int pageSize;               /* Number of bytes in a page */
35575   Pgno mxPgno;                /* Maximum allowed size of the database */
35576   i64 journalSizeLimit;       /* Size limit for persistent journal files */
35577   char *zFilename;            /* Name of the database file */
35578   char *zJournal;             /* Name of the journal file */
35579   int (*xBusyHandler)(void*); /* Function to call when busy */
35580   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
35581 #ifdef SQLITE_TEST
35582   int nHit, nMiss;            /* Cache hits and missing */
35583   int nRead, nWrite;          /* Database pages read/written */
35584 #endif
35585   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
35586 #ifdef SQLITE_HAS_CODEC
35587   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
35588   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
35589   void (*xCodecFree)(void*);             /* Destructor for the codec */
35590   void *pCodec;               /* First argument to xCodec... methods */
35591 #endif
35592   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
35593   PCache *pPCache;            /* Pointer to page cache object */
35594 #ifndef SQLITE_OMIT_WAL
35595   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
35596   char *zWal;                 /* File name for write-ahead log */
35597 #endif
35598 };
35599
35600 /*
35601 ** The following global variables hold counters used for
35602 ** testing purposes only.  These variables do not exist in
35603 ** a non-testing build.  These variables are not thread-safe.
35604 */
35605 #ifdef SQLITE_TEST
35606 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
35607 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
35608 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
35609 # define PAGER_INCR(v)  v++
35610 #else
35611 # define PAGER_INCR(v)
35612 #endif
35613
35614
35615
35616 /*
35617 ** Journal files begin with the following magic string.  The data
35618 ** was obtained from /dev/random.  It is used only as a sanity check.
35619 **
35620 ** Since version 2.8.0, the journal format contains additional sanity
35621 ** checking information.  If the power fails while the journal is being
35622 ** written, semi-random garbage data might appear in the journal
35623 ** file after power is restored.  If an attempt is then made
35624 ** to roll the journal back, the database could be corrupted.  The additional
35625 ** sanity checking data is an attempt to discover the garbage in the
35626 ** journal and ignore it.
35627 **
35628 ** The sanity checking information for the new journal format consists
35629 ** of a 32-bit checksum on each page of data.  The checksum covers both
35630 ** the page number and the pPager->pageSize bytes of data for the page.
35631 ** This cksum is initialized to a 32-bit random value that appears in the
35632 ** journal file right after the header.  The random initializer is important,
35633 ** because garbage data that appears at the end of a journal is likely
35634 ** data that was once in other files that have now been deleted.  If the
35635 ** garbage data came from an obsolete journal file, the checksums might
35636 ** be correct.  But by initializing the checksum to random value which
35637 ** is different for every journal, we minimize that risk.
35638 */
35639 static const unsigned char aJournalMagic[] = {
35640   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
35641 };
35642
35643 /*
35644 ** The size of the of each page record in the journal is given by
35645 ** the following macro.
35646 */
35647 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
35648
35649 /*
35650 ** The journal header size for this pager. This is usually the same 
35651 ** size as a single disk sector. See also setSectorSize().
35652 */
35653 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
35654
35655 /*
35656 ** The macro MEMDB is true if we are dealing with an in-memory database.
35657 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
35658 ** the value of MEMDB will be a constant and the compiler will optimize
35659 ** out code that would never execute.
35660 */
35661 #ifdef SQLITE_OMIT_MEMORYDB
35662 # define MEMDB 0
35663 #else
35664 # define MEMDB pPager->memDb
35665 #endif
35666
35667 /*
35668 ** The maximum legal page number is (2^31 - 1).
35669 */
35670 #define PAGER_MAX_PGNO 2147483647
35671
35672 /*
35673 ** The argument to this macro is a file descriptor (type sqlite3_file*).
35674 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
35675 **
35676 ** This is so that expressions can be written as:
35677 **
35678 **   if( isOpen(pPager->jfd) ){ ...
35679 **
35680 ** instead of
35681 **
35682 **   if( pPager->jfd->pMethods ){ ...
35683 */
35684 #define isOpen(pFd) ((pFd)->pMethods)
35685
35686 /*
35687 ** Return true if this pager uses a write-ahead log instead of the usual
35688 ** rollback journal. Otherwise false.
35689 */
35690 #ifndef SQLITE_OMIT_WAL
35691 static int pagerUseWal(Pager *pPager){
35692   return (pPager->pWal!=0);
35693 }
35694 #else
35695 # define pagerUseWal(x) 0
35696 # define pagerRollbackWal(x) 0
35697 # define pagerWalFrames(v,w,x,y,z) 0
35698 # define pagerOpenWalIfPresent(z) SQLITE_OK
35699 # define pagerBeginReadTransaction(z) SQLITE_OK
35700 #endif
35701
35702 #ifndef NDEBUG 
35703 /*
35704 ** Usage:
35705 **
35706 **   assert( assert_pager_state(pPager) );
35707 **
35708 ** This function runs many asserts to try to find inconsistencies in
35709 ** the internal state of the Pager object.
35710 */
35711 static int assert_pager_state(Pager *p){
35712   Pager *pPager = p;
35713
35714   /* State must be valid. */
35715   assert( p->eState==PAGER_OPEN
35716        || p->eState==PAGER_READER
35717        || p->eState==PAGER_WRITER_LOCKED
35718        || p->eState==PAGER_WRITER_CACHEMOD
35719        || p->eState==PAGER_WRITER_DBMOD
35720        || p->eState==PAGER_WRITER_FINISHED
35721        || p->eState==PAGER_ERROR
35722   );
35723
35724   /* Regardless of the current state, a temp-file connection always behaves
35725   ** as if it has an exclusive lock on the database file. It never updates
35726   ** the change-counter field, so the changeCountDone flag is always set.
35727   */
35728   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
35729   assert( p->tempFile==0 || pPager->changeCountDone );
35730
35731   /* If the useJournal flag is clear, the journal-mode must be "OFF". 
35732   ** And if the journal-mode is "OFF", the journal file must not be open.
35733   */
35734   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
35735   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
35736
35737   /* Check that MEMDB implies noSync. And an in-memory journal. Since 
35738   ** this means an in-memory pager performs no IO at all, it cannot encounter 
35739   ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing 
35740   ** a journal file. (although the in-memory journal implementation may 
35741   ** return SQLITE_IOERR_NOMEM while the journal file is being written). It 
35742   ** is therefore not possible for an in-memory pager to enter the ERROR 
35743   ** state.
35744   */
35745   if( MEMDB ){
35746     assert( p->noSync );
35747     assert( p->journalMode==PAGER_JOURNALMODE_OFF 
35748          || p->journalMode==PAGER_JOURNALMODE_MEMORY 
35749     );
35750     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
35751     assert( pagerUseWal(p)==0 );
35752   }
35753
35754   /* If changeCountDone is set, a RESERVED lock or greater must be held
35755   ** on the file.
35756   */
35757   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
35758   assert( p->eLock!=PENDING_LOCK );
35759
35760   switch( p->eState ){
35761     case PAGER_OPEN:
35762       assert( !MEMDB );
35763       assert( pPager->errCode==SQLITE_OK );
35764       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
35765       break;
35766
35767     case PAGER_READER:
35768       assert( pPager->errCode==SQLITE_OK );
35769       assert( p->eLock!=UNKNOWN_LOCK );
35770       assert( p->eLock>=SHARED_LOCK || p->noReadlock );
35771       break;
35772
35773     case PAGER_WRITER_LOCKED:
35774       assert( p->eLock!=UNKNOWN_LOCK );
35775       assert( pPager->errCode==SQLITE_OK );
35776       if( !pagerUseWal(pPager) ){
35777         assert( p->eLock>=RESERVED_LOCK );
35778       }
35779       assert( pPager->dbSize==pPager->dbOrigSize );
35780       assert( pPager->dbOrigSize==pPager->dbFileSize );
35781       assert( pPager->dbOrigSize==pPager->dbHintSize );
35782       assert( pPager->setMaster==0 );
35783       break;
35784
35785     case PAGER_WRITER_CACHEMOD:
35786       assert( p->eLock!=UNKNOWN_LOCK );
35787       assert( pPager->errCode==SQLITE_OK );
35788       if( !pagerUseWal(pPager) ){
35789         /* It is possible that if journal_mode=wal here that neither the
35790         ** journal file nor the WAL file are open. This happens during
35791         ** a rollback transaction that switches from journal_mode=off
35792         ** to journal_mode=wal.
35793         */
35794         assert( p->eLock>=RESERVED_LOCK );
35795         assert( isOpen(p->jfd) 
35796              || p->journalMode==PAGER_JOURNALMODE_OFF 
35797              || p->journalMode==PAGER_JOURNALMODE_WAL 
35798         );
35799       }
35800       assert( pPager->dbOrigSize==pPager->dbFileSize );
35801       assert( pPager->dbOrigSize==pPager->dbHintSize );
35802       break;
35803
35804     case PAGER_WRITER_DBMOD:
35805       assert( p->eLock==EXCLUSIVE_LOCK );
35806       assert( pPager->errCode==SQLITE_OK );
35807       assert( !pagerUseWal(pPager) );
35808       assert( p->eLock>=EXCLUSIVE_LOCK );
35809       assert( isOpen(p->jfd) 
35810            || p->journalMode==PAGER_JOURNALMODE_OFF 
35811            || p->journalMode==PAGER_JOURNALMODE_WAL 
35812       );
35813       assert( pPager->dbOrigSize<=pPager->dbHintSize );
35814       break;
35815
35816     case PAGER_WRITER_FINISHED:
35817       assert( p->eLock==EXCLUSIVE_LOCK );
35818       assert( pPager->errCode==SQLITE_OK );
35819       assert( !pagerUseWal(pPager) );
35820       assert( isOpen(p->jfd) 
35821            || p->journalMode==PAGER_JOURNALMODE_OFF 
35822            || p->journalMode==PAGER_JOURNALMODE_WAL 
35823       );
35824       break;
35825
35826     case PAGER_ERROR:
35827       /* There must be at least one outstanding reference to the pager if
35828       ** in ERROR state. Otherwise the pager should have already dropped
35829       ** back to OPEN state.
35830       */
35831       assert( pPager->errCode!=SQLITE_OK );
35832       assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
35833       break;
35834   }
35835
35836   return 1;
35837 }
35838 #endif /* ifndef NDEBUG */
35839
35840 #ifdef SQLITE_DEBUG 
35841 /*
35842 ** Return a pointer to a human readable string in a static buffer
35843 ** containing the state of the Pager object passed as an argument. This
35844 ** is intended to be used within debuggers. For example, as an alternative
35845 ** to "print *pPager" in gdb:
35846 **
35847 ** (gdb) printf "%s", print_pager_state(pPager)
35848 */
35849 static char *print_pager_state(Pager *p){
35850   static char zRet[1024];
35851
35852   sqlite3_snprintf(1024, zRet,
35853       "Filename:      %s\n"
35854       "State:         %s errCode=%d\n"
35855       "Lock:          %s\n"
35856       "Locking mode:  locking_mode=%s\n"
35857       "Journal mode:  journal_mode=%s\n"
35858       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
35859       "Journal:       journalOff=%lld journalHdr=%lld\n"
35860       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
35861       , p->zFilename
35862       , p->eState==PAGER_OPEN            ? "OPEN" :
35863         p->eState==PAGER_READER          ? "READER" :
35864         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
35865         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
35866         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
35867         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
35868         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
35869       , (int)p->errCode
35870       , p->eLock==NO_LOCK         ? "NO_LOCK" :
35871         p->eLock==RESERVED_LOCK   ? "RESERVED" :
35872         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
35873         p->eLock==SHARED_LOCK     ? "SHARED" :
35874         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
35875       , p->exclusiveMode ? "exclusive" : "normal"
35876       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
35877         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
35878         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
35879         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
35880         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
35881         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
35882       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
35883       , p->journalOff, p->journalHdr
35884       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
35885   );
35886
35887   return zRet;
35888 }
35889 #endif
35890
35891 /*
35892 ** Return true if it is necessary to write page *pPg into the sub-journal.
35893 ** A page needs to be written into the sub-journal if there exists one
35894 ** or more open savepoints for which:
35895 **
35896 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
35897 **   * The bit corresponding to the page-number is not set in
35898 **     PagerSavepoint.pInSavepoint.
35899 */
35900 static int subjRequiresPage(PgHdr *pPg){
35901   Pgno pgno = pPg->pgno;
35902   Pager *pPager = pPg->pPager;
35903   int i;
35904   for(i=0; i<pPager->nSavepoint; i++){
35905     PagerSavepoint *p = &pPager->aSavepoint[i];
35906     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
35907       return 1;
35908     }
35909   }
35910   return 0;
35911 }
35912
35913 /*
35914 ** Return true if the page is already in the journal file.
35915 */
35916 static int pageInJournal(PgHdr *pPg){
35917   return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
35918 }
35919
35920 /*
35921 ** Read a 32-bit integer from the given file descriptor.  Store the integer
35922 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
35923 ** error code is something goes wrong.
35924 **
35925 ** All values are stored on disk as big-endian.
35926 */
35927 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
35928   unsigned char ac[4];
35929   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
35930   if( rc==SQLITE_OK ){
35931     *pRes = sqlite3Get4byte(ac);
35932   }
35933   return rc;
35934 }
35935
35936 /*
35937 ** Write a 32-bit integer into a string buffer in big-endian byte order.
35938 */
35939 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
35940
35941
35942 /*
35943 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
35944 ** on success or an error code is something goes wrong.
35945 */
35946 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
35947   char ac[4];
35948   put32bits(ac, val);
35949   return sqlite3OsWrite(fd, ac, 4, offset);
35950 }
35951
35952 /*
35953 ** Unlock the database file to level eLock, which must be either NO_LOCK
35954 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
35955 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
35956 **
35957 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
35958 ** called, do not modify it. See the comment above the #define of 
35959 ** UNKNOWN_LOCK for an explanation of this.
35960 */
35961 static int pagerUnlockDb(Pager *pPager, int eLock){
35962   int rc = SQLITE_OK;
35963
35964   assert( !pPager->exclusiveMode || pPager->eLock==eLock );
35965   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
35966   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
35967   if( isOpen(pPager->fd) ){
35968     assert( pPager->eLock>=eLock );
35969     rc = sqlite3OsUnlock(pPager->fd, eLock);
35970     if( pPager->eLock!=UNKNOWN_LOCK ){
35971       pPager->eLock = (u8)eLock;
35972     }
35973     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
35974   }
35975   return rc;
35976 }
35977
35978 /*
35979 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
35980 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
35981 ** Pager.eLock variable to the new locking state. 
35982 **
35983 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is 
35984 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. 
35985 ** See the comment above the #define of UNKNOWN_LOCK for an explanation 
35986 ** of this.
35987 */
35988 static int pagerLockDb(Pager *pPager, int eLock){
35989   int rc = SQLITE_OK;
35990
35991   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
35992   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
35993     rc = sqlite3OsLock(pPager->fd, eLock);
35994     if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
35995       pPager->eLock = (u8)eLock;
35996       IOTRACE(("LOCK %p %d\n", pPager, eLock))
35997     }
35998   }
35999   return rc;
36000 }
36001
36002 /*
36003 ** This function determines whether or not the atomic-write optimization
36004 ** can be used with this pager. The optimization can be used if:
36005 **
36006 **  (a) the value returned by OsDeviceCharacteristics() indicates that
36007 **      a database page may be written atomically, and
36008 **  (b) the value returned by OsSectorSize() is less than or equal
36009 **      to the page size.
36010 **
36011 ** The optimization is also always enabled for temporary files. It is
36012 ** an error to call this function if pPager is opened on an in-memory
36013 ** database.
36014 **
36015 ** If the optimization cannot be used, 0 is returned. If it can be used,
36016 ** then the value returned is the size of the journal file when it
36017 ** contains rollback data for exactly one page.
36018 */
36019 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
36020 static int jrnlBufferSize(Pager *pPager){
36021   assert( !MEMDB );
36022   if( !pPager->tempFile ){
36023     int dc;                           /* Device characteristics */
36024     int nSector;                      /* Sector size */
36025     int szPage;                       /* Page size */
36026
36027     assert( isOpen(pPager->fd) );
36028     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
36029     nSector = pPager->sectorSize;
36030     szPage = pPager->pageSize;
36031
36032     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
36033     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
36034     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
36035       return 0;
36036     }
36037   }
36038
36039   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
36040 }
36041 #endif
36042
36043 /*
36044 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
36045 ** on the cache using a hash function.  This is used for testing
36046 ** and debugging only.
36047 */
36048 #ifdef SQLITE_CHECK_PAGES
36049 /*
36050 ** Return a 32-bit hash of the page data for pPage.
36051 */
36052 static u32 pager_datahash(int nByte, unsigned char *pData){
36053   u32 hash = 0;
36054   int i;
36055   for(i=0; i<nByte; i++){
36056     hash = (hash*1039) + pData[i];
36057   }
36058   return hash;
36059 }
36060 static u32 pager_pagehash(PgHdr *pPage){
36061   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
36062 }
36063 static void pager_set_pagehash(PgHdr *pPage){
36064   pPage->pageHash = pager_pagehash(pPage);
36065 }
36066
36067 /*
36068 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
36069 ** is defined, and NDEBUG is not defined, an assert() statement checks
36070 ** that the page is either dirty or still matches the calculated page-hash.
36071 */
36072 #define CHECK_PAGE(x) checkPage(x)
36073 static void checkPage(PgHdr *pPg){
36074   Pager *pPager = pPg->pPager;
36075   assert( pPager->eState!=PAGER_ERROR );
36076   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
36077 }
36078
36079 #else
36080 #define pager_datahash(X,Y)  0
36081 #define pager_pagehash(X)  0
36082 #define pager_set_pagehash(X)
36083 #define CHECK_PAGE(x)
36084 #endif  /* SQLITE_CHECK_PAGES */
36085
36086 /*
36087 ** When this is called the journal file for pager pPager must be open.
36088 ** This function attempts to read a master journal file name from the 
36089 ** end of the file and, if successful, copies it into memory supplied 
36090 ** by the caller. See comments above writeMasterJournal() for the format
36091 ** used to store a master journal file name at the end of a journal file.
36092 **
36093 ** zMaster must point to a buffer of at least nMaster bytes allocated by
36094 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
36095 ** enough space to write the master journal name). If the master journal
36096 ** name in the journal is longer than nMaster bytes (including a
36097 ** nul-terminator), then this is handled as if no master journal name
36098 ** were present in the journal.
36099 **
36100 ** If a master journal file name is present at the end of the journal
36101 ** file, then it is copied into the buffer pointed to by zMaster. A
36102 ** nul-terminator byte is appended to the buffer following the master
36103 ** journal file name.
36104 **
36105 ** If it is determined that no master journal file name is present 
36106 ** zMaster[0] is set to 0 and SQLITE_OK returned.
36107 **
36108 ** If an error occurs while reading from the journal file, an SQLite
36109 ** error code is returned.
36110 */
36111 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
36112   int rc;                    /* Return code */
36113   u32 len;                   /* Length in bytes of master journal name */
36114   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
36115   u32 cksum;                 /* MJ checksum value read from journal */
36116   u32 u;                     /* Unsigned loop counter */
36117   unsigned char aMagic[8];   /* A buffer to hold the magic header */
36118   zMaster[0] = '\0';
36119
36120   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
36121    || szJ<16
36122    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
36123    || len>=nMaster 
36124    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
36125    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
36126    || memcmp(aMagic, aJournalMagic, 8)
36127    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
36128   ){
36129     return rc;
36130   }
36131
36132   /* See if the checksum matches the master journal name */
36133   for(u=0; u<len; u++){
36134     cksum -= zMaster[u];
36135   }
36136   if( cksum ){
36137     /* If the checksum doesn't add up, then one or more of the disk sectors
36138     ** containing the master journal filename is corrupted. This means
36139     ** definitely roll back, so just return SQLITE_OK and report a (nul)
36140     ** master-journal filename.
36141     */
36142     len = 0;
36143   }
36144   zMaster[len] = '\0';
36145    
36146   return SQLITE_OK;
36147 }
36148
36149 /*
36150 ** Return the offset of the sector boundary at or immediately 
36151 ** following the value in pPager->journalOff, assuming a sector 
36152 ** size of pPager->sectorSize bytes.
36153 **
36154 ** i.e for a sector size of 512:
36155 **
36156 **   Pager.journalOff          Return value
36157 **   ---------------------------------------
36158 **   0                         0
36159 **   512                       512
36160 **   100                       512
36161 **   2000                      2048
36162 ** 
36163 */
36164 static i64 journalHdrOffset(Pager *pPager){
36165   i64 offset = 0;
36166   i64 c = pPager->journalOff;
36167   if( c ){
36168     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
36169   }
36170   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
36171   assert( offset>=c );
36172   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
36173   return offset;
36174 }
36175
36176 /*
36177 ** The journal file must be open when this function is called.
36178 **
36179 ** This function is a no-op if the journal file has not been written to
36180 ** within the current transaction (i.e. if Pager.journalOff==0).
36181 **
36182 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
36183 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
36184 ** zero the 28-byte header at the start of the journal file. In either case, 
36185 ** if the pager is not in no-sync mode, sync the journal file immediately 
36186 ** after writing or truncating it.
36187 **
36188 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
36189 ** following the truncation or zeroing described above the size of the 
36190 ** journal file in bytes is larger than this value, then truncate the
36191 ** journal file to Pager.journalSizeLimit bytes. The journal file does
36192 ** not need to be synced following this operation.
36193 **
36194 ** If an IO error occurs, abandon processing and return the IO error code.
36195 ** Otherwise, return SQLITE_OK.
36196 */
36197 static int zeroJournalHdr(Pager *pPager, int doTruncate){
36198   int rc = SQLITE_OK;                               /* Return code */
36199   assert( isOpen(pPager->jfd) );
36200   if( pPager->journalOff ){
36201     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
36202
36203     IOTRACE(("JZEROHDR %p\n", pPager))
36204     if( doTruncate || iLimit==0 ){
36205       rc = sqlite3OsTruncate(pPager->jfd, 0);
36206     }else{
36207       static const char zeroHdr[28] = {0};
36208       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
36209     }
36210     if( rc==SQLITE_OK && !pPager->noSync ){
36211       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
36212     }
36213
36214     /* At this point the transaction is committed but the write lock 
36215     ** is still held on the file. If there is a size limit configured for 
36216     ** the persistent journal and the journal file currently consumes more
36217     ** space than that limit allows for, truncate it now. There is no need
36218     ** to sync the file following this operation.
36219     */
36220     if( rc==SQLITE_OK && iLimit>0 ){
36221       i64 sz;
36222       rc = sqlite3OsFileSize(pPager->jfd, &sz);
36223       if( rc==SQLITE_OK && sz>iLimit ){
36224         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
36225       }
36226     }
36227   }
36228   return rc;
36229 }
36230
36231 /*
36232 ** The journal file must be open when this routine is called. A journal
36233 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
36234 ** current location.
36235 **
36236 ** The format for the journal header is as follows:
36237 ** - 8 bytes: Magic identifying journal format.
36238 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
36239 ** - 4 bytes: Random number used for page hash.
36240 ** - 4 bytes: Initial database page count.
36241 ** - 4 bytes: Sector size used by the process that wrote this journal.
36242 ** - 4 bytes: Database page size.
36243 ** 
36244 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
36245 */
36246 static int writeJournalHdr(Pager *pPager){
36247   int rc = SQLITE_OK;                 /* Return code */
36248   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
36249   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
36250   u32 nWrite;                         /* Bytes of header sector written */
36251   int ii;                             /* Loop counter */
36252
36253   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
36254
36255   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
36256     nHeader = JOURNAL_HDR_SZ(pPager);
36257   }
36258
36259   /* If there are active savepoints and any of them were created 
36260   ** since the most recent journal header was written, update the 
36261   ** PagerSavepoint.iHdrOffset fields now.
36262   */
36263   for(ii=0; ii<pPager->nSavepoint; ii++){
36264     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
36265       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
36266     }
36267   }
36268
36269   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
36270
36271   /* 
36272   ** Write the nRec Field - the number of page records that follow this
36273   ** journal header. Normally, zero is written to this value at this time.
36274   ** After the records are added to the journal (and the journal synced, 
36275   ** if in full-sync mode), the zero is overwritten with the true number
36276   ** of records (see syncJournal()).
36277   **
36278   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
36279   ** reading the journal this value tells SQLite to assume that the
36280   ** rest of the journal file contains valid page records. This assumption
36281   ** is dangerous, as if a failure occurred whilst writing to the journal
36282   ** file it may contain some garbage data. There are two scenarios
36283   ** where this risk can be ignored:
36284   **
36285   **   * When the pager is in no-sync mode. Corruption can follow a
36286   **     power failure in this case anyway.
36287   **
36288   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
36289   **     that garbage data is never appended to the journal file.
36290   */
36291   assert( isOpen(pPager->fd) || pPager->noSync );
36292   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
36293    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
36294   ){
36295     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
36296     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
36297   }else{
36298     memset(zHeader, 0, sizeof(aJournalMagic)+4);
36299   }
36300
36301   /* The random check-hash initialiser */ 
36302   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
36303   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
36304   /* The initial database size */
36305   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
36306   /* The assumed sector size for this process */
36307   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
36308
36309   /* The page size */
36310   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
36311
36312   /* Initializing the tail of the buffer is not necessary.  Everything
36313   ** works find if the following memset() is omitted.  But initializing
36314   ** the memory prevents valgrind from complaining, so we are willing to
36315   ** take the performance hit.
36316   */
36317   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
36318          nHeader-(sizeof(aJournalMagic)+20));
36319
36320   /* In theory, it is only necessary to write the 28 bytes that the 
36321   ** journal header consumes to the journal file here. Then increment the 
36322   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next 
36323   ** record is written to the following sector (leaving a gap in the file
36324   ** that will be implicitly filled in by the OS).
36325   **
36326   ** However it has been discovered that on some systems this pattern can 
36327   ** be significantly slower than contiguously writing data to the file,
36328   ** even if that means explicitly writing data to the block of 
36329   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
36330   ** is done. 
36331   **
36332   ** The loop is required here in case the sector-size is larger than the 
36333   ** database page size. Since the zHeader buffer is only Pager.pageSize
36334   ** bytes in size, more than one call to sqlite3OsWrite() may be required
36335   ** to populate the entire journal header sector.
36336   */ 
36337   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
36338     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
36339     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
36340     assert( pPager->journalHdr <= pPager->journalOff );
36341     pPager->journalOff += nHeader;
36342   }
36343
36344   return rc;
36345 }
36346
36347 /*
36348 ** The journal file must be open when this is called. A journal header file
36349 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
36350 ** file. The current location in the journal file is given by
36351 ** pPager->journalOff. See comments above function writeJournalHdr() for
36352 ** a description of the journal header format.
36353 **
36354 ** If the header is read successfully, *pNRec is set to the number of
36355 ** page records following this header and *pDbSize is set to the size of the
36356 ** database before the transaction began, in pages. Also, pPager->cksumInit
36357 ** is set to the value read from the journal header. SQLITE_OK is returned
36358 ** in this case.
36359 **
36360 ** If the journal header file appears to be corrupted, SQLITE_DONE is
36361 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
36362 ** cannot be read from the journal file an error code is returned.
36363 */
36364 static int readJournalHdr(
36365   Pager *pPager,               /* Pager object */
36366   int isHot,
36367   i64 journalSize,             /* Size of the open journal file in bytes */
36368   u32 *pNRec,                  /* OUT: Value read from the nRec field */
36369   u32 *pDbSize                 /* OUT: Value of original database size field */
36370 ){
36371   int rc;                      /* Return code */
36372   unsigned char aMagic[8];     /* A buffer to hold the magic header */
36373   i64 iHdrOff;                 /* Offset of journal header being read */
36374
36375   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
36376
36377   /* Advance Pager.journalOff to the start of the next sector. If the
36378   ** journal file is too small for there to be a header stored at this
36379   ** point, return SQLITE_DONE.
36380   */
36381   pPager->journalOff = journalHdrOffset(pPager);
36382   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
36383     return SQLITE_DONE;
36384   }
36385   iHdrOff = pPager->journalOff;
36386
36387   /* Read in the first 8 bytes of the journal header. If they do not match
36388   ** the  magic string found at the start of each journal header, return
36389   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
36390   ** proceed.
36391   */
36392   if( isHot || iHdrOff!=pPager->journalHdr ){
36393     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
36394     if( rc ){
36395       return rc;
36396     }
36397     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
36398       return SQLITE_DONE;
36399     }
36400   }
36401
36402   /* Read the first three 32-bit fields of the journal header: The nRec
36403   ** field, the checksum-initializer and the database size at the start
36404   ** of the transaction. Return an error code if anything goes wrong.
36405   */
36406   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
36407    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
36408    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
36409   ){
36410     return rc;
36411   }
36412
36413   if( pPager->journalOff==0 ){
36414     u32 iPageSize;               /* Page-size field of journal header */
36415     u32 iSectorSize;             /* Sector-size field of journal header */
36416
36417     /* Read the page-size and sector-size journal header fields. */
36418     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
36419      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
36420     ){
36421       return rc;
36422     }
36423
36424     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
36425     ** journal header to zero. In this case, assume that the Pager.pageSize
36426     ** variable is already set to the correct page size.
36427     */
36428     if( iPageSize==0 ){
36429       iPageSize = pPager->pageSize;
36430     }
36431
36432     /* Check that the values read from the page-size and sector-size fields
36433     ** are within range. To be 'in range', both values need to be a power
36434     ** of two greater than or equal to 512 or 32, and not greater than their 
36435     ** respective compile time maximum limits.
36436     */
36437     if( iPageSize<512                  || iSectorSize<32
36438      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
36439      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 
36440     ){
36441       /* If the either the page-size or sector-size in the journal-header is 
36442       ** invalid, then the process that wrote the journal-header must have 
36443       ** crashed before the header was synced. In this case stop reading 
36444       ** the journal file here.
36445       */
36446       return SQLITE_DONE;
36447     }
36448
36449     /* Update the page-size to match the value read from the journal. 
36450     ** Use a testcase() macro to make sure that malloc failure within 
36451     ** PagerSetPagesize() is tested.
36452     */
36453     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
36454     testcase( rc!=SQLITE_OK );
36455
36456     /* Update the assumed sector-size to match the value used by 
36457     ** the process that created this journal. If this journal was
36458     ** created by a process other than this one, then this routine
36459     ** is being called from within pager_playback(). The local value
36460     ** of Pager.sectorSize is restored at the end of that routine.
36461     */
36462     pPager->sectorSize = iSectorSize;
36463   }
36464
36465   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
36466   return rc;
36467 }
36468
36469
36470 /*
36471 ** Write the supplied master journal name into the journal file for pager
36472 ** pPager at the current location. The master journal name must be the last
36473 ** thing written to a journal file. If the pager is in full-sync mode, the
36474 ** journal file descriptor is advanced to the next sector boundary before
36475 ** anything is written. The format is:
36476 **
36477 **   + 4 bytes: PAGER_MJ_PGNO.
36478 **   + N bytes: Master journal filename in utf-8.
36479 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
36480 **   + 4 bytes: Master journal name checksum.
36481 **   + 8 bytes: aJournalMagic[].
36482 **
36483 ** The master journal page checksum is the sum of the bytes in the master
36484 ** journal name, where each byte is interpreted as a signed 8-bit integer.
36485 **
36486 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
36487 ** this call is a no-op.
36488 */
36489 static int writeMasterJournal(Pager *pPager, const char *zMaster){
36490   int rc;                          /* Return code */
36491   int nMaster;                     /* Length of string zMaster */
36492   i64 iHdrOff;                     /* Offset of header in journal file */
36493   i64 jrnlSize;                    /* Size of journal file on disk */
36494   u32 cksum = 0;                   /* Checksum of string zMaster */
36495
36496   assert( pPager->setMaster==0 );
36497   assert( !pagerUseWal(pPager) );
36498
36499   if( !zMaster 
36500    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
36501    || pPager->journalMode==PAGER_JOURNALMODE_OFF 
36502   ){
36503     return SQLITE_OK;
36504   }
36505   pPager->setMaster = 1;
36506   assert( isOpen(pPager->jfd) );
36507   assert( pPager->journalHdr <= pPager->journalOff );
36508
36509   /* Calculate the length in bytes and the checksum of zMaster */
36510   for(nMaster=0; zMaster[nMaster]; nMaster++){
36511     cksum += zMaster[nMaster];
36512   }
36513
36514   /* If in full-sync mode, advance to the next disk sector before writing
36515   ** the master journal name. This is in case the previous page written to
36516   ** the journal has already been synced.
36517   */
36518   if( pPager->fullSync ){
36519     pPager->journalOff = journalHdrOffset(pPager);
36520   }
36521   iHdrOff = pPager->journalOff;
36522
36523   /* Write the master journal data to the end of the journal file. If
36524   ** an error occurs, return the error code to the caller.
36525   */
36526   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
36527    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
36528    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
36529    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
36530    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
36531   ){
36532     return rc;
36533   }
36534   pPager->journalOff += (nMaster+20);
36535
36536   /* If the pager is in peristent-journal mode, then the physical 
36537   ** journal-file may extend past the end of the master-journal name
36538   ** and 8 bytes of magic data just written to the file. This is 
36539   ** dangerous because the code to rollback a hot-journal file
36540   ** will not be able to find the master-journal name to determine 
36541   ** whether or not the journal is hot. 
36542   **
36543   ** Easiest thing to do in this scenario is to truncate the journal 
36544   ** file to the required size.
36545   */ 
36546   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
36547    && jrnlSize>pPager->journalOff
36548   ){
36549     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
36550   }
36551   return rc;
36552 }
36553
36554 /*
36555 ** Find a page in the hash table given its page number. Return
36556 ** a pointer to the page or NULL if the requested page is not 
36557 ** already in memory.
36558 */
36559 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
36560   PgHdr *p;                         /* Return value */
36561
36562   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
36563   ** fail, since no attempt to allocate dynamic memory will be made.
36564   */
36565   (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
36566   return p;
36567 }
36568
36569 /*
36570 ** Discard the entire contents of the in-memory page-cache.
36571 */
36572 static void pager_reset(Pager *pPager){
36573   sqlite3BackupRestart(pPager->pBackup);
36574   sqlite3PcacheClear(pPager->pPCache);
36575 }
36576
36577 /*
36578 ** Free all structures in the Pager.aSavepoint[] array and set both
36579 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
36580 ** if it is open and the pager is not in exclusive mode.
36581 */
36582 static void releaseAllSavepoints(Pager *pPager){
36583   int ii;               /* Iterator for looping through Pager.aSavepoint */
36584   for(ii=0; ii<pPager->nSavepoint; ii++){
36585     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
36586   }
36587   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
36588     sqlite3OsClose(pPager->sjfd);
36589   }
36590   sqlite3_free(pPager->aSavepoint);
36591   pPager->aSavepoint = 0;
36592   pPager->nSavepoint = 0;
36593   pPager->nSubRec = 0;
36594 }
36595
36596 /*
36597 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint 
36598 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
36599 ** or SQLITE_NOMEM if a malloc failure occurs.
36600 */
36601 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
36602   int ii;                   /* Loop counter */
36603   int rc = SQLITE_OK;       /* Result code */
36604
36605   for(ii=0; ii<pPager->nSavepoint; ii++){
36606     PagerSavepoint *p = &pPager->aSavepoint[ii];
36607     if( pgno<=p->nOrig ){
36608       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
36609       testcase( rc==SQLITE_NOMEM );
36610       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
36611     }
36612   }
36613   return rc;
36614 }
36615
36616 /*
36617 ** This function is a no-op if the pager is in exclusive mode and not
36618 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
36619 ** state.
36620 **
36621 ** If the pager is not in exclusive-access mode, the database file is
36622 ** completely unlocked. If the file is unlocked and the file-system does
36623 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
36624 ** closed (if it is open).
36625 **
36626 ** If the pager is in ERROR state when this function is called, the 
36627 ** contents of the pager cache are discarded before switching back to 
36628 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
36629 ** or not, any journal file left in the file-system will be treated
36630 ** as a hot-journal and rolled back the next time a read-transaction
36631 ** is opened (by this or by any other connection).
36632 */
36633 static void pager_unlock(Pager *pPager){
36634
36635   assert( pPager->eState==PAGER_READER 
36636        || pPager->eState==PAGER_OPEN 
36637        || pPager->eState==PAGER_ERROR 
36638   );
36639
36640   sqlite3BitvecDestroy(pPager->pInJournal);
36641   pPager->pInJournal = 0;
36642   releaseAllSavepoints(pPager);
36643
36644   if( pagerUseWal(pPager) ){
36645     assert( !isOpen(pPager->jfd) );
36646     sqlite3WalEndReadTransaction(pPager->pWal);
36647     pPager->eState = PAGER_OPEN;
36648   }else if( !pPager->exclusiveMode ){
36649     int rc;                       /* Error code returned by pagerUnlockDb() */
36650     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
36651
36652     /* If the operating system support deletion of open files, then
36653     ** close the journal file when dropping the database lock.  Otherwise
36654     ** another connection with journal_mode=delete might delete the file
36655     ** out from under us.
36656     */
36657     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
36658     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
36659     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
36660     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
36661     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
36662     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
36663     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
36664      || 1!=(pPager->journalMode & 5)
36665     ){
36666       sqlite3OsClose(pPager->jfd);
36667     }
36668
36669     /* If the pager is in the ERROR state and the call to unlock the database
36670     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
36671     ** above the #define for UNKNOWN_LOCK for an explanation of why this
36672     ** is necessary.
36673     */
36674     rc = pagerUnlockDb(pPager, NO_LOCK);
36675     if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
36676       pPager->eLock = UNKNOWN_LOCK;
36677     }
36678
36679     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
36680     ** without clearing the error code. This is intentional - the error
36681     ** code is cleared and the cache reset in the block below.
36682     */
36683     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
36684     pPager->changeCountDone = 0;
36685     pPager->eState = PAGER_OPEN;
36686   }
36687
36688   /* If Pager.errCode is set, the contents of the pager cache cannot be
36689   ** trusted. Now that there are no outstanding references to the pager,
36690   ** it can safely move back to PAGER_OPEN state. This happens in both
36691   ** normal and exclusive-locking mode.
36692   */
36693   if( pPager->errCode ){
36694     assert( !MEMDB );
36695     pager_reset(pPager);
36696     pPager->changeCountDone = pPager->tempFile;
36697     pPager->eState = PAGER_OPEN;
36698     pPager->errCode = SQLITE_OK;
36699   }
36700
36701   pPager->journalOff = 0;
36702   pPager->journalHdr = 0;
36703   pPager->setMaster = 0;
36704 }
36705
36706 /*
36707 ** This function is called whenever an IOERR or FULL error that requires
36708 ** the pager to transition into the ERROR state may ahve occurred.
36709 ** The first argument is a pointer to the pager structure, the second 
36710 ** the error-code about to be returned by a pager API function. The 
36711 ** value returned is a copy of the second argument to this function. 
36712 **
36713 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
36714 ** IOERR sub-codes, the pager enters the ERROR state and the error code
36715 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
36716 ** all major API calls on the Pager will immediately return Pager.errCode.
36717 **
36718 ** The ERROR state indicates that the contents of the pager-cache 
36719 ** cannot be trusted. This state can be cleared by completely discarding 
36720 ** the contents of the pager-cache. If a transaction was active when
36721 ** the persistent error occurred, then the rollback journal may need
36722 ** to be replayed to restore the contents of the database file (as if
36723 ** it were a hot-journal).
36724 */
36725 static int pager_error(Pager *pPager, int rc){
36726   int rc2 = rc & 0xff;
36727   assert( rc==SQLITE_OK || !MEMDB );
36728   assert(
36729        pPager->errCode==SQLITE_FULL ||
36730        pPager->errCode==SQLITE_OK ||
36731        (pPager->errCode & 0xff)==SQLITE_IOERR
36732   );
36733   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
36734     pPager->errCode = rc;
36735     pPager->eState = PAGER_ERROR;
36736   }
36737   return rc;
36738 }
36739
36740 /*
36741 ** This routine ends a transaction. A transaction is usually ended by 
36742 ** either a COMMIT or a ROLLBACK operation. This routine may be called 
36743 ** after rollback of a hot-journal, or if an error occurs while opening
36744 ** the journal file or writing the very first journal-header of a
36745 ** database transaction.
36746 ** 
36747 ** This routine is never called in PAGER_ERROR state. If it is called
36748 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
36749 ** exclusive than a RESERVED lock, it is a no-op.
36750 **
36751 ** Otherwise, any active savepoints are released.
36752 **
36753 ** If the journal file is open, then it is "finalized". Once a journal 
36754 ** file has been finalized it is not possible to use it to roll back a 
36755 ** transaction. Nor will it be considered to be a hot-journal by this
36756 ** or any other database connection. Exactly how a journal is finalized
36757 ** depends on whether or not the pager is running in exclusive mode and
36758 ** the current journal-mode (Pager.journalMode value), as follows:
36759 **
36760 **   journalMode==MEMORY
36761 **     Journal file descriptor is simply closed. This destroys an 
36762 **     in-memory journal.
36763 **
36764 **   journalMode==TRUNCATE
36765 **     Journal file is truncated to zero bytes in size.
36766 **
36767 **   journalMode==PERSIST
36768 **     The first 28 bytes of the journal file are zeroed. This invalidates
36769 **     the first journal header in the file, and hence the entire journal
36770 **     file. An invalid journal file cannot be rolled back.
36771 **
36772 **   journalMode==DELETE
36773 **     The journal file is closed and deleted using sqlite3OsDelete().
36774 **
36775 **     If the pager is running in exclusive mode, this method of finalizing
36776 **     the journal file is never used. Instead, if the journalMode is
36777 **     DELETE and the pager is in exclusive mode, the method described under
36778 **     journalMode==PERSIST is used instead.
36779 **
36780 ** After the journal is finalized, the pager moves to PAGER_READER state.
36781 ** If running in non-exclusive rollback mode, the lock on the file is 
36782 ** downgraded to a SHARED_LOCK.
36783 **
36784 ** SQLITE_OK is returned if no error occurs. If an error occurs during
36785 ** any of the IO operations to finalize the journal file or unlock the
36786 ** database then the IO error code is returned to the user. If the 
36787 ** operation to finalize the journal file fails, then the code still
36788 ** tries to unlock the database file if not in exclusive mode. If the
36789 ** unlock operation fails as well, then the first error code related
36790 ** to the first error encountered (the journal finalization one) is
36791 ** returned.
36792 */
36793 static int pager_end_transaction(Pager *pPager, int hasMaster){
36794   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
36795   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
36796
36797   /* Do nothing if the pager does not have an open write transaction
36798   ** or at least a RESERVED lock. This function may be called when there
36799   ** is no write-transaction active but a RESERVED or greater lock is
36800   ** held under two circumstances:
36801   **
36802   **   1. After a successful hot-journal rollback, it is called with
36803   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
36804   **
36805   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE 
36806   **      lock switches back to locking_mode=normal and then executes a
36807   **      read-transaction, this function is called with eState==PAGER_READER 
36808   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
36809   */
36810   assert( assert_pager_state(pPager) );
36811   assert( pPager->eState!=PAGER_ERROR );
36812   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
36813     return SQLITE_OK;
36814   }
36815
36816   releaseAllSavepoints(pPager);
36817   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
36818   if( isOpen(pPager->jfd) ){
36819     assert( !pagerUseWal(pPager) );
36820
36821     /* Finalize the journal file. */
36822     if( sqlite3IsMemJournal(pPager->jfd) ){
36823       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
36824       sqlite3OsClose(pPager->jfd);
36825     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
36826       if( pPager->journalOff==0 ){
36827         rc = SQLITE_OK;
36828       }else{
36829         rc = sqlite3OsTruncate(pPager->jfd, 0);
36830       }
36831       pPager->journalOff = 0;
36832     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
36833       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
36834     ){
36835       rc = zeroJournalHdr(pPager, hasMaster);
36836       pPager->journalOff = 0;
36837     }else{
36838       /* This branch may be executed with Pager.journalMode==MEMORY if
36839       ** a hot-journal was just rolled back. In this case the journal
36840       ** file should be closed and deleted. If this connection writes to
36841       ** the database file, it will do so using an in-memory journal. 
36842       */
36843       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
36844            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
36845            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
36846       );
36847       sqlite3OsClose(pPager->jfd);
36848       if( !pPager->tempFile ){
36849         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
36850       }
36851     }
36852   }
36853
36854 #ifdef SQLITE_CHECK_PAGES
36855   sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
36856   if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
36857     PgHdr *p = pager_lookup(pPager, 1);
36858     if( p ){
36859       p->pageHash = 0;
36860       sqlite3PagerUnref(p);
36861     }
36862   }
36863 #endif
36864
36865   sqlite3BitvecDestroy(pPager->pInJournal);
36866   pPager->pInJournal = 0;
36867   pPager->nRec = 0;
36868   sqlite3PcacheCleanAll(pPager->pPCache);
36869   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
36870
36871   if( pagerUseWal(pPager) ){
36872     /* Drop the WAL write-lock, if any. Also, if the connection was in 
36873     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE 
36874     ** lock held on the database file.
36875     */
36876     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
36877     assert( rc2==SQLITE_OK );
36878   }
36879   if( !pPager->exclusiveMode 
36880    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
36881   ){
36882     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
36883     pPager->changeCountDone = 0;
36884   }
36885   pPager->eState = PAGER_READER;
36886   pPager->setMaster = 0;
36887
36888   return (rc==SQLITE_OK?rc2:rc);
36889 }
36890
36891 /*
36892 ** Execute a rollback if a transaction is active and unlock the 
36893 ** database file. 
36894 **
36895 ** If the pager has already entered the ERROR state, do not attempt 
36896 ** the rollback at this time. Instead, pager_unlock() is called. The
36897 ** call to pager_unlock() will discard all in-memory pages, unlock
36898 ** the database file and move the pager back to OPEN state. If this 
36899 ** means that there is a hot-journal left in the file-system, the next 
36900 ** connection to obtain a shared lock on the pager (which may be this one) 
36901 ** will roll it back.
36902 **
36903 ** If the pager has not already entered the ERROR state, but an IO or
36904 ** malloc error occurs during a rollback, then this will itself cause 
36905 ** the pager to enter the ERROR state. Which will be cleared by the
36906 ** call to pager_unlock(), as described above.
36907 */
36908 static void pagerUnlockAndRollback(Pager *pPager){
36909   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
36910     assert( assert_pager_state(pPager) );
36911     if( pPager->eState>=PAGER_WRITER_LOCKED ){
36912       sqlite3BeginBenignMalloc();
36913       sqlite3PagerRollback(pPager);
36914       sqlite3EndBenignMalloc();
36915     }else if( !pPager->exclusiveMode ){
36916       assert( pPager->eState==PAGER_READER );
36917       pager_end_transaction(pPager, 0);
36918     }
36919   }
36920   pager_unlock(pPager);
36921 }
36922
36923 /*
36924 ** Parameter aData must point to a buffer of pPager->pageSize bytes
36925 ** of data. Compute and return a checksum based ont the contents of the 
36926 ** page of data and the current value of pPager->cksumInit.
36927 **
36928 ** This is not a real checksum. It is really just the sum of the 
36929 ** random initial value (pPager->cksumInit) and every 200th byte
36930 ** of the page data, starting with byte offset (pPager->pageSize%200).
36931 ** Each byte is interpreted as an 8-bit unsigned integer.
36932 **
36933 ** Changing the formula used to compute this checksum results in an
36934 ** incompatible journal file format.
36935 **
36936 ** If journal corruption occurs due to a power failure, the most likely 
36937 ** scenario is that one end or the other of the record will be changed. 
36938 ** It is much less likely that the two ends of the journal record will be
36939 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
36940 ** though fast and simple, catches the mostly likely kind of corruption.
36941 */
36942 static u32 pager_cksum(Pager *pPager, const u8 *aData){
36943   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
36944   int i = pPager->pageSize-200;          /* Loop counter */
36945   while( i>0 ){
36946     cksum += aData[i];
36947     i -= 200;
36948   }
36949   return cksum;
36950 }
36951
36952 /*
36953 ** Report the current page size and number of reserved bytes back
36954 ** to the codec.
36955 */
36956 #ifdef SQLITE_HAS_CODEC
36957 static void pagerReportSize(Pager *pPager){
36958   if( pPager->xCodecSizeChng ){
36959     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
36960                            (int)pPager->nReserve);
36961   }
36962 }
36963 #else
36964 # define pagerReportSize(X)     /* No-op if we do not support a codec */
36965 #endif
36966
36967 /*
36968 ** Read a single page from either the journal file (if isMainJrnl==1) or
36969 ** from the sub-journal (if isMainJrnl==0) and playback that page.
36970 ** The page begins at offset *pOffset into the file. The *pOffset
36971 ** value is increased to the start of the next page in the journal.
36972 **
36973 ** The main rollback journal uses checksums - the statement journal does 
36974 ** not.
36975 **
36976 ** If the page number of the page record read from the (sub-)journal file
36977 ** is greater than the current value of Pager.dbSize, then playback is
36978 ** skipped and SQLITE_OK is returned.
36979 **
36980 ** If pDone is not NULL, then it is a record of pages that have already
36981 ** been played back.  If the page at *pOffset has already been played back
36982 ** (if the corresponding pDone bit is set) then skip the playback.
36983 ** Make sure the pDone bit corresponding to the *pOffset page is set
36984 ** prior to returning.
36985 **
36986 ** If the page record is successfully read from the (sub-)journal file
36987 ** and played back, then SQLITE_OK is returned. If an IO error occurs
36988 ** while reading the record from the (sub-)journal file or while writing
36989 ** to the database file, then the IO error code is returned. If data
36990 ** is successfully read from the (sub-)journal file but appears to be
36991 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
36992 ** two circumstances:
36993 ** 
36994 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
36995 **   * If the record is being rolled back from the main journal file
36996 **     and the checksum field does not match the record content.
36997 **
36998 ** Neither of these two scenarios are possible during a savepoint rollback.
36999 **
37000 ** If this is a savepoint rollback, then memory may have to be dynamically
37001 ** allocated by this function. If this is the case and an allocation fails,
37002 ** SQLITE_NOMEM is returned.
37003 */
37004 static int pager_playback_one_page(
37005   Pager *pPager,                /* The pager being played back */
37006   i64 *pOffset,                 /* Offset of record to playback */
37007   Bitvec *pDone,                /* Bitvec of pages already played back */
37008   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
37009   int isSavepnt                 /* True for a savepoint rollback */
37010 ){
37011   int rc;
37012   PgHdr *pPg;                   /* An existing page in the cache */
37013   Pgno pgno;                    /* The page number of a page in journal */
37014   u32 cksum;                    /* Checksum used for sanity checking */
37015   char *aData;                  /* Temporary storage for the page */
37016   sqlite3_file *jfd;            /* The file descriptor for the journal file */
37017   int isSynced;                 /* True if journal page is synced */
37018
37019   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
37020   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
37021   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
37022   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
37023
37024   aData = pPager->pTmpSpace;
37025   assert( aData );         /* Temp storage must have already been allocated */
37026   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
37027
37028   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction 
37029   ** or savepoint rollback done at the request of the caller) or this is
37030   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
37031   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
37032   ** only reads from the main journal, not the sub-journal.
37033   */
37034   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
37035        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
37036   );
37037   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
37038
37039   /* Read the page number and page data from the journal or sub-journal
37040   ** file. Return an error code to the caller if an IO error occurs.
37041   */
37042   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
37043   rc = read32bits(jfd, *pOffset, &pgno);
37044   if( rc!=SQLITE_OK ) return rc;
37045   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
37046   if( rc!=SQLITE_OK ) return rc;
37047   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
37048
37049   /* Sanity checking on the page.  This is more important that I originally
37050   ** thought.  If a power failure occurs while the journal is being written,
37051   ** it could cause invalid data to be written into the journal.  We need to
37052   ** detect this invalid data (with high probability) and ignore it.
37053   */
37054   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
37055     assert( !isSavepnt );
37056     return SQLITE_DONE;
37057   }
37058   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
37059     return SQLITE_OK;
37060   }
37061   if( isMainJrnl ){
37062     rc = read32bits(jfd, (*pOffset)-4, &cksum);
37063     if( rc ) return rc;
37064     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
37065       return SQLITE_DONE;
37066     }
37067   }
37068
37069   /* If this page has already been played by before during the current
37070   ** rollback, then don't bother to play it back again.
37071   */
37072   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
37073     return rc;
37074   }
37075
37076   /* When playing back page 1, restore the nReserve setting
37077   */
37078   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
37079     pPager->nReserve = ((u8*)aData)[20];
37080     pagerReportSize(pPager);
37081   }
37082
37083   /* If the pager is in CACHEMOD state, then there must be a copy of this
37084   ** page in the pager cache. In this case just update the pager cache,
37085   ** not the database file. The page is left marked dirty in this case.
37086   **
37087   ** An exception to the above rule: If the database is in no-sync mode
37088   ** and a page is moved during an incremental vacuum then the page may
37089   ** not be in the pager cache. Later: if a malloc() or IO error occurs
37090   ** during a Movepage() call, then the page may not be in the cache
37091   ** either. So the condition described in the above paragraph is not
37092   ** assert()able.
37093   **
37094   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
37095   ** pager cache if it exists and the main file. The page is then marked 
37096   ** not dirty. Since this code is only executed in PAGER_OPEN state for
37097   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
37098   ** if the pager is in OPEN state.
37099   **
37100   ** Ticket #1171:  The statement journal might contain page content that is
37101   ** different from the page content at the start of the transaction.
37102   ** This occurs when a page is changed prior to the start of a statement
37103   ** then changed again within the statement.  When rolling back such a
37104   ** statement we must not write to the original database unless we know
37105   ** for certain that original page contents are synced into the main rollback
37106   ** journal.  Otherwise, a power loss might leave modified data in the
37107   ** database file without an entry in the rollback journal that can
37108   ** restore the database to its original form.  Two conditions must be
37109   ** met before writing to the database files. (1) the database must be
37110   ** locked.  (2) we know that the original page content is fully synced
37111   ** in the main journal either because the page is not in cache or else
37112   ** the page is marked as needSync==0.
37113   **
37114   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
37115   ** is possible to fail a statement on a database that does not yet exist.
37116   ** Do not attempt to write if database file has never been opened.
37117   */
37118   if( pagerUseWal(pPager) ){
37119     pPg = 0;
37120   }else{
37121     pPg = pager_lookup(pPager, pgno);
37122   }
37123   assert( pPg || !MEMDB );
37124   assert( pPager->eState!=PAGER_OPEN || pPg==0 );
37125   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
37126            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
37127            (isMainJrnl?"main-journal":"sub-journal")
37128   ));
37129   if( isMainJrnl ){
37130     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
37131   }else{
37132     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
37133   }
37134   if( isOpen(pPager->fd)
37135    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
37136    && isSynced
37137   ){
37138     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
37139     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
37140     assert( !pagerUseWal(pPager) );
37141     rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
37142     if( pgno>pPager->dbFileSize ){
37143       pPager->dbFileSize = pgno;
37144     }
37145     if( pPager->pBackup ){
37146       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
37147       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
37148       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
37149     }
37150   }else if( !isMainJrnl && pPg==0 ){
37151     /* If this is a rollback of a savepoint and data was not written to
37152     ** the database and the page is not in-memory, there is a potential
37153     ** problem. When the page is next fetched by the b-tree layer, it 
37154     ** will be read from the database file, which may or may not be 
37155     ** current. 
37156     **
37157     ** There are a couple of different ways this can happen. All are quite
37158     ** obscure. When running in synchronous mode, this can only happen 
37159     ** if the page is on the free-list at the start of the transaction, then
37160     ** populated, then moved using sqlite3PagerMovepage().
37161     **
37162     ** The solution is to add an in-memory page to the cache containing
37163     ** the data just read from the sub-journal. Mark the page as dirty 
37164     ** and if the pager requires a journal-sync, then mark the page as 
37165     ** requiring a journal-sync before it is written.
37166     */
37167     assert( isSavepnt );
37168     assert( pPager->doNotSpill==0 );
37169     pPager->doNotSpill++;
37170     rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
37171     assert( pPager->doNotSpill==1 );
37172     pPager->doNotSpill--;
37173     if( rc!=SQLITE_OK ) return rc;
37174     pPg->flags &= ~PGHDR_NEED_READ;
37175     sqlite3PcacheMakeDirty(pPg);
37176   }
37177   if( pPg ){
37178     /* No page should ever be explicitly rolled back that is in use, except
37179     ** for page 1 which is held in use in order to keep the lock on the
37180     ** database active. However such a page may be rolled back as a result
37181     ** of an internal error resulting in an automatic call to
37182     ** sqlite3PagerRollback().
37183     */
37184     void *pData;
37185     pData = pPg->pData;
37186     memcpy(pData, (u8*)aData, pPager->pageSize);
37187     pPager->xReiniter(pPg);
37188     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
37189       /* If the contents of this page were just restored from the main 
37190       ** journal file, then its content must be as they were when the 
37191       ** transaction was first opened. In this case we can mark the page
37192       ** as clean, since there will be no need to write it out to the
37193       ** database.
37194       **
37195       ** There is one exception to this rule. If the page is being rolled
37196       ** back as part of a savepoint (or statement) rollback from an 
37197       ** unsynced portion of the main journal file, then it is not safe
37198       ** to mark the page as clean. This is because marking the page as
37199       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
37200       ** already in the journal file (recorded in Pager.pInJournal) and
37201       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
37202       ** again within this transaction, it will be marked as dirty but
37203       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
37204       ** be written out into the database file before its journal file
37205       ** segment is synced. If a crash occurs during or following this,
37206       ** database corruption may ensue.
37207       */
37208       assert( !pagerUseWal(pPager) );
37209       sqlite3PcacheMakeClean(pPg);
37210     }
37211     pager_set_pagehash(pPg);
37212
37213     /* If this was page 1, then restore the value of Pager.dbFileVers.
37214     ** Do this before any decoding. */
37215     if( pgno==1 ){
37216       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
37217     }
37218
37219     /* Decode the page just read from disk */
37220     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
37221     sqlite3PcacheRelease(pPg);
37222   }
37223   return rc;
37224 }
37225
37226 /*
37227 ** Parameter zMaster is the name of a master journal file. A single journal
37228 ** file that referred to the master journal file has just been rolled back.
37229 ** This routine checks if it is possible to delete the master journal file,
37230 ** and does so if it is.
37231 **
37232 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
37233 ** available for use within this function.
37234 **
37235 ** When a master journal file is created, it is populated with the names 
37236 ** of all of its child journals, one after another, formatted as utf-8 
37237 ** encoded text. The end of each child journal file is marked with a 
37238 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
37239 ** file for a transaction involving two databases might be:
37240 **
37241 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
37242 **
37243 ** A master journal file may only be deleted once all of its child 
37244 ** journals have been rolled back.
37245 **
37246 ** This function reads the contents of the master-journal file into 
37247 ** memory and loops through each of the child journal names. For
37248 ** each child journal, it checks if:
37249 **
37250 **   * if the child journal exists, and if so
37251 **   * if the child journal contains a reference to master journal 
37252 **     file zMaster
37253 **
37254 ** If a child journal can be found that matches both of the criteria
37255 ** above, this function returns without doing anything. Otherwise, if
37256 ** no such child journal can be found, file zMaster is deleted from
37257 ** the file-system using sqlite3OsDelete().
37258 **
37259 ** If an IO error within this function, an error code is returned. This
37260 ** function allocates memory by calling sqlite3Malloc(). If an allocation
37261 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors 
37262 ** occur, SQLITE_OK is returned.
37263 **
37264 ** TODO: This function allocates a single block of memory to load
37265 ** the entire contents of the master journal file. This could be
37266 ** a couple of kilobytes or so - potentially larger than the page 
37267 ** size.
37268 */
37269 static int pager_delmaster(Pager *pPager, const char *zMaster){
37270   sqlite3_vfs *pVfs = pPager->pVfs;
37271   int rc;                   /* Return code */
37272   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
37273   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
37274   char *zMasterJournal = 0; /* Contents of master journal file */
37275   i64 nMasterJournal;       /* Size of master journal file */
37276   char *zJournal;           /* Pointer to one journal within MJ file */
37277   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
37278   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
37279
37280   /* Allocate space for both the pJournal and pMaster file descriptors.
37281   ** If successful, open the master journal file for reading.
37282   */
37283   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
37284   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
37285   if( !pMaster ){
37286     rc = SQLITE_NOMEM;
37287   }else{
37288     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
37289     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
37290   }
37291   if( rc!=SQLITE_OK ) goto delmaster_out;
37292
37293   /* Load the entire master journal file into space obtained from
37294   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
37295   ** sufficient space (in zMasterPtr) to hold the names of master
37296   ** journal files extracted from regular rollback-journals.
37297   */
37298   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
37299   if( rc!=SQLITE_OK ) goto delmaster_out;
37300   nMasterPtr = pVfs->mxPathname+1;
37301   zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
37302   if( !zMasterJournal ){
37303     rc = SQLITE_NOMEM;
37304     goto delmaster_out;
37305   }
37306   zMasterPtr = &zMasterJournal[nMasterJournal+1];
37307   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
37308   if( rc!=SQLITE_OK ) goto delmaster_out;
37309   zMasterJournal[nMasterJournal] = 0;
37310
37311   zJournal = zMasterJournal;
37312   while( (zJournal-zMasterJournal)<nMasterJournal ){
37313     int exists;
37314     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
37315     if( rc!=SQLITE_OK ){
37316       goto delmaster_out;
37317     }
37318     if( exists ){
37319       /* One of the journals pointed to by the master journal exists.
37320       ** Open it and check if it points at the master journal. If
37321       ** so, return without deleting the master journal file.
37322       */
37323       int c;
37324       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
37325       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
37326       if( rc!=SQLITE_OK ){
37327         goto delmaster_out;
37328       }
37329
37330       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
37331       sqlite3OsClose(pJournal);
37332       if( rc!=SQLITE_OK ){
37333         goto delmaster_out;
37334       }
37335
37336       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
37337       if( c ){
37338         /* We have a match. Do not delete the master journal file. */
37339         goto delmaster_out;
37340       }
37341     }
37342     zJournal += (sqlite3Strlen30(zJournal)+1);
37343   }
37344  
37345   sqlite3OsClose(pMaster);
37346   rc = sqlite3OsDelete(pVfs, zMaster, 0);
37347
37348 delmaster_out:
37349   sqlite3_free(zMasterJournal);
37350   if( pMaster ){
37351     sqlite3OsClose(pMaster);
37352     assert( !isOpen(pJournal) );
37353     sqlite3_free(pMaster);
37354   }
37355   return rc;
37356 }
37357
37358
37359 /*
37360 ** This function is used to change the actual size of the database 
37361 ** file in the file-system. This only happens when committing a transaction,
37362 ** or rolling back a transaction (including rolling back a hot-journal).
37363 **
37364 ** If the main database file is not open, or the pager is not in either
37365 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size 
37366 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes). 
37367 ** If the file on disk is currently larger than nPage pages, then use the VFS
37368 ** xTruncate() method to truncate it.
37369 **
37370 ** Or, it might might be the case that the file on disk is smaller than 
37371 ** nPage pages. Some operating system implementations can get confused if 
37372 ** you try to truncate a file to some size that is larger than it 
37373 ** currently is, so detect this case and write a single zero byte to 
37374 ** the end of the new file instead.
37375 **
37376 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
37377 ** the database file, return the error code to the caller.
37378 */
37379 static int pager_truncate(Pager *pPager, Pgno nPage){
37380   int rc = SQLITE_OK;
37381   assert( pPager->eState!=PAGER_ERROR );
37382   assert( pPager->eState!=PAGER_READER );
37383   
37384   if( isOpen(pPager->fd) 
37385    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) 
37386   ){
37387     i64 currentSize, newSize;
37388     int szPage = pPager->pageSize;
37389     assert( pPager->eLock==EXCLUSIVE_LOCK );
37390     /* TODO: Is it safe to use Pager.dbFileSize here? */
37391     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
37392     newSize = szPage*(i64)nPage;
37393     if( rc==SQLITE_OK && currentSize!=newSize ){
37394       if( currentSize>newSize ){
37395         rc = sqlite3OsTruncate(pPager->fd, newSize);
37396       }else{
37397         char *pTmp = pPager->pTmpSpace;
37398         memset(pTmp, 0, szPage);
37399         testcase( (newSize-szPage) <  currentSize );
37400         testcase( (newSize-szPage) == currentSize );
37401         testcase( (newSize-szPage) >  currentSize );
37402         rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
37403       }
37404       if( rc==SQLITE_OK ){
37405         pPager->dbFileSize = nPage;
37406       }
37407     }
37408   }
37409   return rc;
37410 }
37411
37412 /*
37413 ** Set the value of the Pager.sectorSize variable for the given
37414 ** pager based on the value returned by the xSectorSize method
37415 ** of the open database file. The sector size will be used used 
37416 ** to determine the size and alignment of journal header and 
37417 ** master journal pointers within created journal files.
37418 **
37419 ** For temporary files the effective sector size is always 512 bytes.
37420 **
37421 ** Otherwise, for non-temporary files, the effective sector size is
37422 ** the value returned by the xSectorSize() method rounded up to 32 if
37423 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
37424 ** is greater than MAX_SECTOR_SIZE.
37425 */
37426 static void setSectorSize(Pager *pPager){
37427   assert( isOpen(pPager->fd) || pPager->tempFile );
37428
37429   if( !pPager->tempFile ){
37430     /* Sector size doesn't matter for temporary files. Also, the file
37431     ** may not have been opened yet, in which case the OsSectorSize()
37432     ** call will segfault.
37433     */
37434     pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
37435   }
37436   if( pPager->sectorSize<32 ){
37437     pPager->sectorSize = 512;
37438   }
37439   if( pPager->sectorSize>MAX_SECTOR_SIZE ){
37440     assert( MAX_SECTOR_SIZE>=512 );
37441     pPager->sectorSize = MAX_SECTOR_SIZE;
37442   }
37443 }
37444
37445 /*
37446 ** Playback the journal and thus restore the database file to
37447 ** the state it was in before we started making changes.  
37448 **
37449 ** The journal file format is as follows: 
37450 **
37451 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
37452 **  (2)  4 byte big-endian integer which is the number of valid page records
37453 **       in the journal.  If this value is 0xffffffff, then compute the
37454 **       number of page records from the journal size.
37455 **  (3)  4 byte big-endian integer which is the initial value for the 
37456 **       sanity checksum.
37457 **  (4)  4 byte integer which is the number of pages to truncate the
37458 **       database to during a rollback.
37459 **  (5)  4 byte big-endian integer which is the sector size.  The header
37460 **       is this many bytes in size.
37461 **  (6)  4 byte big-endian integer which is the page size.
37462 **  (7)  zero padding out to the next sector size.
37463 **  (8)  Zero or more pages instances, each as follows:
37464 **        +  4 byte page number.
37465 **        +  pPager->pageSize bytes of data.
37466 **        +  4 byte checksum
37467 **
37468 ** When we speak of the journal header, we mean the first 7 items above.
37469 ** Each entry in the journal is an instance of the 8th item.
37470 **
37471 ** Call the value from the second bullet "nRec".  nRec is the number of
37472 ** valid page entries in the journal.  In most cases, you can compute the
37473 ** value of nRec from the size of the journal file.  But if a power
37474 ** failure occurred while the journal was being written, it could be the
37475 ** case that the size of the journal file had already been increased but
37476 ** the extra entries had not yet made it safely to disk.  In such a case,
37477 ** the value of nRec computed from the file size would be too large.  For
37478 ** that reason, we always use the nRec value in the header.
37479 **
37480 ** If the nRec value is 0xffffffff it means that nRec should be computed
37481 ** from the file size.  This value is used when the user selects the
37482 ** no-sync option for the journal.  A power failure could lead to corruption
37483 ** in this case.  But for things like temporary table (which will be
37484 ** deleted when the power is restored) we don't care.  
37485 **
37486 ** If the file opened as the journal file is not a well-formed
37487 ** journal file then all pages up to the first corrupted page are rolled
37488 ** back (or no pages if the journal header is corrupted). The journal file
37489 ** is then deleted and SQLITE_OK returned, just as if no corruption had
37490 ** been encountered.
37491 **
37492 ** If an I/O or malloc() error occurs, the journal-file is not deleted
37493 ** and an error code is returned.
37494 **
37495 ** The isHot parameter indicates that we are trying to rollback a journal
37496 ** that might be a hot journal.  Or, it could be that the journal is 
37497 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
37498 ** If the journal really is hot, reset the pager cache prior rolling
37499 ** back any content.  If the journal is merely persistent, no reset is
37500 ** needed.
37501 */
37502 static int pager_playback(Pager *pPager, int isHot){
37503   sqlite3_vfs *pVfs = pPager->pVfs;
37504   i64 szJ;                 /* Size of the journal file in bytes */
37505   u32 nRec;                /* Number of Records in the journal */
37506   u32 u;                   /* Unsigned loop counter */
37507   Pgno mxPg = 0;           /* Size of the original file in pages */
37508   int rc;                  /* Result code of a subroutine */
37509   int res = 1;             /* Value returned by sqlite3OsAccess() */
37510   char *zMaster = 0;       /* Name of master journal file if any */
37511   int needPagerReset;      /* True to reset page prior to first page rollback */
37512
37513   /* Figure out how many records are in the journal.  Abort early if
37514   ** the journal is empty.
37515   */
37516   assert( isOpen(pPager->jfd) );
37517   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
37518   if( rc!=SQLITE_OK ){
37519     goto end_playback;
37520   }
37521
37522   /* Read the master journal name from the journal, if it is present.
37523   ** If a master journal file name is specified, but the file is not
37524   ** present on disk, then the journal is not hot and does not need to be
37525   ** played back.
37526   **
37527   ** TODO: Technically the following is an error because it assumes that
37528   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
37529   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
37530   **  mxPathname is 512, which is the same as the minimum allowable value
37531   ** for pageSize.
37532   */
37533   zMaster = pPager->pTmpSpace;
37534   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
37535   if( rc==SQLITE_OK && zMaster[0] ){
37536     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
37537   }
37538   zMaster = 0;
37539   if( rc!=SQLITE_OK || !res ){
37540     goto end_playback;
37541   }
37542   pPager->journalOff = 0;
37543   needPagerReset = isHot;
37544
37545   /* This loop terminates either when a readJournalHdr() or 
37546   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error 
37547   ** occurs. 
37548   */
37549   while( 1 ){
37550     /* Read the next journal header from the journal file.  If there are
37551     ** not enough bytes left in the journal file for a complete header, or
37552     ** it is corrupted, then a process must have failed while writing it.
37553     ** This indicates nothing more needs to be rolled back.
37554     */
37555     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
37556     if( rc!=SQLITE_OK ){ 
37557       if( rc==SQLITE_DONE ){
37558         rc = SQLITE_OK;
37559       }
37560       goto end_playback;
37561     }
37562
37563     /* If nRec is 0xffffffff, then this journal was created by a process
37564     ** working in no-sync mode. This means that the rest of the journal
37565     ** file consists of pages, there are no more journal headers. Compute
37566     ** the value of nRec based on this assumption.
37567     */
37568     if( nRec==0xffffffff ){
37569       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
37570       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
37571     }
37572
37573     /* If nRec is 0 and this rollback is of a transaction created by this
37574     ** process and if this is the final header in the journal, then it means
37575     ** that this part of the journal was being filled but has not yet been
37576     ** synced to disk.  Compute the number of pages based on the remaining
37577     ** size of the file.
37578     **
37579     ** The third term of the test was added to fix ticket #2565.
37580     ** When rolling back a hot journal, nRec==0 always means that the next
37581     ** chunk of the journal contains zero pages to be rolled back.  But
37582     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
37583     ** the journal, it means that the journal might contain additional
37584     ** pages that need to be rolled back and that the number of pages 
37585     ** should be computed based on the journal file size.
37586     */
37587     if( nRec==0 && !isHot &&
37588         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
37589       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
37590     }
37591
37592     /* If this is the first header read from the journal, truncate the
37593     ** database file back to its original size.
37594     */
37595     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
37596       rc = pager_truncate(pPager, mxPg);
37597       if( rc!=SQLITE_OK ){
37598         goto end_playback;
37599       }
37600       pPager->dbSize = mxPg;
37601     }
37602
37603     /* Copy original pages out of the journal and back into the 
37604     ** database file and/or page cache.
37605     */
37606     for(u=0; u<nRec; u++){
37607       if( needPagerReset ){
37608         pager_reset(pPager);
37609         needPagerReset = 0;
37610       }
37611       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
37612       if( rc!=SQLITE_OK ){
37613         if( rc==SQLITE_DONE ){
37614           rc = SQLITE_OK;
37615           pPager->journalOff = szJ;
37616           break;
37617         }else if( rc==SQLITE_IOERR_SHORT_READ ){
37618           /* If the journal has been truncated, simply stop reading and
37619           ** processing the journal. This might happen if the journal was
37620           ** not completely written and synced prior to a crash.  In that
37621           ** case, the database should have never been written in the
37622           ** first place so it is OK to simply abandon the rollback. */
37623           rc = SQLITE_OK;
37624           goto end_playback;
37625         }else{
37626           /* If we are unable to rollback, quit and return the error
37627           ** code.  This will cause the pager to enter the error state
37628           ** so that no further harm will be done.  Perhaps the next
37629           ** process to come along will be able to rollback the database.
37630           */
37631           goto end_playback;
37632         }
37633       }
37634     }
37635   }
37636   /*NOTREACHED*/
37637   assert( 0 );
37638
37639 end_playback:
37640   /* Following a rollback, the database file should be back in its original
37641   ** state prior to the start of the transaction, so invoke the
37642   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
37643   ** assertion that the transaction counter was modified.
37644   */
37645   assert(
37646     pPager->fd->pMethods==0 ||
37647     sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
37648   );
37649
37650   /* If this playback is happening automatically as a result of an IO or 
37651   ** malloc error that occurred after the change-counter was updated but 
37652   ** before the transaction was committed, then the change-counter 
37653   ** modification may just have been reverted. If this happens in exclusive 
37654   ** mode, then subsequent transactions performed by the connection will not
37655   ** update the change-counter at all. This may lead to cache inconsistency
37656   ** problems for other processes at some point in the future. So, just
37657   ** in case this has happened, clear the changeCountDone flag now.
37658   */
37659   pPager->changeCountDone = pPager->tempFile;
37660
37661   if( rc==SQLITE_OK ){
37662     zMaster = pPager->pTmpSpace;
37663     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
37664     testcase( rc!=SQLITE_OK );
37665   }
37666   if( rc==SQLITE_OK
37667    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
37668   ){
37669     rc = sqlite3PagerSync(pPager);
37670   }
37671   if( rc==SQLITE_OK ){
37672     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
37673     testcase( rc!=SQLITE_OK );
37674   }
37675   if( rc==SQLITE_OK && zMaster[0] && res ){
37676     /* If there was a master journal and this routine will return success,
37677     ** see if it is possible to delete the master journal.
37678     */
37679     rc = pager_delmaster(pPager, zMaster);
37680     testcase( rc!=SQLITE_OK );
37681   }
37682
37683   /* The Pager.sectorSize variable may have been updated while rolling
37684   ** back a journal created by a process with a different sector size
37685   ** value. Reset it to the correct value for this process.
37686   */
37687   setSectorSize(pPager);
37688   return rc;
37689 }
37690
37691
37692 /*
37693 ** Read the content for page pPg out of the database file and into 
37694 ** pPg->pData. A shared lock or greater must be held on the database
37695 ** file before this function is called.
37696 **
37697 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
37698 ** the value read from the database file.
37699 **
37700 ** If an IO error occurs, then the IO error is returned to the caller.
37701 ** Otherwise, SQLITE_OK is returned.
37702 */
37703 static int readDbPage(PgHdr *pPg){
37704   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
37705   Pgno pgno = pPg->pgno;       /* Page number to read */
37706   int rc = SQLITE_OK;          /* Return code */
37707   int isInWal = 0;             /* True if page is in log file */
37708   int pgsz = pPager->pageSize; /* Number of bytes to read */
37709
37710   assert( pPager->eState>=PAGER_READER && !MEMDB );
37711   assert( isOpen(pPager->fd) );
37712
37713   if( NEVER(!isOpen(pPager->fd)) ){
37714     assert( pPager->tempFile );
37715     memset(pPg->pData, 0, pPager->pageSize);
37716     return SQLITE_OK;
37717   }
37718
37719   if( pagerUseWal(pPager) ){
37720     /* Try to pull the page from the write-ahead log. */
37721     rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
37722   }
37723   if( rc==SQLITE_OK && !isInWal ){
37724     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
37725     rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
37726     if( rc==SQLITE_IOERR_SHORT_READ ){
37727       rc = SQLITE_OK;
37728     }
37729   }
37730
37731   if( pgno==1 ){
37732     if( rc ){
37733       /* If the read is unsuccessful, set the dbFileVers[] to something
37734       ** that will never be a valid file version.  dbFileVers[] is a copy
37735       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
37736       ** zero or the size of the database in page. Bytes 32..35 and 35..39
37737       ** should be page numbers which are never 0xffffffff.  So filling
37738       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
37739       **
37740       ** For an encrypted database, the situation is more complex:  bytes
37741       ** 24..39 of the database are white noise.  But the probability of
37742       ** white noising equaling 16 bytes of 0xff is vanishingly small so
37743       ** we should still be ok.
37744       */
37745       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
37746     }else{
37747       u8 *dbFileVers = &((u8*)pPg->pData)[24];
37748       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
37749     }
37750   }
37751   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
37752
37753   PAGER_INCR(sqlite3_pager_readdb_count);
37754   PAGER_INCR(pPager->nRead);
37755   IOTRACE(("PGIN %p %d\n", pPager, pgno));
37756   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
37757                PAGERID(pPager), pgno, pager_pagehash(pPg)));
37758
37759   return rc;
37760 }
37761
37762 #ifndef SQLITE_OMIT_WAL
37763 /*
37764 ** This function is invoked once for each page that has already been 
37765 ** written into the log file when a WAL transaction is rolled back.
37766 ** Parameter iPg is the page number of said page. The pCtx argument 
37767 ** is actually a pointer to the Pager structure.
37768 **
37769 ** If page iPg is present in the cache, and has no outstanding references,
37770 ** it is discarded. Otherwise, if there are one or more outstanding
37771 ** references, the page content is reloaded from the database. If the
37772 ** attempt to reload content from the database is required and fails, 
37773 ** return an SQLite error code. Otherwise, SQLITE_OK.
37774 */
37775 static int pagerUndoCallback(void *pCtx, Pgno iPg){
37776   int rc = SQLITE_OK;
37777   Pager *pPager = (Pager *)pCtx;
37778   PgHdr *pPg;
37779
37780   pPg = sqlite3PagerLookup(pPager, iPg);
37781   if( pPg ){
37782     if( sqlite3PcachePageRefcount(pPg)==1 ){
37783       sqlite3PcacheDrop(pPg);
37784     }else{
37785       rc = readDbPage(pPg);
37786       if( rc==SQLITE_OK ){
37787         pPager->xReiniter(pPg);
37788       }
37789       sqlite3PagerUnref(pPg);
37790     }
37791   }
37792
37793   /* Normally, if a transaction is rolled back, any backup processes are
37794   ** updated as data is copied out of the rollback journal and into the
37795   ** database. This is not generally possible with a WAL database, as
37796   ** rollback involves simply truncating the log file. Therefore, if one
37797   ** or more frames have already been written to the log (and therefore 
37798   ** also copied into the backup databases) as part of this transaction,
37799   ** the backups must be restarted.
37800   */
37801   sqlite3BackupRestart(pPager->pBackup);
37802
37803   return rc;
37804 }
37805
37806 /*
37807 ** This function is called to rollback a transaction on a WAL database.
37808 */
37809 static int pagerRollbackWal(Pager *pPager){
37810   int rc;                         /* Return Code */
37811   PgHdr *pList;                   /* List of dirty pages to revert */
37812
37813   /* For all pages in the cache that are currently dirty or have already
37814   ** been written (but not committed) to the log file, do one of the 
37815   ** following:
37816   **
37817   **   + Discard the cached page (if refcount==0), or
37818   **   + Reload page content from the database (if refcount>0).
37819   */
37820   pPager->dbSize = pPager->dbOrigSize;
37821   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
37822   pList = sqlite3PcacheDirtyList(pPager->pPCache);
37823   while( pList && rc==SQLITE_OK ){
37824     PgHdr *pNext = pList->pDirty;
37825     rc = pagerUndoCallback((void *)pPager, pList->pgno);
37826     pList = pNext;
37827   }
37828
37829   return rc;
37830 }
37831
37832
37833 /*
37834 ** Update the value of the change-counter at offsets 24 and 92 in
37835 ** the header and the sqlite version number at offset 96.
37836 **
37837 ** This is an unconditional update.  See also the pager_incr_changecounter()
37838 ** routine which only updates the change-counter if the update is actually
37839 ** needed, as determined by the pPager->changeCountDone state variable.
37840 */
37841 static void pager_write_changecounter(PgHdr *pPg){
37842   u32 change_counter;
37843
37844   /* Increment the value just read and write it back to byte 24. */
37845   change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
37846   put32bits(((char*)pPg->pData)+24, change_counter);
37847
37848   /* Also store the SQLite version number in bytes 96..99 and in
37849   ** bytes 92..95 store the change counter for which the version number
37850   ** is valid. */
37851   put32bits(((char*)pPg->pData)+92, change_counter);
37852   put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
37853 }
37854
37855 /*
37856 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
37857 ** the contents of the list of pages headed by pList (connected by pDirty),
37858 ** this function notifies any active backup processes that the pages have
37859 ** changed.
37860 **
37861 ** The list of pages passed into this routine is always sorted by page number.
37862 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
37863 */ 
37864 static int pagerWalFrames(
37865   Pager *pPager,                  /* Pager object */
37866   PgHdr *pList,                   /* List of frames to log */
37867   Pgno nTruncate,                 /* Database size after this commit */
37868   int isCommit,                   /* True if this is a commit */
37869   int syncFlags                   /* Flags to pass to OsSync() (or 0) */
37870 ){
37871   int rc;                         /* Return code */
37872 #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
37873   PgHdr *p;                       /* For looping over pages */
37874 #endif
37875
37876   assert( pPager->pWal );
37877 #ifdef SQLITE_DEBUG
37878   /* Verify that the page list is in accending order */
37879   for(p=pList; p && p->pDirty; p=p->pDirty){
37880     assert( p->pgno < p->pDirty->pgno );
37881   }
37882 #endif
37883
37884   if( pList->pgno==1 ) pager_write_changecounter(pList);
37885   rc = sqlite3WalFrames(pPager->pWal, 
37886       pPager->pageSize, pList, nTruncate, isCommit, syncFlags
37887   );
37888   if( rc==SQLITE_OK && pPager->pBackup ){
37889     PgHdr *p;
37890     for(p=pList; p; p=p->pDirty){
37891       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
37892     }
37893   }
37894
37895 #ifdef SQLITE_CHECK_PAGES
37896   for(p=pList; p; p=p->pDirty){
37897     pager_set_pagehash(p);
37898   }
37899 #endif
37900
37901   return rc;
37902 }
37903
37904 /*
37905 ** Begin a read transaction on the WAL.
37906 **
37907 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
37908 ** makes a snapshot of the database at the current point in time and preserves
37909 ** that snapshot for use by the reader in spite of concurrently changes by
37910 ** other writers or checkpointers.
37911 */
37912 static int pagerBeginReadTransaction(Pager *pPager){
37913   int rc;                         /* Return code */
37914   int changed = 0;                /* True if cache must be reset */
37915
37916   assert( pagerUseWal(pPager) );
37917   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
37918
37919   /* sqlite3WalEndReadTransaction() was not called for the previous
37920   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
37921   ** are in locking_mode=NORMAL and EndRead() was previously called,
37922   ** the duplicate call is harmless.
37923   */
37924   sqlite3WalEndReadTransaction(pPager->pWal);
37925
37926   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
37927   if( rc!=SQLITE_OK || changed ){
37928     pager_reset(pPager);
37929   }
37930
37931   return rc;
37932 }
37933 #endif
37934
37935 /*
37936 ** This function is called as part of the transition from PAGER_OPEN
37937 ** to PAGER_READER state to determine the size of the database file
37938 ** in pages (assuming the page size currently stored in Pager.pageSize).
37939 **
37940 ** If no error occurs, SQLITE_OK is returned and the size of the database
37941 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
37942 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
37943 */
37944 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
37945   Pgno nPage;                     /* Value to return via *pnPage */
37946
37947   /* Query the WAL sub-system for the database size. The WalDbsize()
37948   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
37949   ** if the database size is not available. The database size is not
37950   ** available from the WAL sub-system if the log file is empty or
37951   ** contains no valid committed transactions.
37952   */
37953   assert( pPager->eState==PAGER_OPEN );
37954   assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
37955   nPage = sqlite3WalDbsize(pPager->pWal);
37956
37957   /* If the database size was not available from the WAL sub-system,
37958   ** determine it based on the size of the database file. If the size
37959   ** of the database file is not an integer multiple of the page-size,
37960   ** round down to the nearest page. Except, any file larger than 0
37961   ** bytes in size is considered to contain at least one page.
37962   */
37963   if( nPage==0 ){
37964     i64 n = 0;                    /* Size of db file in bytes */
37965     assert( isOpen(pPager->fd) || pPager->tempFile );
37966     if( isOpen(pPager->fd) ){
37967       int rc = sqlite3OsFileSize(pPager->fd, &n);
37968       if( rc!=SQLITE_OK ){
37969         return rc;
37970       }
37971     }
37972     nPage = (Pgno)(n / pPager->pageSize);
37973     if( nPage==0 && n>0 ){
37974       nPage = 1;
37975     }
37976   }
37977
37978   /* If the current number of pages in the file is greater than the
37979   ** configured maximum pager number, increase the allowed limit so
37980   ** that the file can be read.
37981   */
37982   if( nPage>pPager->mxPgno ){
37983     pPager->mxPgno = (Pgno)nPage;
37984   }
37985
37986   *pnPage = nPage;
37987   return SQLITE_OK;
37988 }
37989
37990 #ifndef SQLITE_OMIT_WAL
37991 /*
37992 ** Check if the *-wal file that corresponds to the database opened by pPager
37993 ** exists if the database is not empy, or verify that the *-wal file does
37994 ** not exist (by deleting it) if the database file is empty.
37995 **
37996 ** If the database is not empty and the *-wal file exists, open the pager
37997 ** in WAL mode.  If the database is empty or if no *-wal file exists and
37998 ** if no error occurs, make sure Pager.journalMode is not set to
37999 ** PAGER_JOURNALMODE_WAL.
38000 **
38001 ** Return SQLITE_OK or an error code.
38002 **
38003 ** The caller must hold a SHARED lock on the database file to call this
38004 ** function. Because an EXCLUSIVE lock on the db file is required to delete 
38005 ** a WAL on a none-empty database, this ensures there is no race condition 
38006 ** between the xAccess() below and an xDelete() being executed by some 
38007 ** other connection.
38008 */
38009 static int pagerOpenWalIfPresent(Pager *pPager){
38010   int rc = SQLITE_OK;
38011   assert( pPager->eState==PAGER_OPEN );
38012   assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
38013
38014   if( !pPager->tempFile ){
38015     int isWal;                    /* True if WAL file exists */
38016     Pgno nPage;                   /* Size of the database file */
38017
38018     rc = pagerPagecount(pPager, &nPage);
38019     if( rc ) return rc;
38020     if( nPage==0 ){
38021       rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
38022       isWal = 0;
38023     }else{
38024       rc = sqlite3OsAccess(
38025           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
38026       );
38027     }
38028     if( rc==SQLITE_OK ){
38029       if( isWal ){
38030         testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
38031         rc = sqlite3PagerOpenWal(pPager, 0);
38032       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
38033         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
38034       }
38035     }
38036   }
38037   return rc;
38038 }
38039 #endif
38040
38041 /*
38042 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
38043 ** the entire master journal file. The case pSavepoint==NULL occurs when 
38044 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction 
38045 ** savepoint.
38046 **
38047 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is 
38048 ** being rolled back), then the rollback consists of up to three stages,
38049 ** performed in the order specified:
38050 **
38051 **   * Pages are played back from the main journal starting at byte
38052 **     offset PagerSavepoint.iOffset and continuing to 
38053 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
38054 **     file if PagerSavepoint.iHdrOffset is zero.
38055 **
38056 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
38057 **     back starting from the journal header immediately following 
38058 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
38059 **
38060 **   * Pages are then played back from the sub-journal file, starting
38061 **     with the PagerSavepoint.iSubRec and continuing to the end of
38062 **     the journal file.
38063 **
38064 ** Throughout the rollback process, each time a page is rolled back, the
38065 ** corresponding bit is set in a bitvec structure (variable pDone in the
38066 ** implementation below). This is used to ensure that a page is only
38067 ** rolled back the first time it is encountered in either journal.
38068 **
38069 ** If pSavepoint is NULL, then pages are only played back from the main
38070 ** journal file. There is no need for a bitvec in this case.
38071 **
38072 ** In either case, before playback commences the Pager.dbSize variable
38073 ** is reset to the value that it held at the start of the savepoint 
38074 ** (or transaction). No page with a page-number greater than this value
38075 ** is played back. If one is encountered it is simply skipped.
38076 */
38077 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
38078   i64 szJ;                 /* Effective size of the main journal */
38079   i64 iHdrOff;             /* End of first segment of main-journal records */
38080   int rc = SQLITE_OK;      /* Return code */
38081   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
38082
38083   assert( pPager->eState!=PAGER_ERROR );
38084   assert( pPager->eState>=PAGER_WRITER_LOCKED );
38085
38086   /* Allocate a bitvec to use to store the set of pages rolled back */
38087   if( pSavepoint ){
38088     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
38089     if( !pDone ){
38090       return SQLITE_NOMEM;
38091     }
38092   }
38093
38094   /* Set the database size back to the value it was before the savepoint 
38095   ** being reverted was opened.
38096   */
38097   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
38098   pPager->changeCountDone = pPager->tempFile;
38099
38100   if( !pSavepoint && pagerUseWal(pPager) ){
38101     return pagerRollbackWal(pPager);
38102   }
38103
38104   /* Use pPager->journalOff as the effective size of the main rollback
38105   ** journal.  The actual file might be larger than this in
38106   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
38107   ** past pPager->journalOff is off-limits to us.
38108   */
38109   szJ = pPager->journalOff;
38110   assert( pagerUseWal(pPager)==0 || szJ==0 );
38111
38112   /* Begin by rolling back records from the main journal starting at
38113   ** PagerSavepoint.iOffset and continuing to the next journal header.
38114   ** There might be records in the main journal that have a page number
38115   ** greater than the current database size (pPager->dbSize) but those
38116   ** will be skipped automatically.  Pages are added to pDone as they
38117   ** are played back.
38118   */
38119   if( pSavepoint && !pagerUseWal(pPager) ){
38120     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
38121     pPager->journalOff = pSavepoint->iOffset;
38122     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
38123       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
38124     }
38125     assert( rc!=SQLITE_DONE );
38126   }else{
38127     pPager->journalOff = 0;
38128   }
38129
38130   /* Continue rolling back records out of the main journal starting at
38131   ** the first journal header seen and continuing until the effective end
38132   ** of the main journal file.  Continue to skip out-of-range pages and
38133   ** continue adding pages rolled back to pDone.
38134   */
38135   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
38136     u32 ii;            /* Loop counter */
38137     u32 nJRec = 0;     /* Number of Journal Records */
38138     u32 dummy;
38139     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
38140     assert( rc!=SQLITE_DONE );
38141
38142     /*
38143     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
38144     ** test is related to ticket #2565.  See the discussion in the
38145     ** pager_playback() function for additional information.
38146     */
38147     if( nJRec==0 
38148      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
38149     ){
38150       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
38151     }
38152     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
38153       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
38154     }
38155     assert( rc!=SQLITE_DONE );
38156   }
38157   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
38158
38159   /* Finally,  rollback pages from the sub-journal.  Page that were
38160   ** previously rolled back out of the main journal (and are hence in pDone)
38161   ** will be skipped.  Out-of-range pages are also skipped.
38162   */
38163   if( pSavepoint ){
38164     u32 ii;            /* Loop counter */
38165     i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
38166
38167     if( pagerUseWal(pPager) ){
38168       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
38169     }
38170     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
38171       assert( offset==ii*(4+pPager->pageSize) );
38172       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
38173     }
38174     assert( rc!=SQLITE_DONE );
38175   }
38176
38177   sqlite3BitvecDestroy(pDone);
38178   if( rc==SQLITE_OK ){
38179     pPager->journalOff = szJ;
38180   }
38181
38182   return rc;
38183 }
38184
38185 /*
38186 ** Change the maximum number of in-memory pages that are allowed.
38187 */
38188 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
38189   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
38190 }
38191
38192 /*
38193 ** Adjust the robustness of the database to damage due to OS crashes
38194 ** or power failures by changing the number of syncs()s when writing
38195 ** the rollback journal.  There are three levels:
38196 **
38197 **    OFF       sqlite3OsSync() is never called.  This is the default
38198 **              for temporary and transient files.
38199 **
38200 **    NORMAL    The journal is synced once before writes begin on the
38201 **              database.  This is normally adequate protection, but
38202 **              it is theoretically possible, though very unlikely,
38203 **              that an inopertune power failure could leave the journal
38204 **              in a state which would cause damage to the database
38205 **              when it is rolled back.
38206 **
38207 **    FULL      The journal is synced twice before writes begin on the
38208 **              database (with some additional information - the nRec field
38209 **              of the journal header - being written in between the two
38210 **              syncs).  If we assume that writing a
38211 **              single disk sector is atomic, then this mode provides
38212 **              assurance that the journal will not be corrupted to the
38213 **              point of causing damage to the database during rollback.
38214 **
38215 ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
38216 ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
38217 ** prior to the start of checkpoint and that the database file is synced
38218 ** at the conclusion of the checkpoint if the entire content of the WAL
38219 ** was written back into the database.  But no sync operations occur for
38220 ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
38221 ** file is synced following each commit operation, in addition to the
38222 ** syncs associated with NORMAL.
38223 **
38224 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
38225 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
38226 ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
38227 ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
38228 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
38229 ** synchronous=FULL versus synchronous=NORMAL setting determines when
38230 ** the xSync primitive is called and is relevant to all platforms.
38231 **
38232 ** Numeric values associated with these states are OFF==1, NORMAL=2,
38233 ** and FULL=3.
38234 */
38235 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
38236 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(
38237   Pager *pPager,        /* The pager to set safety level for */
38238   int level,            /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */  
38239   int bFullFsync,       /* PRAGMA fullfsync */
38240   int bCkptFullFsync    /* PRAGMA checkpoint_fullfsync */
38241 ){
38242   assert( level>=1 && level<=3 );
38243   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
38244   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
38245   if( pPager->noSync ){
38246     pPager->syncFlags = 0;
38247     pPager->ckptSyncFlags = 0;
38248   }else if( bFullFsync ){
38249     pPager->syncFlags = SQLITE_SYNC_FULL;
38250     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
38251   }else if( bCkptFullFsync ){
38252     pPager->syncFlags = SQLITE_SYNC_NORMAL;
38253     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
38254   }else{
38255     pPager->syncFlags = SQLITE_SYNC_NORMAL;
38256     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
38257   }
38258 }
38259 #endif
38260
38261 /*
38262 ** The following global variable is incremented whenever the library
38263 ** attempts to open a temporary file.  This information is used for
38264 ** testing and analysis only.  
38265 */
38266 #ifdef SQLITE_TEST
38267 SQLITE_API int sqlite3_opentemp_count = 0;
38268 #endif
38269
38270 /*
38271 ** Open a temporary file.
38272 **
38273 ** Write the file descriptor into *pFile. Return SQLITE_OK on success 
38274 ** or some other error code if we fail. The OS will automatically 
38275 ** delete the temporary file when it is closed.
38276 **
38277 ** The flags passed to the VFS layer xOpen() call are those specified
38278 ** by parameter vfsFlags ORed with the following:
38279 **
38280 **     SQLITE_OPEN_READWRITE
38281 **     SQLITE_OPEN_CREATE
38282 **     SQLITE_OPEN_EXCLUSIVE
38283 **     SQLITE_OPEN_DELETEONCLOSE
38284 */
38285 static int pagerOpentemp(
38286   Pager *pPager,        /* The pager object */
38287   sqlite3_file *pFile,  /* Write the file descriptor here */
38288   int vfsFlags          /* Flags passed through to the VFS */
38289 ){
38290   int rc;               /* Return code */
38291
38292 #ifdef SQLITE_TEST
38293   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
38294 #endif
38295
38296   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
38297             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
38298   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
38299   assert( rc!=SQLITE_OK || isOpen(pFile) );
38300   return rc;
38301 }
38302
38303 /*
38304 ** Set the busy handler function.
38305 **
38306 ** The pager invokes the busy-handler if sqlite3OsLock() returns 
38307 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
38308 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE 
38309 ** lock. It does *not* invoke the busy handler when upgrading from
38310 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
38311 ** (which occurs during hot-journal rollback). Summary:
38312 **
38313 **   Transition                        | Invokes xBusyHandler
38314 **   --------------------------------------------------------
38315 **   NO_LOCK       -> SHARED_LOCK      | Yes
38316 **   SHARED_LOCK   -> RESERVED_LOCK    | No
38317 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
38318 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
38319 **
38320 ** If the busy-handler callback returns non-zero, the lock is 
38321 ** retried. If it returns zero, then the SQLITE_BUSY error is
38322 ** returned to the caller of the pager API function.
38323 */
38324 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
38325   Pager *pPager,                       /* Pager object */
38326   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
38327   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
38328 ){  
38329   pPager->xBusyHandler = xBusyHandler;
38330   pPager->pBusyHandlerArg = pBusyHandlerArg;
38331 }
38332
38333 /*
38334 ** Change the page size used by the Pager object. The new page size 
38335 ** is passed in *pPageSize.
38336 **
38337 ** If the pager is in the error state when this function is called, it
38338 ** is a no-op. The value returned is the error state error code (i.e. 
38339 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
38340 **
38341 ** Otherwise, if all of the following are true:
38342 **
38343 **   * the new page size (value of *pPageSize) is valid (a power 
38344 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
38345 **
38346 **   * there are no outstanding page references, and
38347 **
38348 **   * the database is either not an in-memory database or it is
38349 **     an in-memory database that currently consists of zero pages.
38350 **
38351 ** then the pager object page size is set to *pPageSize.
38352 **
38353 ** If the page size is changed, then this function uses sqlite3PagerMalloc() 
38354 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt 
38355 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged. 
38356 ** In all other cases, SQLITE_OK is returned.
38357 **
38358 ** If the page size is not changed, either because one of the enumerated
38359 ** conditions above is not true, the pager was in error state when this
38360 ** function was called, or because the memory allocation attempt failed, 
38361 ** then *pPageSize is set to the old, retained page size before returning.
38362 */
38363 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
38364   int rc = SQLITE_OK;
38365
38366   /* It is not possible to do a full assert_pager_state() here, as this
38367   ** function may be called from within PagerOpen(), before the state
38368   ** of the Pager object is internally consistent.
38369   **
38370   ** At one point this function returned an error if the pager was in 
38371   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
38372   ** there is at least one outstanding page reference, this function
38373   ** is a no-op for that case anyhow.
38374   */
38375
38376   u32 pageSize = *pPageSize;
38377   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
38378   if( (pPager->memDb==0 || pPager->dbSize==0)
38379    && sqlite3PcacheRefCount(pPager->pPCache)==0 
38380    && pageSize && pageSize!=(u32)pPager->pageSize 
38381   ){
38382     char *pNew = NULL;             /* New temp space */
38383     i64 nByte = 0;
38384
38385     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
38386       rc = sqlite3OsFileSize(pPager->fd, &nByte);
38387     }
38388     if( rc==SQLITE_OK ){
38389       pNew = (char *)sqlite3PageMalloc(pageSize);
38390       if( !pNew ) rc = SQLITE_NOMEM;
38391     }
38392
38393     if( rc==SQLITE_OK ){
38394       pager_reset(pPager);
38395       pPager->dbSize = (Pgno)(nByte/pageSize);
38396       pPager->pageSize = pageSize;
38397       sqlite3PageFree(pPager->pTmpSpace);
38398       pPager->pTmpSpace = pNew;
38399       sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
38400     }
38401   }
38402
38403   *pPageSize = pPager->pageSize;
38404   if( rc==SQLITE_OK ){
38405     if( nReserve<0 ) nReserve = pPager->nReserve;
38406     assert( nReserve>=0 && nReserve<1000 );
38407     pPager->nReserve = (i16)nReserve;
38408     pagerReportSize(pPager);
38409   }
38410   return rc;
38411 }
38412
38413 /*
38414 ** Return a pointer to the "temporary page" buffer held internally
38415 ** by the pager.  This is a buffer that is big enough to hold the
38416 ** entire content of a database page.  This buffer is used internally
38417 ** during rollback and will be overwritten whenever a rollback
38418 ** occurs.  But other modules are free to use it too, as long as
38419 ** no rollbacks are happening.
38420 */
38421 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
38422   return pPager->pTmpSpace;
38423 }
38424
38425 /*
38426 ** Attempt to set the maximum database page count if mxPage is positive. 
38427 ** Make no changes if mxPage is zero or negative.  And never reduce the
38428 ** maximum page count below the current size of the database.
38429 **
38430 ** Regardless of mxPage, return the current maximum page count.
38431 */
38432 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
38433   if( mxPage>0 ){
38434     pPager->mxPgno = mxPage;
38435   }
38436   assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
38437   assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
38438   return pPager->mxPgno;
38439 }
38440
38441 /*
38442 ** The following set of routines are used to disable the simulated
38443 ** I/O error mechanism.  These routines are used to avoid simulated
38444 ** errors in places where we do not care about errors.
38445 **
38446 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
38447 ** and generate no code.
38448 */
38449 #ifdef SQLITE_TEST
38450 SQLITE_API extern int sqlite3_io_error_pending;
38451 SQLITE_API extern int sqlite3_io_error_hit;
38452 static int saved_cnt;
38453 void disable_simulated_io_errors(void){
38454   saved_cnt = sqlite3_io_error_pending;
38455   sqlite3_io_error_pending = -1;
38456 }
38457 void enable_simulated_io_errors(void){
38458   sqlite3_io_error_pending = saved_cnt;
38459 }
38460 #else
38461 # define disable_simulated_io_errors()
38462 # define enable_simulated_io_errors()
38463 #endif
38464
38465 /*
38466 ** Read the first N bytes from the beginning of the file into memory
38467 ** that pDest points to. 
38468 **
38469 ** If the pager was opened on a transient file (zFilename==""), or
38470 ** opened on a file less than N bytes in size, the output buffer is
38471 ** zeroed and SQLITE_OK returned. The rationale for this is that this 
38472 ** function is used to read database headers, and a new transient or
38473 ** zero sized database has a header than consists entirely of zeroes.
38474 **
38475 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
38476 ** the error code is returned to the caller and the contents of the
38477 ** output buffer undefined.
38478 */
38479 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
38480   int rc = SQLITE_OK;
38481   memset(pDest, 0, N);
38482   assert( isOpen(pPager->fd) || pPager->tempFile );
38483
38484   /* This routine is only called by btree immediately after creating
38485   ** the Pager object.  There has not been an opportunity to transition
38486   ** to WAL mode yet.
38487   */
38488   assert( !pagerUseWal(pPager) );
38489
38490   if( isOpen(pPager->fd) ){
38491     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
38492     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
38493     if( rc==SQLITE_IOERR_SHORT_READ ){
38494       rc = SQLITE_OK;
38495     }
38496   }
38497   return rc;
38498 }
38499
38500 /*
38501 ** This function may only be called when a read-transaction is open on
38502 ** the pager. It returns the total number of pages in the database.
38503 **
38504 ** However, if the file is between 1 and <page-size> bytes in size, then 
38505 ** this is considered a 1 page file.
38506 */
38507 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
38508   assert( pPager->eState>=PAGER_READER );
38509   assert( pPager->eState!=PAGER_WRITER_FINISHED );
38510   *pnPage = (int)pPager->dbSize;
38511 }
38512
38513
38514 /*
38515 ** Try to obtain a lock of type locktype on the database file. If
38516 ** a similar or greater lock is already held, this function is a no-op
38517 ** (returning SQLITE_OK immediately).
38518 **
38519 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke 
38520 ** the busy callback if the lock is currently not available. Repeat 
38521 ** until the busy callback returns false or until the attempt to 
38522 ** obtain the lock succeeds.
38523 **
38524 ** Return SQLITE_OK on success and an error code if we cannot obtain
38525 ** the lock. If the lock is obtained successfully, set the Pager.state 
38526 ** variable to locktype before returning.
38527 */
38528 static int pager_wait_on_lock(Pager *pPager, int locktype){
38529   int rc;                              /* Return code */
38530
38531   /* Check that this is either a no-op (because the requested lock is 
38532   ** already held, or one of the transistions that the busy-handler
38533   ** may be invoked during, according to the comment above
38534   ** sqlite3PagerSetBusyhandler().
38535   */
38536   assert( (pPager->eLock>=locktype)
38537        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
38538        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
38539   );
38540
38541   do {
38542     rc = pagerLockDb(pPager, locktype);
38543   }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
38544   return rc;
38545 }
38546
38547 /*
38548 ** Function assertTruncateConstraint(pPager) checks that one of the 
38549 ** following is true for all dirty pages currently in the page-cache:
38550 **
38551 **   a) The page number is less than or equal to the size of the 
38552 **      current database image, in pages, OR
38553 **
38554 **   b) if the page content were written at this time, it would not
38555 **      be necessary to write the current content out to the sub-journal
38556 **      (as determined by function subjRequiresPage()).
38557 **
38558 ** If the condition asserted by this function were not true, and the
38559 ** dirty page were to be discarded from the cache via the pagerStress()
38560 ** routine, pagerStress() would not write the current page content to
38561 ** the database file. If a savepoint transaction were rolled back after
38562 ** this happened, the correct behaviour would be to restore the current
38563 ** content of the page. However, since this content is not present in either
38564 ** the database file or the portion of the rollback journal and 
38565 ** sub-journal rolled back the content could not be restored and the
38566 ** database image would become corrupt. It is therefore fortunate that 
38567 ** this circumstance cannot arise.
38568 */
38569 #if defined(SQLITE_DEBUG)
38570 static void assertTruncateConstraintCb(PgHdr *pPg){
38571   assert( pPg->flags&PGHDR_DIRTY );
38572   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
38573 }
38574 static void assertTruncateConstraint(Pager *pPager){
38575   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
38576 }
38577 #else
38578 # define assertTruncateConstraint(pPager)
38579 #endif
38580
38581 /*
38582 ** Truncate the in-memory database file image to nPage pages. This 
38583 ** function does not actually modify the database file on disk. It 
38584 ** just sets the internal state of the pager object so that the 
38585 ** truncation will be done when the current transaction is committed.
38586 */
38587 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
38588   assert( pPager->dbSize>=nPage );
38589   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
38590   pPager->dbSize = nPage;
38591   assertTruncateConstraint(pPager);
38592 }
38593
38594
38595 /*
38596 ** This function is called before attempting a hot-journal rollback. It
38597 ** syncs the journal file to disk, then sets pPager->journalHdr to the
38598 ** size of the journal file so that the pager_playback() routine knows
38599 ** that the entire journal file has been synced.
38600 **
38601 ** Syncing a hot-journal to disk before attempting to roll it back ensures 
38602 ** that if a power-failure occurs during the rollback, the process that
38603 ** attempts rollback following system recovery sees the same journal
38604 ** content as this process.
38605 **
38606 ** If everything goes as planned, SQLITE_OK is returned. Otherwise, 
38607 ** an SQLite error code.
38608 */
38609 static int pagerSyncHotJournal(Pager *pPager){
38610   int rc = SQLITE_OK;
38611   if( !pPager->noSync ){
38612     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
38613   }
38614   if( rc==SQLITE_OK ){
38615     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
38616   }
38617   return rc;
38618 }
38619
38620 /*
38621 ** Shutdown the page cache.  Free all memory and close all files.
38622 **
38623 ** If a transaction was in progress when this routine is called, that
38624 ** transaction is rolled back.  All outstanding pages are invalidated
38625 ** and their memory is freed.  Any attempt to use a page associated
38626 ** with this page cache after this function returns will likely
38627 ** result in a coredump.
38628 **
38629 ** This function always succeeds. If a transaction is active an attempt
38630 ** is made to roll it back. If an error occurs during the rollback 
38631 ** a hot journal may be left in the filesystem but no error is returned
38632 ** to the caller.
38633 */
38634 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
38635   u8 *pTmp = (u8 *)pPager->pTmpSpace;
38636
38637   disable_simulated_io_errors();
38638   sqlite3BeginBenignMalloc();
38639   /* pPager->errCode = 0; */
38640   pPager->exclusiveMode = 0;
38641 #ifndef SQLITE_OMIT_WAL
38642   sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
38643   pPager->pWal = 0;
38644 #endif
38645   pager_reset(pPager);
38646   if( MEMDB ){
38647     pager_unlock(pPager);
38648   }else{
38649     /* If it is open, sync the journal file before calling UnlockAndRollback.
38650     ** If this is not done, then an unsynced portion of the open journal 
38651     ** file may be played back into the database. If a power failure occurs 
38652     ** while this is happening, the database could become corrupt.
38653     **
38654     ** If an error occurs while trying to sync the journal, shift the pager
38655     ** into the ERROR state. This causes UnlockAndRollback to unlock the
38656     ** database and close the journal file without attempting to roll it
38657     ** back or finalize it. The next database user will have to do hot-journal
38658     ** rollback before accessing the database file.
38659     */
38660     if( isOpen(pPager->jfd) ){
38661       pager_error(pPager, pagerSyncHotJournal(pPager));
38662     }
38663     pagerUnlockAndRollback(pPager);
38664   }
38665   sqlite3EndBenignMalloc();
38666   enable_simulated_io_errors();
38667   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
38668   IOTRACE(("CLOSE %p\n", pPager))
38669   sqlite3OsClose(pPager->jfd);
38670   sqlite3OsClose(pPager->fd);
38671   sqlite3PageFree(pTmp);
38672   sqlite3PcacheClose(pPager->pPCache);
38673
38674 #ifdef SQLITE_HAS_CODEC
38675   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
38676 #endif
38677
38678   assert( !pPager->aSavepoint && !pPager->pInJournal );
38679   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
38680
38681   sqlite3_free(pPager);
38682   return SQLITE_OK;
38683 }
38684
38685 #if !defined(NDEBUG) || defined(SQLITE_TEST)
38686 /*
38687 ** Return the page number for page pPg.
38688 */
38689 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
38690   return pPg->pgno;
38691 }
38692 #endif
38693
38694 /*
38695 ** Increment the reference count for page pPg.
38696 */
38697 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
38698   sqlite3PcacheRef(pPg);
38699 }
38700
38701 /*
38702 ** Sync the journal. In other words, make sure all the pages that have
38703 ** been written to the journal have actually reached the surface of the
38704 ** disk and can be restored in the event of a hot-journal rollback.
38705 **
38706 ** If the Pager.noSync flag is set, then this function is a no-op.
38707 ** Otherwise, the actions required depend on the journal-mode and the 
38708 ** device characteristics of the the file-system, as follows:
38709 **
38710 **   * If the journal file is an in-memory journal file, no action need
38711 **     be taken.
38712 **
38713 **   * Otherwise, if the device does not support the SAFE_APPEND property,
38714 **     then the nRec field of the most recently written journal header
38715 **     is updated to contain the number of journal records that have
38716 **     been written following it. If the pager is operating in full-sync
38717 **     mode, then the journal file is synced before this field is updated.
38718 **
38719 **   * If the device does not support the SEQUENTIAL property, then 
38720 **     journal file is synced.
38721 **
38722 ** Or, in pseudo-code:
38723 **
38724 **   if( NOT <in-memory journal> ){
38725 **     if( NOT SAFE_APPEND ){
38726 **       if( <full-sync mode> ) xSync(<journal file>);
38727 **       <update nRec field>
38728 **     } 
38729 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
38730 **   }
38731 **
38732 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
38733 ** page currently held in memory before returning SQLITE_OK. If an IO
38734 ** error is encountered, then the IO error code is returned to the caller.
38735 */
38736 static int syncJournal(Pager *pPager, int newHdr){
38737   int rc;                         /* Return code */
38738
38739   assert( pPager->eState==PAGER_WRITER_CACHEMOD
38740        || pPager->eState==PAGER_WRITER_DBMOD
38741   );
38742   assert( assert_pager_state(pPager) );
38743   assert( !pagerUseWal(pPager) );
38744
38745   rc = sqlite3PagerExclusiveLock(pPager);
38746   if( rc!=SQLITE_OK ) return rc;
38747
38748   if( !pPager->noSync ){
38749     assert( !pPager->tempFile );
38750     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
38751       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
38752       assert( isOpen(pPager->jfd) );
38753
38754       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
38755         /* This block deals with an obscure problem. If the last connection
38756         ** that wrote to this database was operating in persistent-journal
38757         ** mode, then the journal file may at this point actually be larger
38758         ** than Pager.journalOff bytes. If the next thing in the journal
38759         ** file happens to be a journal-header (written as part of the
38760         ** previous connection's transaction), and a crash or power-failure 
38761         ** occurs after nRec is updated but before this connection writes 
38762         ** anything else to the journal file (or commits/rolls back its 
38763         ** transaction), then SQLite may become confused when doing the 
38764         ** hot-journal rollback following recovery. It may roll back all
38765         ** of this connections data, then proceed to rolling back the old,
38766         ** out-of-date data that follows it. Database corruption.
38767         **
38768         ** To work around this, if the journal file does appear to contain
38769         ** a valid header following Pager.journalOff, then write a 0x00
38770         ** byte to the start of it to prevent it from being recognized.
38771         **
38772         ** Variable iNextHdrOffset is set to the offset at which this
38773         ** problematic header will occur, if it exists. aMagic is used 
38774         ** as a temporary buffer to inspect the first couple of bytes of
38775         ** the potential journal header.
38776         */
38777         i64 iNextHdrOffset;
38778         u8 aMagic[8];
38779         u8 zHeader[sizeof(aJournalMagic)+4];
38780
38781         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
38782         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
38783
38784         iNextHdrOffset = journalHdrOffset(pPager);
38785         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
38786         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
38787           static const u8 zerobyte = 0;
38788           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
38789         }
38790         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
38791           return rc;
38792         }
38793
38794         /* Write the nRec value into the journal file header. If in
38795         ** full-synchronous mode, sync the journal first. This ensures that
38796         ** all data has really hit the disk before nRec is updated to mark
38797         ** it as a candidate for rollback.
38798         **
38799         ** This is not required if the persistent media supports the
38800         ** SAFE_APPEND property. Because in this case it is not possible 
38801         ** for garbage data to be appended to the file, the nRec field
38802         ** is populated with 0xFFFFFFFF when the journal header is written
38803         ** and never needs to be updated.
38804         */
38805         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
38806           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
38807           IOTRACE(("JSYNC %p\n", pPager))
38808           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
38809           if( rc!=SQLITE_OK ) return rc;
38810         }
38811         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
38812         rc = sqlite3OsWrite(
38813             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
38814         );
38815         if( rc!=SQLITE_OK ) return rc;
38816       }
38817       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
38818         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
38819         IOTRACE(("JSYNC %p\n", pPager))
38820         rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags| 
38821           (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
38822         );
38823         if( rc!=SQLITE_OK ) return rc;
38824       }
38825
38826       pPager->journalHdr = pPager->journalOff;
38827       if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
38828         pPager->nRec = 0;
38829         rc = writeJournalHdr(pPager);
38830         if( rc!=SQLITE_OK ) return rc;
38831       }
38832     }else{
38833       pPager->journalHdr = pPager->journalOff;
38834     }
38835   }
38836
38837   /* Unless the pager is in noSync mode, the journal file was just 
38838   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on 
38839   ** all pages.
38840   */
38841   sqlite3PcacheClearSyncFlags(pPager->pPCache);
38842   pPager->eState = PAGER_WRITER_DBMOD;
38843   assert( assert_pager_state(pPager) );
38844   return SQLITE_OK;
38845 }
38846
38847 /*
38848 ** The argument is the first in a linked list of dirty pages connected
38849 ** by the PgHdr.pDirty pointer. This function writes each one of the
38850 ** in-memory pages in the list to the database file. The argument may
38851 ** be NULL, representing an empty list. In this case this function is
38852 ** a no-op.
38853 **
38854 ** The pager must hold at least a RESERVED lock when this function
38855 ** is called. Before writing anything to the database file, this lock
38856 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
38857 ** SQLITE_BUSY is returned and no data is written to the database file.
38858 ** 
38859 ** If the pager is a temp-file pager and the actual file-system file
38860 ** is not yet open, it is created and opened before any data is 
38861 ** written out.
38862 **
38863 ** Once the lock has been upgraded and, if necessary, the file opened,
38864 ** the pages are written out to the database file in list order. Writing
38865 ** a page is skipped if it meets either of the following criteria:
38866 **
38867 **   * The page number is greater than Pager.dbSize, or
38868 **   * The PGHDR_DONT_WRITE flag is set on the page.
38869 **
38870 ** If writing out a page causes the database file to grow, Pager.dbFileSize
38871 ** is updated accordingly. If page 1 is written out, then the value cached
38872 ** in Pager.dbFileVers[] is updated to match the new value stored in
38873 ** the database file.
38874 **
38875 ** If everything is successful, SQLITE_OK is returned. If an IO error 
38876 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
38877 ** be obtained, SQLITE_BUSY is returned.
38878 */
38879 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
38880   int rc = SQLITE_OK;                  /* Return code */
38881
38882   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
38883   assert( !pagerUseWal(pPager) );
38884   assert( pPager->eState==PAGER_WRITER_DBMOD );
38885   assert( pPager->eLock==EXCLUSIVE_LOCK );
38886
38887   /* If the file is a temp-file has not yet been opened, open it now. It
38888   ** is not possible for rc to be other than SQLITE_OK if this branch
38889   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
38890   */
38891   if( !isOpen(pPager->fd) ){
38892     assert( pPager->tempFile && rc==SQLITE_OK );
38893     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
38894   }
38895
38896   /* Before the first write, give the VFS a hint of what the final
38897   ** file size will be.
38898   */
38899   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
38900   if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
38901     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
38902     sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
38903     pPager->dbHintSize = pPager->dbSize;
38904   }
38905
38906   while( rc==SQLITE_OK && pList ){
38907     Pgno pgno = pList->pgno;
38908
38909     /* If there are dirty pages in the page cache with page numbers greater
38910     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
38911     ** make the file smaller (presumably by auto-vacuum code). Do not write
38912     ** any such pages to the file.
38913     **
38914     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
38915     ** set (set by sqlite3PagerDontWrite()).
38916     */
38917     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
38918       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
38919       char *pData;                                   /* Data to write */    
38920
38921       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
38922       if( pList->pgno==1 ) pager_write_changecounter(pList);
38923
38924       /* Encode the database */
38925       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
38926
38927       /* Write out the page data. */
38928       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
38929
38930       /* If page 1 was just written, update Pager.dbFileVers to match
38931       ** the value now stored in the database file. If writing this 
38932       ** page caused the database file to grow, update dbFileSize. 
38933       */
38934       if( pgno==1 ){
38935         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
38936       }
38937       if( pgno>pPager->dbFileSize ){
38938         pPager->dbFileSize = pgno;
38939       }
38940
38941       /* Update any backup objects copying the contents of this pager. */
38942       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
38943
38944       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
38945                    PAGERID(pPager), pgno, pager_pagehash(pList)));
38946       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
38947       PAGER_INCR(sqlite3_pager_writedb_count);
38948       PAGER_INCR(pPager->nWrite);
38949     }else{
38950       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
38951     }
38952     pager_set_pagehash(pList);
38953     pList = pList->pDirty;
38954   }
38955
38956   return rc;
38957 }
38958
38959 /*
38960 ** Ensure that the sub-journal file is open. If it is already open, this 
38961 ** function is a no-op.
38962 **
38963 ** SQLITE_OK is returned if everything goes according to plan. An 
38964 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() 
38965 ** fails.
38966 */
38967 static int openSubJournal(Pager *pPager){
38968   int rc = SQLITE_OK;
38969   if( !isOpen(pPager->sjfd) ){
38970     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
38971       sqlite3MemJournalOpen(pPager->sjfd);
38972     }else{
38973       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
38974     }
38975   }
38976   return rc;
38977 }
38978
38979 /*
38980 ** Append a record of the current state of page pPg to the sub-journal. 
38981 ** It is the callers responsibility to use subjRequiresPage() to check 
38982 ** that it is really required before calling this function.
38983 **
38984 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
38985 ** for all open savepoints before returning.
38986 **
38987 ** This function returns SQLITE_OK if everything is successful, an IO
38988 ** error code if the attempt to write to the sub-journal fails, or 
38989 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
38990 ** bitvec.
38991 */
38992 static int subjournalPage(PgHdr *pPg){
38993   int rc = SQLITE_OK;
38994   Pager *pPager = pPg->pPager;
38995   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
38996
38997     /* Open the sub-journal, if it has not already been opened */
38998     assert( pPager->useJournal );
38999     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
39000     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
39001     assert( pagerUseWal(pPager) 
39002          || pageInJournal(pPg) 
39003          || pPg->pgno>pPager->dbOrigSize 
39004     );
39005     rc = openSubJournal(pPager);
39006
39007     /* If the sub-journal was opened successfully (or was already open),
39008     ** write the journal record into the file.  */
39009     if( rc==SQLITE_OK ){
39010       void *pData = pPg->pData;
39011       i64 offset = pPager->nSubRec*(4+pPager->pageSize);
39012       char *pData2;
39013   
39014       CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
39015       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
39016       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
39017       if( rc==SQLITE_OK ){
39018         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
39019       }
39020     }
39021   }
39022   if( rc==SQLITE_OK ){
39023     pPager->nSubRec++;
39024     assert( pPager->nSavepoint>0 );
39025     rc = addToSavepointBitvecs(pPager, pPg->pgno);
39026   }
39027   return rc;
39028 }
39029
39030 /*
39031 ** This function is called by the pcache layer when it has reached some
39032 ** soft memory limit. The first argument is a pointer to a Pager object
39033 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
39034 ** database). The second argument is a reference to a page that is 
39035 ** currently dirty but has no outstanding references. The page
39036 ** is always associated with the Pager object passed as the first 
39037 ** argument.
39038 **
39039 ** The job of this function is to make pPg clean by writing its contents
39040 ** out to the database file, if possible. This may involve syncing the
39041 ** journal file. 
39042 **
39043 ** If successful, sqlite3PcacheMakeClean() is called on the page and
39044 ** SQLITE_OK returned. If an IO error occurs while trying to make the
39045 ** page clean, the IO error code is returned. If the page cannot be
39046 ** made clean for some other reason, but no error occurs, then SQLITE_OK
39047 ** is returned by sqlite3PcacheMakeClean() is not called.
39048 */
39049 static int pagerStress(void *p, PgHdr *pPg){
39050   Pager *pPager = (Pager *)p;
39051   int rc = SQLITE_OK;
39052
39053   assert( pPg->pPager==pPager );
39054   assert( pPg->flags&PGHDR_DIRTY );
39055
39056   /* The doNotSyncSpill flag is set during times when doing a sync of
39057   ** journal (and adding a new header) is not allowed.  This occurs
39058   ** during calls to sqlite3PagerWrite() while trying to journal multiple
39059   ** pages belonging to the same sector.
39060   **
39061   ** The doNotSpill flag inhibits all cache spilling regardless of whether
39062   ** or not a sync is required.  This is set during a rollback.
39063   **
39064   ** Spilling is also prohibited when in an error state since that could
39065   ** lead to database corruption.   In the current implementaton it 
39066   ** is impossible for sqlite3PCacheFetch() to be called with createFlag==1
39067   ** while in the error state, hence it is impossible for this routine to
39068   ** be called in the error state.  Nevertheless, we include a NEVER()
39069   ** test for the error state as a safeguard against future changes.
39070   */
39071   if( NEVER(pPager->errCode) ) return SQLITE_OK;
39072   if( pPager->doNotSpill ) return SQLITE_OK;
39073   if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
39074     return SQLITE_OK;
39075   }
39076
39077   pPg->pDirty = 0;
39078   if( pagerUseWal(pPager) ){
39079     /* Write a single frame for this page to the log. */
39080     if( subjRequiresPage(pPg) ){ 
39081       rc = subjournalPage(pPg); 
39082     }
39083     if( rc==SQLITE_OK ){
39084       rc = pagerWalFrames(pPager, pPg, 0, 0, 0);
39085     }
39086   }else{
39087   
39088     /* Sync the journal file if required. */
39089     if( pPg->flags&PGHDR_NEED_SYNC 
39090      || pPager->eState==PAGER_WRITER_CACHEMOD
39091     ){
39092       rc = syncJournal(pPager, 1);
39093     }
39094   
39095     /* If the page number of this page is larger than the current size of
39096     ** the database image, it may need to be written to the sub-journal.
39097     ** This is because the call to pager_write_pagelist() below will not
39098     ** actually write data to the file in this case.
39099     **
39100     ** Consider the following sequence of events:
39101     **
39102     **   BEGIN;
39103     **     <journal page X>
39104     **     <modify page X>
39105     **     SAVEPOINT sp;
39106     **       <shrink database file to Y pages>
39107     **       pagerStress(page X)
39108     **     ROLLBACK TO sp;
39109     **
39110     ** If (X>Y), then when pagerStress is called page X will not be written
39111     ** out to the database file, but will be dropped from the cache. Then,
39112     ** following the "ROLLBACK TO sp" statement, reading page X will read
39113     ** data from the database file. This will be the copy of page X as it
39114     ** was when the transaction started, not as it was when "SAVEPOINT sp"
39115     ** was executed.
39116     **
39117     ** The solution is to write the current data for page X into the 
39118     ** sub-journal file now (if it is not already there), so that it will
39119     ** be restored to its current value when the "ROLLBACK TO sp" is 
39120     ** executed.
39121     */
39122     if( NEVER(
39123         rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
39124     ) ){
39125       rc = subjournalPage(pPg);
39126     }
39127   
39128     /* Write the contents of the page out to the database file. */
39129     if( rc==SQLITE_OK ){
39130       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
39131       rc = pager_write_pagelist(pPager, pPg);
39132     }
39133   }
39134
39135   /* Mark the page as clean. */
39136   if( rc==SQLITE_OK ){
39137     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
39138     sqlite3PcacheMakeClean(pPg);
39139   }
39140
39141   return pager_error(pPager, rc); 
39142 }
39143
39144
39145 /*
39146 ** Allocate and initialize a new Pager object and put a pointer to it
39147 ** in *ppPager. The pager should eventually be freed by passing it
39148 ** to sqlite3PagerClose().
39149 **
39150 ** The zFilename argument is the path to the database file to open.
39151 ** If zFilename is NULL then a randomly-named temporary file is created
39152 ** and used as the file to be cached. Temporary files are be deleted
39153 ** automatically when they are closed. If zFilename is ":memory:" then 
39154 ** all information is held in cache. It is never written to disk. 
39155 ** This can be used to implement an in-memory database.
39156 **
39157 ** The nExtra parameter specifies the number of bytes of space allocated
39158 ** along with each page reference. This space is available to the user
39159 ** via the sqlite3PagerGetExtra() API.
39160 **
39161 ** The flags argument is used to specify properties that affect the
39162 ** operation of the pager. It should be passed some bitwise combination
39163 ** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
39164 **
39165 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
39166 ** of the xOpen() method of the supplied VFS when opening files. 
39167 **
39168 ** If the pager object is allocated and the specified file opened 
39169 ** successfully, SQLITE_OK is returned and *ppPager set to point to
39170 ** the new pager object. If an error occurs, *ppPager is set to NULL
39171 ** and error code returned. This function may return SQLITE_NOMEM
39172 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or 
39173 ** various SQLITE_IO_XXX errors.
39174 */
39175 SQLITE_PRIVATE int sqlite3PagerOpen(
39176   sqlite3_vfs *pVfs,       /* The virtual file system to use */
39177   Pager **ppPager,         /* OUT: Return the Pager structure here */
39178   const char *zFilename,   /* Name of the database file to open */
39179   int nExtra,              /* Extra bytes append to each in-memory page */
39180   int flags,               /* flags controlling this file */
39181   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
39182   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
39183 ){
39184   u8 *pPtr;
39185   Pager *pPager = 0;       /* Pager object to allocate and return */
39186   int rc = SQLITE_OK;      /* Return code */
39187   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
39188   int memDb = 0;           /* True if this is an in-memory file */
39189   int readOnly = 0;        /* True if this is a read-only file */
39190   int journalFileSize;     /* Bytes to allocate for each journal fd */
39191   char *zPathname = 0;     /* Full path to database file */
39192   int nPathname = 0;       /* Number of bytes in zPathname */
39193   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
39194   int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
39195   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
39196   u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
39197
39198   /* Figure out how much space is required for each journal file-handle
39199   ** (there are two of them, the main journal and the sub-journal). This
39200   ** is the maximum space required for an in-memory journal file handle 
39201   ** and a regular journal file-handle. Note that a "regular journal-handle"
39202   ** may be a wrapper capable of caching the first portion of the journal
39203   ** file in memory to implement the atomic-write optimization (see 
39204   ** source file journal.c).
39205   */
39206   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
39207     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
39208   }else{
39209     journalFileSize = ROUND8(sqlite3MemJournalSize());
39210   }
39211
39212   /* Set the output variable to NULL in case an error occurs. */
39213   *ppPager = 0;
39214
39215 #ifndef SQLITE_OMIT_MEMORYDB
39216   if( flags & PAGER_MEMORY ){
39217     memDb = 1;
39218     zFilename = 0;
39219   }
39220 #endif
39221
39222   /* Compute and store the full pathname in an allocated buffer pointed
39223   ** to by zPathname, length nPathname. Or, if this is a temporary file,
39224   ** leave both nPathname and zPathname set to 0.
39225   */
39226   if( zFilename && zFilename[0] ){
39227     nPathname = pVfs->mxPathname+1;
39228     zPathname = sqlite3Malloc(nPathname*2);
39229     if( zPathname==0 ){
39230       return SQLITE_NOMEM;
39231     }
39232     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
39233     rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
39234     nPathname = sqlite3Strlen30(zPathname);
39235     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
39236       /* This branch is taken when the journal path required by
39237       ** the database being opened will be more than pVfs->mxPathname
39238       ** bytes in length. This means the database cannot be opened,
39239       ** as it will not be possible to open the journal file or even
39240       ** check for a hot-journal before reading.
39241       */
39242       rc = SQLITE_CANTOPEN_BKPT;
39243     }
39244     if( rc!=SQLITE_OK ){
39245       sqlite3_free(zPathname);
39246       return rc;
39247     }
39248   }
39249
39250   /* Allocate memory for the Pager structure, PCache object, the
39251   ** three file descriptors, the database file name and the journal 
39252   ** file name. The layout in memory is as follows:
39253   **
39254   **     Pager object                    (sizeof(Pager) bytes)
39255   **     PCache object                   (sqlite3PcacheSize() bytes)
39256   **     Database file handle            (pVfs->szOsFile bytes)
39257   **     Sub-journal file handle         (journalFileSize bytes)
39258   **     Main journal file handle        (journalFileSize bytes)
39259   **     Database file name              (nPathname+1 bytes)
39260   **     Journal file name               (nPathname+8+1 bytes)
39261   */
39262   pPtr = (u8 *)sqlite3MallocZero(
39263     ROUND8(sizeof(*pPager)) +      /* Pager structure */
39264     ROUND8(pcacheSize) +           /* PCache object */
39265     ROUND8(pVfs->szOsFile) +       /* The main db file */
39266     journalFileSize * 2 +          /* The two journal files */ 
39267     nPathname + 1 +                /* zFilename */
39268     nPathname + 8 + 1              /* zJournal */
39269 #ifndef SQLITE_OMIT_WAL
39270     + nPathname + 4 + 1              /* zWal */
39271 #endif
39272   );
39273   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
39274   if( !pPtr ){
39275     sqlite3_free(zPathname);
39276     return SQLITE_NOMEM;
39277   }
39278   pPager =              (Pager*)(pPtr);
39279   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
39280   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
39281   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
39282   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
39283   pPager->zFilename =    (char*)(pPtr += journalFileSize);
39284   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
39285
39286   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
39287   if( zPathname ){
39288     assert( nPathname>0 );
39289     pPager->zJournal =   (char*)(pPtr += nPathname + 1);
39290     memcpy(pPager->zFilename, zPathname, nPathname);
39291     memcpy(pPager->zJournal, zPathname, nPathname);
39292     memcpy(&pPager->zJournal[nPathname], "-journal", 8);
39293 #ifndef SQLITE_OMIT_WAL
39294     pPager->zWal = &pPager->zJournal[nPathname+8+1];
39295     memcpy(pPager->zWal, zPathname, nPathname);
39296     memcpy(&pPager->zWal[nPathname], "-wal", 4);
39297 #endif
39298     sqlite3_free(zPathname);
39299   }
39300   pPager->pVfs = pVfs;
39301   pPager->vfsFlags = vfsFlags;
39302
39303   /* Open the pager file.
39304   */
39305   if( zFilename && zFilename[0] ){
39306     int fout = 0;                    /* VFS flags returned by xOpen() */
39307     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
39308     assert( !memDb );
39309     readOnly = (fout&SQLITE_OPEN_READONLY);
39310
39311     /* If the file was successfully opened for read/write access,
39312     ** choose a default page size in case we have to create the
39313     ** database file. The default page size is the maximum of:
39314     **
39315     **    + SQLITE_DEFAULT_PAGE_SIZE,
39316     **    + The value returned by sqlite3OsSectorSize()
39317     **    + The largest page size that can be written atomically.
39318     */
39319     if( rc==SQLITE_OK && !readOnly ){
39320       setSectorSize(pPager);
39321       assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
39322       if( szPageDflt<pPager->sectorSize ){
39323         if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
39324           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
39325         }else{
39326           szPageDflt = (u32)pPager->sectorSize;
39327         }
39328       }
39329 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
39330       {
39331         int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
39332         int ii;
39333         assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
39334         assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
39335         assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
39336         for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
39337           if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
39338             szPageDflt = ii;
39339           }
39340         }
39341       }
39342 #endif
39343     }
39344   }else{
39345     /* If a temporary file is requested, it is not opened immediately.
39346     ** In this case we accept the default page size and delay actually
39347     ** opening the file until the first call to OsWrite().
39348     **
39349     ** This branch is also run for an in-memory database. An in-memory
39350     ** database is the same as a temp-file that is never written out to
39351     ** disk and uses an in-memory rollback journal.
39352     */ 
39353     tempFile = 1;
39354     pPager->eState = PAGER_READER;
39355     pPager->eLock = EXCLUSIVE_LOCK;
39356     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
39357   }
39358
39359   /* The following call to PagerSetPagesize() serves to set the value of 
39360   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
39361   */
39362   if( rc==SQLITE_OK ){
39363     assert( pPager->memDb==0 );
39364     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
39365     testcase( rc!=SQLITE_OK );
39366   }
39367
39368   /* If an error occurred in either of the blocks above, free the 
39369   ** Pager structure and close the file.
39370   */
39371   if( rc!=SQLITE_OK ){
39372     assert( !pPager->pTmpSpace );
39373     sqlite3OsClose(pPager->fd);
39374     sqlite3_free(pPager);
39375     return rc;
39376   }
39377
39378   /* Initialize the PCache object. */
39379   assert( nExtra<1000 );
39380   nExtra = ROUND8(nExtra);
39381   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
39382                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
39383
39384   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
39385   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
39386
39387   pPager->useJournal = (u8)useJournal;
39388   pPager->noReadlock = (noReadlock && readOnly) ?1:0;
39389   /* pPager->stmtOpen = 0; */
39390   /* pPager->stmtInUse = 0; */
39391   /* pPager->nRef = 0; */
39392   /* pPager->stmtSize = 0; */
39393   /* pPager->stmtJSize = 0; */
39394   /* pPager->nPage = 0; */
39395   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
39396   /* pPager->state = PAGER_UNLOCK; */
39397 #if 0
39398   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
39399 #endif
39400   /* pPager->errMask = 0; */
39401   pPager->tempFile = (u8)tempFile;
39402   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
39403           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
39404   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
39405   pPager->exclusiveMode = (u8)tempFile; 
39406   pPager->changeCountDone = pPager->tempFile;
39407   pPager->memDb = (u8)memDb;
39408   pPager->readOnly = (u8)readOnly;
39409   assert( useJournal || pPager->tempFile );
39410   pPager->noSync = pPager->tempFile;
39411   pPager->fullSync = pPager->noSync ?0:1;
39412   pPager->syncFlags = pPager->noSync ? 0 : SQLITE_SYNC_NORMAL;
39413   pPager->ckptSyncFlags = pPager->syncFlags;
39414   /* pPager->pFirst = 0; */
39415   /* pPager->pFirstSynced = 0; */
39416   /* pPager->pLast = 0; */
39417   pPager->nExtra = (u16)nExtra;
39418   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
39419   assert( isOpen(pPager->fd) || tempFile );
39420   setSectorSize(pPager);
39421   if( !useJournal ){
39422     pPager->journalMode = PAGER_JOURNALMODE_OFF;
39423   }else if( memDb ){
39424     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
39425   }
39426   /* pPager->xBusyHandler = 0; */
39427   /* pPager->pBusyHandlerArg = 0; */
39428   pPager->xReiniter = xReinit;
39429   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
39430
39431   *ppPager = pPager;
39432   return SQLITE_OK;
39433 }
39434
39435
39436
39437 /*
39438 ** This function is called after transitioning from PAGER_UNLOCK to
39439 ** PAGER_SHARED state. It tests if there is a hot journal present in
39440 ** the file-system for the given pager. A hot journal is one that 
39441 ** needs to be played back. According to this function, a hot-journal
39442 ** file exists if the following criteria are met:
39443 **
39444 **   * The journal file exists in the file system, and
39445 **   * No process holds a RESERVED or greater lock on the database file, and
39446 **   * The database file itself is greater than 0 bytes in size, and
39447 **   * The first byte of the journal file exists and is not 0x00.
39448 **
39449 ** If the current size of the database file is 0 but a journal file
39450 ** exists, that is probably an old journal left over from a prior
39451 ** database with the same name. In this case the journal file is
39452 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
39453 ** is returned.
39454 **
39455 ** This routine does not check if there is a master journal filename
39456 ** at the end of the file. If there is, and that master journal file
39457 ** does not exist, then the journal file is not really hot. In this
39458 ** case this routine will return a false-positive. The pager_playback()
39459 ** routine will discover that the journal file is not really hot and 
39460 ** will not roll it back. 
39461 **
39462 ** If a hot-journal file is found to exist, *pExists is set to 1 and 
39463 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
39464 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
39465 ** to determine whether or not a hot-journal file exists, the IO error
39466 ** code is returned and the value of *pExists is undefined.
39467 */
39468 static int hasHotJournal(Pager *pPager, int *pExists){
39469   sqlite3_vfs * const pVfs = pPager->pVfs;
39470   int rc = SQLITE_OK;           /* Return code */
39471   int exists = 1;               /* True if a journal file is present */
39472   int jrnlOpen = !!isOpen(pPager->jfd);
39473
39474   assert( pPager->useJournal );
39475   assert( isOpen(pPager->fd) );
39476   assert( pPager->eState==PAGER_OPEN );
39477
39478   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
39479     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
39480   ));
39481
39482   *pExists = 0;
39483   if( !jrnlOpen ){
39484     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
39485   }
39486   if( rc==SQLITE_OK && exists ){
39487     int locked = 0;             /* True if some process holds a RESERVED lock */
39488
39489     /* Race condition here:  Another process might have been holding the
39490     ** the RESERVED lock and have a journal open at the sqlite3OsAccess() 
39491     ** call above, but then delete the journal and drop the lock before
39492     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
39493     ** is the case, this routine might think there is a hot journal when
39494     ** in fact there is none.  This results in a false-positive which will
39495     ** be dealt with by the playback routine.  Ticket #3883.
39496     */
39497     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
39498     if( rc==SQLITE_OK && !locked ){
39499       Pgno nPage;                 /* Number of pages in database file */
39500
39501       /* Check the size of the database file. If it consists of 0 pages,
39502       ** then delete the journal file. See the header comment above for 
39503       ** the reasoning here.  Delete the obsolete journal file under
39504       ** a RESERVED lock to avoid race conditions and to avoid violating
39505       ** [H33020].
39506       */
39507       rc = pagerPagecount(pPager, &nPage);
39508       if( rc==SQLITE_OK ){
39509         if( nPage==0 ){
39510           sqlite3BeginBenignMalloc();
39511           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
39512             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
39513             if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
39514           }
39515           sqlite3EndBenignMalloc();
39516         }else{
39517           /* The journal file exists and no other connection has a reserved
39518           ** or greater lock on the database file. Now check that there is
39519           ** at least one non-zero bytes at the start of the journal file.
39520           ** If there is, then we consider this journal to be hot. If not, 
39521           ** it can be ignored.
39522           */
39523           if( !jrnlOpen ){
39524             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
39525             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
39526           }
39527           if( rc==SQLITE_OK ){
39528             u8 first = 0;
39529             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
39530             if( rc==SQLITE_IOERR_SHORT_READ ){
39531               rc = SQLITE_OK;
39532             }
39533             if( !jrnlOpen ){
39534               sqlite3OsClose(pPager->jfd);
39535             }
39536             *pExists = (first!=0);
39537           }else if( rc==SQLITE_CANTOPEN ){
39538             /* If we cannot open the rollback journal file in order to see if
39539             ** its has a zero header, that might be due to an I/O error, or
39540             ** it might be due to the race condition described above and in
39541             ** ticket #3883.  Either way, assume that the journal is hot.
39542             ** This might be a false positive.  But if it is, then the
39543             ** automatic journal playback and recovery mechanism will deal
39544             ** with it under an EXCLUSIVE lock where we do not need to
39545             ** worry so much with race conditions.
39546             */
39547             *pExists = 1;
39548             rc = SQLITE_OK;
39549           }
39550         }
39551       }
39552     }
39553   }
39554
39555   return rc;
39556 }
39557
39558 /*
39559 ** This function is called to obtain a shared lock on the database file.
39560 ** It is illegal to call sqlite3PagerAcquire() until after this function
39561 ** has been successfully called. If a shared-lock is already held when
39562 ** this function is called, it is a no-op.
39563 **
39564 ** The following operations are also performed by this function.
39565 **
39566 **   1) If the pager is currently in PAGER_OPEN state (no lock held
39567 **      on the database file), then an attempt is made to obtain a
39568 **      SHARED lock on the database file. Immediately after obtaining
39569 **      the SHARED lock, the file-system is checked for a hot-journal,
39570 **      which is played back if present. Following any hot-journal 
39571 **      rollback, the contents of the cache are validated by checking
39572 **      the 'change-counter' field of the database file header and
39573 **      discarded if they are found to be invalid.
39574 **
39575 **   2) If the pager is running in exclusive-mode, and there are currently
39576 **      no outstanding references to any pages, and is in the error state,
39577 **      then an attempt is made to clear the error state by discarding
39578 **      the contents of the page cache and rolling back any open journal
39579 **      file.
39580 **
39581 ** If everything is successful, SQLITE_OK is returned. If an IO error 
39582 ** occurs while locking the database, checking for a hot-journal file or 
39583 ** rolling back a journal file, the IO error code is returned.
39584 */
39585 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
39586   int rc = SQLITE_OK;                /* Return code */
39587
39588   /* This routine is only called from b-tree and only when there are no
39589   ** outstanding pages. This implies that the pager state should either
39590   ** be OPEN or READER. READER is only possible if the pager is or was in 
39591   ** exclusive access mode.
39592   */
39593   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
39594   assert( assert_pager_state(pPager) );
39595   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
39596   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
39597
39598   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
39599     int bHotJournal = 1;          /* True if there exists a hot journal-file */
39600
39601     assert( !MEMDB );
39602     assert( pPager->noReadlock==0 || pPager->readOnly );
39603
39604     if( pPager->noReadlock==0 ){
39605       rc = pager_wait_on_lock(pPager, SHARED_LOCK);
39606       if( rc!=SQLITE_OK ){
39607         assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
39608         goto failed;
39609       }
39610     }
39611
39612     /* If a journal file exists, and there is no RESERVED lock on the
39613     ** database file, then it either needs to be played back or deleted.
39614     */
39615     if( pPager->eLock<=SHARED_LOCK ){
39616       rc = hasHotJournal(pPager, &bHotJournal);
39617     }
39618     if( rc!=SQLITE_OK ){
39619       goto failed;
39620     }
39621     if( bHotJournal ){
39622       /* Get an EXCLUSIVE lock on the database file. At this point it is
39623       ** important that a RESERVED lock is not obtained on the way to the
39624       ** EXCLUSIVE lock. If it were, another process might open the
39625       ** database file, detect the RESERVED lock, and conclude that the
39626       ** database is safe to read while this process is still rolling the 
39627       ** hot-journal back.
39628       ** 
39629       ** Because the intermediate RESERVED lock is not requested, any
39630       ** other process attempting to access the database file will get to 
39631       ** this point in the code and fail to obtain its own EXCLUSIVE lock 
39632       ** on the database file.
39633       **
39634       ** Unless the pager is in locking_mode=exclusive mode, the lock is
39635       ** downgraded to SHARED_LOCK before this function returns.
39636       */
39637       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
39638       if( rc!=SQLITE_OK ){
39639         goto failed;
39640       }
39641  
39642       /* If it is not already open and the file exists on disk, open the 
39643       ** journal for read/write access. Write access is required because 
39644       ** in exclusive-access mode the file descriptor will be kept open 
39645       ** and possibly used for a transaction later on. Also, write-access 
39646       ** is usually required to finalize the journal in journal_mode=persist 
39647       ** mode (and also for journal_mode=truncate on some systems).
39648       **
39649       ** If the journal does not exist, it usually means that some 
39650       ** other connection managed to get in and roll it back before 
39651       ** this connection obtained the exclusive lock above. Or, it 
39652       ** may mean that the pager was in the error-state when this
39653       ** function was called and the journal file does not exist.
39654       */
39655       if( !isOpen(pPager->jfd) ){
39656         sqlite3_vfs * const pVfs = pPager->pVfs;
39657         int bExists;              /* True if journal file exists */
39658         rc = sqlite3OsAccess(
39659             pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
39660         if( rc==SQLITE_OK && bExists ){
39661           int fout = 0;
39662           int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
39663           assert( !pPager->tempFile );
39664           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
39665           assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
39666           if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
39667             rc = SQLITE_CANTOPEN_BKPT;
39668             sqlite3OsClose(pPager->jfd);
39669           }
39670         }
39671       }
39672  
39673       /* Playback and delete the journal.  Drop the database write
39674       ** lock and reacquire the read lock. Purge the cache before
39675       ** playing back the hot-journal so that we don't end up with
39676       ** an inconsistent cache.  Sync the hot journal before playing
39677       ** it back since the process that crashed and left the hot journal
39678       ** probably did not sync it and we are required to always sync
39679       ** the journal before playing it back.
39680       */
39681       if( isOpen(pPager->jfd) ){
39682         assert( rc==SQLITE_OK );
39683         rc = pagerSyncHotJournal(pPager);
39684         if( rc==SQLITE_OK ){
39685           rc = pager_playback(pPager, 1);
39686           pPager->eState = PAGER_OPEN;
39687         }
39688       }else if( !pPager->exclusiveMode ){
39689         pagerUnlockDb(pPager, SHARED_LOCK);
39690       }
39691
39692       if( rc!=SQLITE_OK ){
39693         /* This branch is taken if an error occurs while trying to open
39694         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
39695         ** pager_unlock() routine will be called before returning to unlock
39696         ** the file. If the unlock attempt fails, then Pager.eLock must be
39697         ** set to UNKNOWN_LOCK (see the comment above the #define for 
39698         ** UNKNOWN_LOCK above for an explanation). 
39699         **
39700         ** In order to get pager_unlock() to do this, set Pager.eState to
39701         ** PAGER_ERROR now. This is not actually counted as a transition
39702         ** to ERROR state in the state diagram at the top of this file,
39703         ** since we know that the same call to pager_unlock() will very
39704         ** shortly transition the pager object to the OPEN state. Calling
39705         ** assert_pager_state() would fail now, as it should not be possible
39706         ** to be in ERROR state when there are zero outstanding page 
39707         ** references.
39708         */
39709         pager_error(pPager, rc);
39710         goto failed;
39711       }
39712
39713       assert( pPager->eState==PAGER_OPEN );
39714       assert( (pPager->eLock==SHARED_LOCK)
39715            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
39716       );
39717     }
39718
39719     if( !pPager->tempFile 
39720      && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0) 
39721     ){
39722       /* The shared-lock has just been acquired on the database file
39723       ** and there are already pages in the cache (from a previous
39724       ** read or write transaction).  Check to see if the database
39725       ** has been modified.  If the database has changed, flush the
39726       ** cache.
39727       **
39728       ** Database changes is detected by looking at 15 bytes beginning
39729       ** at offset 24 into the file.  The first 4 of these 16 bytes are
39730       ** a 32-bit counter that is incremented with each change.  The
39731       ** other bytes change randomly with each file change when
39732       ** a codec is in use.
39733       ** 
39734       ** There is a vanishingly small chance that a change will not be 
39735       ** detected.  The chance of an undetected change is so small that
39736       ** it can be neglected.
39737       */
39738       Pgno nPage = 0;
39739       char dbFileVers[sizeof(pPager->dbFileVers)];
39740
39741       rc = pagerPagecount(pPager, &nPage);
39742       if( rc ) goto failed;
39743
39744       if( nPage>0 ){
39745         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
39746         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
39747         if( rc!=SQLITE_OK ){
39748           goto failed;
39749         }
39750       }else{
39751         memset(dbFileVers, 0, sizeof(dbFileVers));
39752       }
39753
39754       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
39755         pager_reset(pPager);
39756       }
39757     }
39758
39759     /* If there is a WAL file in the file-system, open this database in WAL
39760     ** mode. Otherwise, the following function call is a no-op.
39761     */
39762     rc = pagerOpenWalIfPresent(pPager);
39763 #ifndef SQLITE_OMIT_WAL
39764     assert( pPager->pWal==0 || rc==SQLITE_OK );
39765 #endif
39766   }
39767
39768   if( pagerUseWal(pPager) ){
39769     assert( rc==SQLITE_OK );
39770     rc = pagerBeginReadTransaction(pPager);
39771   }
39772
39773   if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
39774     rc = pagerPagecount(pPager, &pPager->dbSize);
39775   }
39776
39777  failed:
39778   if( rc!=SQLITE_OK ){
39779     assert( !MEMDB );
39780     pager_unlock(pPager);
39781     assert( pPager->eState==PAGER_OPEN );
39782   }else{
39783     pPager->eState = PAGER_READER;
39784   }
39785   return rc;
39786 }
39787
39788 /*
39789 ** If the reference count has reached zero, rollback any active
39790 ** transaction and unlock the pager.
39791 **
39792 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
39793 ** the rollback journal, the unlock is not performed and there is
39794 ** nothing to rollback, so this routine is a no-op.
39795 */ 
39796 static void pagerUnlockIfUnused(Pager *pPager){
39797   if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
39798     pagerUnlockAndRollback(pPager);
39799   }
39800 }
39801
39802 /*
39803 ** Acquire a reference to page number pgno in pager pPager (a page
39804 ** reference has type DbPage*). If the requested reference is 
39805 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
39806 **
39807 ** If the requested page is already in the cache, it is returned. 
39808 ** Otherwise, a new page object is allocated and populated with data
39809 ** read from the database file. In some cases, the pcache module may
39810 ** choose not to allocate a new page object and may reuse an existing
39811 ** object with no outstanding references.
39812 **
39813 ** The extra data appended to a page is always initialized to zeros the 
39814 ** first time a page is loaded into memory. If the page requested is 
39815 ** already in the cache when this function is called, then the extra
39816 ** data is left as it was when the page object was last used.
39817 **
39818 ** If the database image is smaller than the requested page or if a 
39819 ** non-zero value is passed as the noContent parameter and the 
39820 ** requested page is not already stored in the cache, then no 
39821 ** actual disk read occurs. In this case the memory image of the 
39822 ** page is initialized to all zeros. 
39823 **
39824 ** If noContent is true, it means that we do not care about the contents
39825 ** of the page. This occurs in two seperate scenarios:
39826 **
39827 **   a) When reading a free-list leaf page from the database, and
39828 **
39829 **   b) When a savepoint is being rolled back and we need to load
39830 **      a new page into the cache to be filled with the data read
39831 **      from the savepoint journal.
39832 **
39833 ** If noContent is true, then the data returned is zeroed instead of
39834 ** being read from the database. Additionally, the bits corresponding
39835 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
39836 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
39837 ** savepoints are set. This means if the page is made writable at any
39838 ** point in the future, using a call to sqlite3PagerWrite(), its contents
39839 ** will not be journaled. This saves IO.
39840 **
39841 ** The acquisition might fail for several reasons.  In all cases,
39842 ** an appropriate error code is returned and *ppPage is set to NULL.
39843 **
39844 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
39845 ** to find a page in the in-memory cache first.  If the page is not already
39846 ** in memory, this routine goes to disk to read it in whereas Lookup()
39847 ** just returns 0.  This routine acquires a read-lock the first time it
39848 ** has to go to disk, and could also playback an old journal if necessary.
39849 ** Since Lookup() never goes to disk, it never has to deal with locks
39850 ** or journal files.
39851 */
39852 SQLITE_PRIVATE int sqlite3PagerAcquire(
39853   Pager *pPager,      /* The pager open on the database file */
39854   Pgno pgno,          /* Page number to fetch */
39855   DbPage **ppPage,    /* Write a pointer to the page here */
39856   int noContent       /* Do not bother reading content from disk if true */
39857 ){
39858   int rc;
39859   PgHdr *pPg;
39860
39861   assert( pPager->eState>=PAGER_READER );
39862   assert( assert_pager_state(pPager) );
39863
39864   if( pgno==0 ){
39865     return SQLITE_CORRUPT_BKPT;
39866   }
39867
39868   /* If the pager is in the error state, return an error immediately. 
39869   ** Otherwise, request the page from the PCache layer. */
39870   if( pPager->errCode!=SQLITE_OK ){
39871     rc = pPager->errCode;
39872   }else{
39873     rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
39874   }
39875
39876   if( rc!=SQLITE_OK ){
39877     /* Either the call to sqlite3PcacheFetch() returned an error or the
39878     ** pager was already in the error-state when this function was called.
39879     ** Set pPg to 0 and jump to the exception handler.  */
39880     pPg = 0;
39881     goto pager_acquire_err;
39882   }
39883   assert( (*ppPage)->pgno==pgno );
39884   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
39885
39886   if( (*ppPage)->pPager && !noContent ){
39887     /* In this case the pcache already contains an initialized copy of
39888     ** the page. Return without further ado.  */
39889     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
39890     PAGER_INCR(pPager->nHit);
39891     return SQLITE_OK;
39892
39893   }else{
39894     /* The pager cache has created a new page. Its content needs to 
39895     ** be initialized.  */
39896
39897     PAGER_INCR(pPager->nMiss);
39898     pPg = *ppPage;
39899     pPg->pPager = pPager;
39900
39901     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
39902     ** number greater than this, or the unused locking-page, is requested. */
39903     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
39904       rc = SQLITE_CORRUPT_BKPT;
39905       goto pager_acquire_err;
39906     }
39907
39908     if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
39909       if( pgno>pPager->mxPgno ){
39910         rc = SQLITE_FULL;
39911         goto pager_acquire_err;
39912       }
39913       if( noContent ){
39914         /* Failure to set the bits in the InJournal bit-vectors is benign.
39915         ** It merely means that we might do some extra work to journal a 
39916         ** page that does not need to be journaled.  Nevertheless, be sure 
39917         ** to test the case where a malloc error occurs while trying to set 
39918         ** a bit in a bit vector.
39919         */
39920         sqlite3BeginBenignMalloc();
39921         if( pgno<=pPager->dbOrigSize ){
39922           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
39923           testcase( rc==SQLITE_NOMEM );
39924         }
39925         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
39926         testcase( rc==SQLITE_NOMEM );
39927         sqlite3EndBenignMalloc();
39928       }
39929       memset(pPg->pData, 0, pPager->pageSize);
39930       IOTRACE(("ZERO %p %d\n", pPager, pgno));
39931     }else{
39932       assert( pPg->pPager==pPager );
39933       rc = readDbPage(pPg);
39934       if( rc!=SQLITE_OK ){
39935         goto pager_acquire_err;
39936       }
39937     }
39938     pager_set_pagehash(pPg);
39939   }
39940
39941   return SQLITE_OK;
39942
39943 pager_acquire_err:
39944   assert( rc!=SQLITE_OK );
39945   if( pPg ){
39946     sqlite3PcacheDrop(pPg);
39947   }
39948   pagerUnlockIfUnused(pPager);
39949
39950   *ppPage = 0;
39951   return rc;
39952 }
39953
39954 /*
39955 ** Acquire a page if it is already in the in-memory cache.  Do
39956 ** not read the page from disk.  Return a pointer to the page,
39957 ** or 0 if the page is not in cache. 
39958 **
39959 ** See also sqlite3PagerGet().  The difference between this routine
39960 ** and sqlite3PagerGet() is that _get() will go to the disk and read
39961 ** in the page if the page is not already in cache.  This routine
39962 ** returns NULL if the page is not in cache or if a disk I/O error 
39963 ** has ever happened.
39964 */
39965 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
39966   PgHdr *pPg = 0;
39967   assert( pPager!=0 );
39968   assert( pgno!=0 );
39969   assert( pPager->pPCache!=0 );
39970   assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
39971   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
39972   return pPg;
39973 }
39974
39975 /*
39976 ** Release a page reference.
39977 **
39978 ** If the number of references to the page drop to zero, then the
39979 ** page is added to the LRU list.  When all references to all pages
39980 ** are released, a rollback occurs and the lock on the database is
39981 ** removed.
39982 */
39983 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
39984   if( pPg ){
39985     Pager *pPager = pPg->pPager;
39986     sqlite3PcacheRelease(pPg);
39987     pagerUnlockIfUnused(pPager);
39988   }
39989 }
39990
39991 /*
39992 ** This function is called at the start of every write transaction.
39993 ** There must already be a RESERVED or EXCLUSIVE lock on the database 
39994 ** file when this routine is called.
39995 **
39996 ** Open the journal file for pager pPager and write a journal header
39997 ** to the start of it. If there are active savepoints, open the sub-journal
39998 ** as well. This function is only used when the journal file is being 
39999 ** opened to write a rollback log for a transaction. It is not used 
40000 ** when opening a hot journal file to roll it back.
40001 **
40002 ** If the journal file is already open (as it may be in exclusive mode),
40003 ** then this function just writes a journal header to the start of the
40004 ** already open file. 
40005 **
40006 ** Whether or not the journal file is opened by this function, the
40007 ** Pager.pInJournal bitvec structure is allocated.
40008 **
40009 ** Return SQLITE_OK if everything is successful. Otherwise, return 
40010 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or 
40011 ** an IO error code if opening or writing the journal file fails.
40012 */
40013 static int pager_open_journal(Pager *pPager){
40014   int rc = SQLITE_OK;                        /* Return code */
40015   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
40016
40017   assert( pPager->eState==PAGER_WRITER_LOCKED );
40018   assert( assert_pager_state(pPager) );
40019   assert( pPager->pInJournal==0 );
40020   
40021   /* If already in the error state, this function is a no-op.  But on
40022   ** the other hand, this routine is never called if we are already in
40023   ** an error state. */
40024   if( NEVER(pPager->errCode) ) return pPager->errCode;
40025
40026   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
40027     pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
40028     if( pPager->pInJournal==0 ){
40029       return SQLITE_NOMEM;
40030     }
40031   
40032     /* Open the journal file if it is not already open. */
40033     if( !isOpen(pPager->jfd) ){
40034       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
40035         sqlite3MemJournalOpen(pPager->jfd);
40036       }else{
40037         const int flags =                   /* VFS flags to open journal file */
40038           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
40039           (pPager->tempFile ? 
40040             (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
40041             (SQLITE_OPEN_MAIN_JOURNAL)
40042           );
40043   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
40044         rc = sqlite3JournalOpen(
40045             pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
40046         );
40047   #else
40048         rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
40049   #endif
40050       }
40051       assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
40052     }
40053   
40054   
40055     /* Write the first journal header to the journal file and open 
40056     ** the sub-journal if necessary.
40057     */
40058     if( rc==SQLITE_OK ){
40059       /* TODO: Check if all of these are really required. */
40060       pPager->nRec = 0;
40061       pPager->journalOff = 0;
40062       pPager->setMaster = 0;
40063       pPager->journalHdr = 0;
40064       rc = writeJournalHdr(pPager);
40065     }
40066   }
40067
40068   if( rc!=SQLITE_OK ){
40069     sqlite3BitvecDestroy(pPager->pInJournal);
40070     pPager->pInJournal = 0;
40071   }else{
40072     assert( pPager->eState==PAGER_WRITER_LOCKED );
40073     pPager->eState = PAGER_WRITER_CACHEMOD;
40074   }
40075
40076   return rc;
40077 }
40078
40079 /*
40080 ** Begin a write-transaction on the specified pager object. If a 
40081 ** write-transaction has already been opened, this function is a no-op.
40082 **
40083 ** If the exFlag argument is false, then acquire at least a RESERVED
40084 ** lock on the database file. If exFlag is true, then acquire at least
40085 ** an EXCLUSIVE lock. If such a lock is already held, no locking 
40086 ** functions need be called.
40087 **
40088 ** If the subjInMemory argument is non-zero, then any sub-journal opened
40089 ** within this transaction will be opened as an in-memory file. This
40090 ** has no effect if the sub-journal is already opened (as it may be when
40091 ** running in exclusive mode) or if the transaction does not require a
40092 ** sub-journal. If the subjInMemory argument is zero, then any required
40093 ** sub-journal is implemented in-memory if pPager is an in-memory database, 
40094 ** or using a temporary file otherwise.
40095 */
40096 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
40097   int rc = SQLITE_OK;
40098
40099   if( pPager->errCode ) return pPager->errCode;
40100   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
40101   pPager->subjInMemory = (u8)subjInMemory;
40102
40103   if( ALWAYS(pPager->eState==PAGER_READER) ){
40104     assert( pPager->pInJournal==0 );
40105
40106     if( pagerUseWal(pPager) ){
40107       /* If the pager is configured to use locking_mode=exclusive, and an
40108       ** exclusive lock on the database is not already held, obtain it now.
40109       */
40110       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
40111         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
40112         if( rc!=SQLITE_OK ){
40113           return rc;
40114         }
40115         sqlite3WalExclusiveMode(pPager->pWal, 1);
40116       }
40117
40118       /* Grab the write lock on the log file. If successful, upgrade to
40119       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
40120       ** The busy-handler is not invoked if another connection already
40121       ** holds the write-lock. If possible, the upper layer will call it.
40122       */
40123       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
40124     }else{
40125       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
40126       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
40127       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
40128       ** lock, but not when obtaining the RESERVED lock.
40129       */
40130       rc = pagerLockDb(pPager, RESERVED_LOCK);
40131       if( rc==SQLITE_OK && exFlag ){
40132         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
40133       }
40134     }
40135
40136     if( rc==SQLITE_OK ){
40137       /* Change to WRITER_LOCKED state.
40138       **
40139       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
40140       ** when it has an open transaction, but never to DBMOD or FINISHED.
40141       ** This is because in those states the code to roll back savepoint 
40142       ** transactions may copy data from the sub-journal into the database 
40143       ** file as well as into the page cache. Which would be incorrect in 
40144       ** WAL mode.
40145       */
40146       pPager->eState = PAGER_WRITER_LOCKED;
40147       pPager->dbHintSize = pPager->dbSize;
40148       pPager->dbFileSize = pPager->dbSize;
40149       pPager->dbOrigSize = pPager->dbSize;
40150       pPager->journalOff = 0;
40151     }
40152
40153     assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
40154     assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
40155     assert( assert_pager_state(pPager) );
40156   }
40157
40158   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
40159   return rc;
40160 }
40161
40162 /*
40163 ** Mark a single data page as writeable. The page is written into the 
40164 ** main journal or sub-journal as required. If the page is written into
40165 ** one of the journals, the corresponding bit is set in the 
40166 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
40167 ** of any open savepoints as appropriate.
40168 */
40169 static int pager_write(PgHdr *pPg){
40170   void *pData = pPg->pData;
40171   Pager *pPager = pPg->pPager;
40172   int rc = SQLITE_OK;
40173
40174   /* This routine is not called unless a write-transaction has already 
40175   ** been started. The journal file may or may not be open at this point.
40176   ** It is never called in the ERROR state.
40177   */
40178   assert( pPager->eState==PAGER_WRITER_LOCKED
40179        || pPager->eState==PAGER_WRITER_CACHEMOD
40180        || pPager->eState==PAGER_WRITER_DBMOD
40181   );
40182   assert( assert_pager_state(pPager) );
40183
40184   /* If an error has been previously detected, report the same error
40185   ** again. This should not happen, but the check provides robustness. */
40186   if( NEVER(pPager->errCode) )  return pPager->errCode;
40187
40188   /* Higher-level routines never call this function if database is not
40189   ** writable.  But check anyway, just for robustness. */
40190   if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
40191
40192   CHECK_PAGE(pPg);
40193
40194   /* The journal file needs to be opened. Higher level routines have already
40195   ** obtained the necessary locks to begin the write-transaction, but the
40196   ** rollback journal might not yet be open. Open it now if this is the case.
40197   **
40198   ** This is done before calling sqlite3PcacheMakeDirty() on the page. 
40199   ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
40200   ** an error might occur and the pager would end up in WRITER_LOCKED state
40201   ** with pages marked as dirty in the cache.
40202   */
40203   if( pPager->eState==PAGER_WRITER_LOCKED ){
40204     rc = pager_open_journal(pPager);
40205     if( rc!=SQLITE_OK ) return rc;
40206   }
40207   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
40208   assert( assert_pager_state(pPager) );
40209
40210   /* Mark the page as dirty.  If the page has already been written
40211   ** to the journal then we can return right away.
40212   */
40213   sqlite3PcacheMakeDirty(pPg);
40214   if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
40215     assert( !pagerUseWal(pPager) );
40216   }else{
40217   
40218     /* The transaction journal now exists and we have a RESERVED or an
40219     ** EXCLUSIVE lock on the main database file.  Write the current page to
40220     ** the transaction journal if it is not there already.
40221     */
40222     if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
40223       assert( pagerUseWal(pPager)==0 );
40224       if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
40225         u32 cksum;
40226         char *pData2;
40227         i64 iOff = pPager->journalOff;
40228
40229         /* We should never write to the journal file the page that
40230         ** contains the database locks.  The following assert verifies
40231         ** that we do not. */
40232         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
40233
40234         assert( pPager->journalHdr<=pPager->journalOff );
40235         CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
40236         cksum = pager_cksum(pPager, (u8*)pData2);
40237
40238         /* Even if an IO or diskfull error occurs while journalling the
40239         ** page in the block above, set the need-sync flag for the page.
40240         ** Otherwise, when the transaction is rolled back, the logic in
40241         ** playback_one_page() will think that the page needs to be restored
40242         ** in the database file. And if an IO error occurs while doing so,
40243         ** then corruption may follow.
40244         */
40245         pPg->flags |= PGHDR_NEED_SYNC;
40246
40247         rc = write32bits(pPager->jfd, iOff, pPg->pgno);
40248         if( rc!=SQLITE_OK ) return rc;
40249         rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
40250         if( rc!=SQLITE_OK ) return rc;
40251         rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
40252         if( rc!=SQLITE_OK ) return rc;
40253
40254         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
40255                  pPager->journalOff, pPager->pageSize));
40256         PAGER_INCR(sqlite3_pager_writej_count);
40257         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
40258              PAGERID(pPager), pPg->pgno, 
40259              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
40260
40261         pPager->journalOff += 8 + pPager->pageSize;
40262         pPager->nRec++;
40263         assert( pPager->pInJournal!=0 );
40264         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
40265         testcase( rc==SQLITE_NOMEM );
40266         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
40267         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
40268         if( rc!=SQLITE_OK ){
40269           assert( rc==SQLITE_NOMEM );
40270           return rc;
40271         }
40272       }else{
40273         if( pPager->eState!=PAGER_WRITER_DBMOD ){
40274           pPg->flags |= PGHDR_NEED_SYNC;
40275         }
40276         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
40277                 PAGERID(pPager), pPg->pgno,
40278                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
40279       }
40280     }
40281   
40282     /* If the statement journal is open and the page is not in it,
40283     ** then write the current page to the statement journal.  Note that
40284     ** the statement journal format differs from the standard journal format
40285     ** in that it omits the checksums and the header.
40286     */
40287     if( subjRequiresPage(pPg) ){
40288       rc = subjournalPage(pPg);
40289     }
40290   }
40291
40292   /* Update the database size and return.
40293   */
40294   if( pPager->dbSize<pPg->pgno ){
40295     pPager->dbSize = pPg->pgno;
40296   }
40297   return rc;
40298 }
40299
40300 /*
40301 ** Mark a data page as writeable. This routine must be called before 
40302 ** making changes to a page. The caller must check the return value 
40303 ** of this function and be careful not to change any page data unless 
40304 ** this routine returns SQLITE_OK.
40305 **
40306 ** The difference between this function and pager_write() is that this
40307 ** function also deals with the special case where 2 or more pages
40308 ** fit on a single disk sector. In this case all co-resident pages
40309 ** must have been written to the journal file before returning.
40310 **
40311 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
40312 ** as appropriate. Otherwise, SQLITE_OK.
40313 */
40314 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
40315   int rc = SQLITE_OK;
40316
40317   PgHdr *pPg = pDbPage;
40318   Pager *pPager = pPg->pPager;
40319   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
40320
40321   assert( pPager->eState>=PAGER_WRITER_LOCKED );
40322   assert( pPager->eState!=PAGER_ERROR );
40323   assert( assert_pager_state(pPager) );
40324
40325   if( nPagePerSector>1 ){
40326     Pgno nPageCount;          /* Total number of pages in database file */
40327     Pgno pg1;                 /* First page of the sector pPg is located on. */
40328     int nPage = 0;            /* Number of pages starting at pg1 to journal */
40329     int ii;                   /* Loop counter */
40330     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
40331
40332     /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
40333     ** a journal header to be written between the pages journaled by
40334     ** this function.
40335     */
40336     assert( !MEMDB );
40337     assert( pPager->doNotSyncSpill==0 );
40338     pPager->doNotSyncSpill++;
40339
40340     /* This trick assumes that both the page-size and sector-size are
40341     ** an integer power of 2. It sets variable pg1 to the identifier
40342     ** of the first page of the sector pPg is located on.
40343     */
40344     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
40345
40346     nPageCount = pPager->dbSize;
40347     if( pPg->pgno>nPageCount ){
40348       nPage = (pPg->pgno - pg1)+1;
40349     }else if( (pg1+nPagePerSector-1)>nPageCount ){
40350       nPage = nPageCount+1-pg1;
40351     }else{
40352       nPage = nPagePerSector;
40353     }
40354     assert(nPage>0);
40355     assert(pg1<=pPg->pgno);
40356     assert((pg1+nPage)>pPg->pgno);
40357
40358     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
40359       Pgno pg = pg1+ii;
40360       PgHdr *pPage;
40361       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
40362         if( pg!=PAGER_MJ_PGNO(pPager) ){
40363           rc = sqlite3PagerGet(pPager, pg, &pPage);
40364           if( rc==SQLITE_OK ){
40365             rc = pager_write(pPage);
40366             if( pPage->flags&PGHDR_NEED_SYNC ){
40367               needSync = 1;
40368             }
40369             sqlite3PagerUnref(pPage);
40370           }
40371         }
40372       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
40373         if( pPage->flags&PGHDR_NEED_SYNC ){
40374           needSync = 1;
40375         }
40376         sqlite3PagerUnref(pPage);
40377       }
40378     }
40379
40380     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages 
40381     ** starting at pg1, then it needs to be set for all of them. Because
40382     ** writing to any of these nPage pages may damage the others, the
40383     ** journal file must contain sync()ed copies of all of them
40384     ** before any of them can be written out to the database file.
40385     */
40386     if( rc==SQLITE_OK && needSync ){
40387       assert( !MEMDB );
40388       for(ii=0; ii<nPage; ii++){
40389         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
40390         if( pPage ){
40391           pPage->flags |= PGHDR_NEED_SYNC;
40392           sqlite3PagerUnref(pPage);
40393         }
40394       }
40395     }
40396
40397     assert( pPager->doNotSyncSpill==1 );
40398     pPager->doNotSyncSpill--;
40399   }else{
40400     rc = pager_write(pDbPage);
40401   }
40402   return rc;
40403 }
40404
40405 /*
40406 ** Return TRUE if the page given in the argument was previously passed
40407 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
40408 ** to change the content of the page.
40409 */
40410 #ifndef NDEBUG
40411 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
40412   return pPg->flags&PGHDR_DIRTY;
40413 }
40414 #endif
40415
40416 /*
40417 ** A call to this routine tells the pager that it is not necessary to
40418 ** write the information on page pPg back to the disk, even though
40419 ** that page might be marked as dirty.  This happens, for example, when
40420 ** the page has been added as a leaf of the freelist and so its
40421 ** content no longer matters.
40422 **
40423 ** The overlying software layer calls this routine when all of the data
40424 ** on the given page is unused. The pager marks the page as clean so
40425 ** that it does not get written to disk.
40426 **
40427 ** Tests show that this optimization can quadruple the speed of large 
40428 ** DELETE operations.
40429 */
40430 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
40431   Pager *pPager = pPg->pPager;
40432   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
40433     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
40434     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
40435     pPg->flags |= PGHDR_DONT_WRITE;
40436     pager_set_pagehash(pPg);
40437   }
40438 }
40439
40440 /*
40441 ** This routine is called to increment the value of the database file 
40442 ** change-counter, stored as a 4-byte big-endian integer starting at 
40443 ** byte offset 24 of the pager file.  The secondary change counter at
40444 ** 92 is also updated, as is the SQLite version number at offset 96.
40445 **
40446 ** But this only happens if the pPager->changeCountDone flag is false.
40447 ** To avoid excess churning of page 1, the update only happens once.
40448 ** See also the pager_write_changecounter() routine that does an 
40449 ** unconditional update of the change counters.
40450 **
40451 ** If the isDirectMode flag is zero, then this is done by calling 
40452 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
40453 ** page data. In this case the file will be updated when the current
40454 ** transaction is committed.
40455 **
40456 ** The isDirectMode flag may only be non-zero if the library was compiled
40457 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
40458 ** if isDirect is non-zero, then the database file is updated directly
40459 ** by writing an updated version of page 1 using a call to the 
40460 ** sqlite3OsWrite() function.
40461 */
40462 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
40463   int rc = SQLITE_OK;
40464
40465   assert( pPager->eState==PAGER_WRITER_CACHEMOD
40466        || pPager->eState==PAGER_WRITER_DBMOD
40467   );
40468   assert( assert_pager_state(pPager) );
40469
40470   /* Declare and initialize constant integer 'isDirect'. If the
40471   ** atomic-write optimization is enabled in this build, then isDirect
40472   ** is initialized to the value passed as the isDirectMode parameter
40473   ** to this function. Otherwise, it is always set to zero.
40474   **
40475   ** The idea is that if the atomic-write optimization is not
40476   ** enabled at compile time, the compiler can omit the tests of
40477   ** 'isDirect' below, as well as the block enclosed in the
40478   ** "if( isDirect )" condition.
40479   */
40480 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
40481 # define DIRECT_MODE 0
40482   assert( isDirectMode==0 );
40483   UNUSED_PARAMETER(isDirectMode);
40484 #else
40485 # define DIRECT_MODE isDirectMode
40486 #endif
40487
40488   if( !pPager->changeCountDone && pPager->dbSize>0 ){
40489     PgHdr *pPgHdr;                /* Reference to page 1 */
40490
40491     assert( !pPager->tempFile && isOpen(pPager->fd) );
40492
40493     /* Open page 1 of the file for writing. */
40494     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
40495     assert( pPgHdr==0 || rc==SQLITE_OK );
40496
40497     /* If page one was fetched successfully, and this function is not
40498     ** operating in direct-mode, make page 1 writable.  When not in 
40499     ** direct mode, page 1 is always held in cache and hence the PagerGet()
40500     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
40501     */
40502     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
40503       rc = sqlite3PagerWrite(pPgHdr);
40504     }
40505
40506     if( rc==SQLITE_OK ){
40507       /* Actually do the update of the change counter */
40508       pager_write_changecounter(pPgHdr);
40509
40510       /* If running in direct mode, write the contents of page 1 to the file. */
40511       if( DIRECT_MODE ){
40512         const void *zBuf;
40513         assert( pPager->dbFileSize>0 );
40514         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
40515         if( rc==SQLITE_OK ){
40516           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
40517         }
40518         if( rc==SQLITE_OK ){
40519           pPager->changeCountDone = 1;
40520         }
40521       }else{
40522         pPager->changeCountDone = 1;
40523       }
40524     }
40525
40526     /* Release the page reference. */
40527     sqlite3PagerUnref(pPgHdr);
40528   }
40529   return rc;
40530 }
40531
40532 /*
40533 ** Sync the database file to disk. This is a no-op for in-memory databases
40534 ** or pages with the Pager.noSync flag set.
40535 **
40536 ** If successful, or if called on a pager for which it is a no-op, this
40537 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
40538 */
40539 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
40540   int rc = SQLITE_OK;
40541   if( !pPager->noSync ){
40542     assert( !MEMDB );
40543     rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
40544   }else if( isOpen(pPager->fd) ){
40545     assert( !MEMDB );
40546     sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, (void *)&rc);
40547   }
40548   return rc;
40549 }
40550
40551 /*
40552 ** This function may only be called while a write-transaction is active in
40553 ** rollback. If the connection is in WAL mode, this call is a no-op. 
40554 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on 
40555 ** the database file, an attempt is made to obtain one.
40556 **
40557 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
40558 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
40559 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is 
40560 ** returned.
40561 */
40562 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
40563   int rc = SQLITE_OK;
40564   assert( pPager->eState==PAGER_WRITER_CACHEMOD 
40565        || pPager->eState==PAGER_WRITER_DBMOD 
40566        || pPager->eState==PAGER_WRITER_LOCKED 
40567   );
40568   assert( assert_pager_state(pPager) );
40569   if( 0==pagerUseWal(pPager) ){
40570     rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
40571   }
40572   return rc;
40573 }
40574
40575 /*
40576 ** Sync the database file for the pager pPager. zMaster points to the name
40577 ** of a master journal file that should be written into the individual
40578 ** journal file. zMaster may be NULL, which is interpreted as no master
40579 ** journal (a single database transaction).
40580 **
40581 ** This routine ensures that:
40582 **
40583 **   * The database file change-counter is updated,
40584 **   * the journal is synced (unless the atomic-write optimization is used),
40585 **   * all dirty pages are written to the database file, 
40586 **   * the database file is truncated (if required), and
40587 **   * the database file synced. 
40588 **
40589 ** The only thing that remains to commit the transaction is to finalize 
40590 ** (delete, truncate or zero the first part of) the journal file (or 
40591 ** delete the master journal file if specified).
40592 **
40593 ** Note that if zMaster==NULL, this does not overwrite a previous value
40594 ** passed to an sqlite3PagerCommitPhaseOne() call.
40595 **
40596 ** If the final parameter - noSync - is true, then the database file itself
40597 ** is not synced. The caller must call sqlite3PagerSync() directly to
40598 ** sync the database file before calling CommitPhaseTwo() to delete the
40599 ** journal file in this case.
40600 */
40601 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
40602   Pager *pPager,                  /* Pager object */
40603   const char *zMaster,            /* If not NULL, the master journal name */
40604   int noSync                      /* True to omit the xSync on the db file */
40605 ){
40606   int rc = SQLITE_OK;             /* Return code */
40607
40608   assert( pPager->eState==PAGER_WRITER_LOCKED
40609        || pPager->eState==PAGER_WRITER_CACHEMOD
40610        || pPager->eState==PAGER_WRITER_DBMOD
40611        || pPager->eState==PAGER_ERROR
40612   );
40613   assert( assert_pager_state(pPager) );
40614
40615   /* If a prior error occurred, report that error again. */
40616   if( NEVER(pPager->errCode) ) return pPager->errCode;
40617
40618   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
40619       pPager->zFilename, zMaster, pPager->dbSize));
40620
40621   /* If no database changes have been made, return early. */
40622   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
40623
40624   if( MEMDB ){
40625     /* If this is an in-memory db, or no pages have been written to, or this
40626     ** function has already been called, it is mostly a no-op.  However, any
40627     ** backup in progress needs to be restarted.
40628     */
40629     sqlite3BackupRestart(pPager->pBackup);
40630   }else{
40631     if( pagerUseWal(pPager) ){
40632       PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
40633       if( pList ){
40634         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1, 
40635             (pPager->fullSync ? pPager->syncFlags : 0)
40636         );
40637       }
40638       if( rc==SQLITE_OK ){
40639         sqlite3PcacheCleanAll(pPager->pPCache);
40640       }
40641     }else{
40642       /* The following block updates the change-counter. Exactly how it
40643       ** does this depends on whether or not the atomic-update optimization
40644       ** was enabled at compile time, and if this transaction meets the 
40645       ** runtime criteria to use the operation: 
40646       **
40647       **    * The file-system supports the atomic-write property for
40648       **      blocks of size page-size, and 
40649       **    * This commit is not part of a multi-file transaction, and
40650       **    * Exactly one page has been modified and store in the journal file.
40651       **
40652       ** If the optimization was not enabled at compile time, then the
40653       ** pager_incr_changecounter() function is called to update the change
40654       ** counter in 'indirect-mode'. If the optimization is compiled in but
40655       ** is not applicable to this transaction, call sqlite3JournalCreate()
40656       ** to make sure the journal file has actually been created, then call
40657       ** pager_incr_changecounter() to update the change-counter in indirect
40658       ** mode. 
40659       **
40660       ** Otherwise, if the optimization is both enabled and applicable,
40661       ** then call pager_incr_changecounter() to update the change-counter
40662       ** in 'direct' mode. In this case the journal file will never be
40663       ** created for this transaction.
40664       */
40665   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
40666       PgHdr *pPg;
40667       assert( isOpen(pPager->jfd) 
40668            || pPager->journalMode==PAGER_JOURNALMODE_OFF 
40669            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
40670       );
40671       if( !zMaster && isOpen(pPager->jfd) 
40672        && pPager->journalOff==jrnlBufferSize(pPager) 
40673        && pPager->dbSize>=pPager->dbOrigSize
40674        && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
40675       ){
40676         /* Update the db file change counter via the direct-write method. The 
40677         ** following call will modify the in-memory representation of page 1 
40678         ** to include the updated change counter and then write page 1 
40679         ** directly to the database file. Because of the atomic-write 
40680         ** property of the host file-system, this is safe.
40681         */
40682         rc = pager_incr_changecounter(pPager, 1);
40683       }else{
40684         rc = sqlite3JournalCreate(pPager->jfd);
40685         if( rc==SQLITE_OK ){
40686           rc = pager_incr_changecounter(pPager, 0);
40687         }
40688       }
40689   #else
40690       rc = pager_incr_changecounter(pPager, 0);
40691   #endif
40692       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
40693   
40694       /* If this transaction has made the database smaller, then all pages
40695       ** being discarded by the truncation must be written to the journal
40696       ** file. This can only happen in auto-vacuum mode.
40697       **
40698       ** Before reading the pages with page numbers larger than the 
40699       ** current value of Pager.dbSize, set dbSize back to the value
40700       ** that it took at the start of the transaction. Otherwise, the
40701       ** calls to sqlite3PagerGet() return zeroed pages instead of 
40702       ** reading data from the database file.
40703       */
40704   #ifndef SQLITE_OMIT_AUTOVACUUM
40705       if( pPager->dbSize<pPager->dbOrigSize 
40706        && pPager->journalMode!=PAGER_JOURNALMODE_OFF
40707       ){
40708         Pgno i;                                   /* Iterator variable */
40709         const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
40710         const Pgno dbSize = pPager->dbSize;       /* Database image size */ 
40711         pPager->dbSize = pPager->dbOrigSize;
40712         for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
40713           if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
40714             PgHdr *pPage;             /* Page to journal */
40715             rc = sqlite3PagerGet(pPager, i, &pPage);
40716             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
40717             rc = sqlite3PagerWrite(pPage);
40718             sqlite3PagerUnref(pPage);
40719             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
40720           }
40721         }
40722         pPager->dbSize = dbSize;
40723       } 
40724   #endif
40725   
40726       /* Write the master journal name into the journal file. If a master 
40727       ** journal file name has already been written to the journal file, 
40728       ** or if zMaster is NULL (no master journal), then this call is a no-op.
40729       */
40730       rc = writeMasterJournal(pPager, zMaster);
40731       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
40732   
40733       /* Sync the journal file and write all dirty pages to the database.
40734       ** If the atomic-update optimization is being used, this sync will not 
40735       ** create the journal file or perform any real IO.
40736       **
40737       ** Because the change-counter page was just modified, unless the
40738       ** atomic-update optimization is used it is almost certain that the
40739       ** journal requires a sync here. However, in locking_mode=exclusive
40740       ** on a system under memory pressure it is just possible that this is 
40741       ** not the case. In this case it is likely enough that the redundant
40742       ** xSync() call will be changed to a no-op by the OS anyhow. 
40743       */
40744       rc = syncJournal(pPager, 0);
40745       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
40746   
40747       rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
40748       if( rc!=SQLITE_OK ){
40749         assert( rc!=SQLITE_IOERR_BLOCKED );
40750         goto commit_phase_one_exit;
40751       }
40752       sqlite3PcacheCleanAll(pPager->pPCache);
40753   
40754       /* If the file on disk is not the same size as the database image,
40755       ** then use pager_truncate to grow or shrink the file here.
40756       */
40757       if( pPager->dbSize!=pPager->dbFileSize ){
40758         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
40759         assert( pPager->eState==PAGER_WRITER_DBMOD );
40760         rc = pager_truncate(pPager, nNew);
40761         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
40762       }
40763   
40764       /* Finally, sync the database file. */
40765       if( !noSync ){
40766         rc = sqlite3PagerSync(pPager);
40767       }
40768       IOTRACE(("DBSYNC %p\n", pPager))
40769     }
40770   }
40771
40772 commit_phase_one_exit:
40773   if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
40774     pPager->eState = PAGER_WRITER_FINISHED;
40775   }
40776   return rc;
40777 }
40778
40779
40780 /*
40781 ** When this function is called, the database file has been completely
40782 ** updated to reflect the changes made by the current transaction and
40783 ** synced to disk. The journal file still exists in the file-system 
40784 ** though, and if a failure occurs at this point it will eventually
40785 ** be used as a hot-journal and the current transaction rolled back.
40786 **
40787 ** This function finalizes the journal file, either by deleting, 
40788 ** truncating or partially zeroing it, so that it cannot be used 
40789 ** for hot-journal rollback. Once this is done the transaction is
40790 ** irrevocably committed.
40791 **
40792 ** If an error occurs, an IO error code is returned and the pager
40793 ** moves into the error state. Otherwise, SQLITE_OK is returned.
40794 */
40795 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
40796   int rc = SQLITE_OK;                  /* Return code */
40797
40798   /* This routine should not be called if a prior error has occurred.
40799   ** But if (due to a coding error elsewhere in the system) it does get
40800   ** called, just return the same error code without doing anything. */
40801   if( NEVER(pPager->errCode) ) return pPager->errCode;
40802
40803   assert( pPager->eState==PAGER_WRITER_LOCKED
40804        || pPager->eState==PAGER_WRITER_FINISHED
40805        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
40806   );
40807   assert( assert_pager_state(pPager) );
40808
40809   /* An optimization. If the database was not actually modified during
40810   ** this transaction, the pager is running in exclusive-mode and is
40811   ** using persistent journals, then this function is a no-op.
40812   **
40813   ** The start of the journal file currently contains a single journal 
40814   ** header with the nRec field set to 0. If such a journal is used as
40815   ** a hot-journal during hot-journal rollback, 0 changes will be made
40816   ** to the database file. So there is no need to zero the journal 
40817   ** header. Since the pager is in exclusive mode, there is no need
40818   ** to drop any locks either.
40819   */
40820   if( pPager->eState==PAGER_WRITER_LOCKED 
40821    && pPager->exclusiveMode 
40822    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
40823   ){
40824     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
40825     pPager->eState = PAGER_READER;
40826     return SQLITE_OK;
40827   }
40828
40829   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
40830   rc = pager_end_transaction(pPager, pPager->setMaster);
40831   return pager_error(pPager, rc);
40832 }
40833
40834 /*
40835 ** If a write transaction is open, then all changes made within the 
40836 ** transaction are reverted and the current write-transaction is closed.
40837 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
40838 ** state if an error occurs.
40839 **
40840 ** If the pager is already in PAGER_ERROR state when this function is called,
40841 ** it returns Pager.errCode immediately. No work is performed in this case.
40842 **
40843 ** Otherwise, in rollback mode, this function performs two functions:
40844 **
40845 **   1) It rolls back the journal file, restoring all database file and 
40846 **      in-memory cache pages to the state they were in when the transaction
40847 **      was opened, and
40848 **
40849 **   2) It finalizes the journal file, so that it is not used for hot
40850 **      rollback at any point in the future.
40851 **
40852 ** Finalization of the journal file (task 2) is only performed if the 
40853 ** rollback is successful.
40854 **
40855 ** In WAL mode, all cache-entries containing data modified within the
40856 ** current transaction are either expelled from the cache or reverted to
40857 ** their pre-transaction state by re-reading data from the database or
40858 ** WAL files. The WAL transaction is then closed.
40859 */
40860 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
40861   int rc = SQLITE_OK;                  /* Return code */
40862   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
40863
40864   /* PagerRollback() is a no-op if called in READER or OPEN state. If
40865   ** the pager is already in the ERROR state, the rollback is not 
40866   ** attempted here. Instead, the error code is returned to the caller.
40867   */
40868   assert( assert_pager_state(pPager) );
40869   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
40870   if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
40871
40872   if( pagerUseWal(pPager) ){
40873     int rc2;
40874     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
40875     rc2 = pager_end_transaction(pPager, pPager->setMaster);
40876     if( rc==SQLITE_OK ) rc = rc2;
40877   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
40878     int eState = pPager->eState;
40879     rc = pager_end_transaction(pPager, 0);
40880     if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
40881       /* This can happen using journal_mode=off. Move the pager to the error 
40882       ** state to indicate that the contents of the cache may not be trusted.
40883       ** Any active readers will get SQLITE_ABORT.
40884       */
40885       pPager->errCode = SQLITE_ABORT;
40886       pPager->eState = PAGER_ERROR;
40887       return rc;
40888     }
40889   }else{
40890     rc = pager_playback(pPager, 0);
40891   }
40892
40893   assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
40894   assert( rc==SQLITE_OK || rc==SQLITE_FULL || (rc&0xFF)==SQLITE_IOERR );
40895
40896   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
40897   ** cache. So call pager_error() on the way out to make any error persistent.
40898   */
40899   return pager_error(pPager, rc);
40900 }
40901
40902 /*
40903 ** Return TRUE if the database file is opened read-only.  Return FALSE
40904 ** if the database is (in theory) writable.
40905 */
40906 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
40907   return pPager->readOnly;
40908 }
40909
40910 /*
40911 ** Return the number of references to the pager.
40912 */
40913 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
40914   return sqlite3PcacheRefCount(pPager->pPCache);
40915 }
40916
40917 /*
40918 ** Return the approximate number of bytes of memory currently
40919 ** used by the pager and its associated cache.
40920 */
40921 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
40922   int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
40923                                      + 5*sizeof(void*);
40924   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
40925            + sqlite3MallocSize(pPager)
40926            + pPager->pageSize;
40927 }
40928
40929 /*
40930 ** Return the number of references to the specified page.
40931 */
40932 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
40933   return sqlite3PcachePageRefcount(pPage);
40934 }
40935
40936 #ifdef SQLITE_TEST
40937 /*
40938 ** This routine is used for testing and analysis only.
40939 */
40940 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
40941   static int a[11];
40942   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
40943   a[1] = sqlite3PcachePagecount(pPager->pPCache);
40944   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
40945   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
40946   a[4] = pPager->eState;
40947   a[5] = pPager->errCode;
40948   a[6] = pPager->nHit;
40949   a[7] = pPager->nMiss;
40950   a[8] = 0;  /* Used to be pPager->nOvfl */
40951   a[9] = pPager->nRead;
40952   a[10] = pPager->nWrite;
40953   return a;
40954 }
40955 #endif
40956
40957 /*
40958 ** Return true if this is an in-memory pager.
40959 */
40960 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
40961   return MEMDB;
40962 }
40963
40964 /*
40965 ** Check that there are at least nSavepoint savepoints open. If there are
40966 ** currently less than nSavepoints open, then open one or more savepoints
40967 ** to make up the difference. If the number of savepoints is already
40968 ** equal to nSavepoint, then this function is a no-op.
40969 **
40970 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error 
40971 ** occurs while opening the sub-journal file, then an IO error code is
40972 ** returned. Otherwise, SQLITE_OK.
40973 */
40974 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
40975   int rc = SQLITE_OK;                       /* Return code */
40976   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
40977
40978   assert( pPager->eState>=PAGER_WRITER_LOCKED );
40979   assert( assert_pager_state(pPager) );
40980
40981   if( nSavepoint>nCurrent && pPager->useJournal ){
40982     int ii;                                 /* Iterator variable */
40983     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
40984
40985     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
40986     ** if the allocation fails. Otherwise, zero the new portion in case a 
40987     ** malloc failure occurs while populating it in the for(...) loop below.
40988     */
40989     aNew = (PagerSavepoint *)sqlite3Realloc(
40990         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
40991     );
40992     if( !aNew ){
40993       return SQLITE_NOMEM;
40994     }
40995     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
40996     pPager->aSavepoint = aNew;
40997
40998     /* Populate the PagerSavepoint structures just allocated. */
40999     for(ii=nCurrent; ii<nSavepoint; ii++){
41000       aNew[ii].nOrig = pPager->dbSize;
41001       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
41002         aNew[ii].iOffset = pPager->journalOff;
41003       }else{
41004         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
41005       }
41006       aNew[ii].iSubRec = pPager->nSubRec;
41007       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
41008       if( !aNew[ii].pInSavepoint ){
41009         return SQLITE_NOMEM;
41010       }
41011       if( pagerUseWal(pPager) ){
41012         sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
41013       }
41014       pPager->nSavepoint = ii+1;
41015     }
41016     assert( pPager->nSavepoint==nSavepoint );
41017     assertTruncateConstraint(pPager);
41018   }
41019
41020   return rc;
41021 }
41022
41023 /*
41024 ** This function is called to rollback or release (commit) a savepoint.
41025 ** The savepoint to release or rollback need not be the most recently 
41026 ** created savepoint.
41027 **
41028 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
41029 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
41030 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
41031 ** that have occurred since the specified savepoint was created.
41032 **
41033 ** The savepoint to rollback or release is identified by parameter 
41034 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
41035 ** (the first created). A value of (Pager.nSavepoint-1) means operate
41036 ** on the most recently created savepoint. If iSavepoint is greater than
41037 ** (Pager.nSavepoint-1), then this function is a no-op.
41038 **
41039 ** If a negative value is passed to this function, then the current
41040 ** transaction is rolled back. This is different to calling 
41041 ** sqlite3PagerRollback() because this function does not terminate
41042 ** the transaction or unlock the database, it just restores the 
41043 ** contents of the database to its original state. 
41044 **
41045 ** In any case, all savepoints with an index greater than iSavepoint 
41046 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
41047 ** then savepoint iSavepoint is also destroyed.
41048 **
41049 ** This function may return SQLITE_NOMEM if a memory allocation fails,
41050 ** or an IO error code if an IO error occurs while rolling back a 
41051 ** savepoint. If no errors occur, SQLITE_OK is returned.
41052 */ 
41053 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
41054   int rc = pPager->errCode;       /* Return code */
41055
41056   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
41057   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
41058
41059   if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
41060     int ii;            /* Iterator variable */
41061     int nNew;          /* Number of remaining savepoints after this op. */
41062
41063     /* Figure out how many savepoints will still be active after this
41064     ** operation. Store this value in nNew. Then free resources associated 
41065     ** with any savepoints that are destroyed by this operation.
41066     */
41067     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
41068     for(ii=nNew; ii<pPager->nSavepoint; ii++){
41069       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
41070     }
41071     pPager->nSavepoint = nNew;
41072
41073     /* If this is a release of the outermost savepoint, truncate 
41074     ** the sub-journal to zero bytes in size. */
41075     if( op==SAVEPOINT_RELEASE ){
41076       if( nNew==0 && isOpen(pPager->sjfd) ){
41077         /* Only truncate if it is an in-memory sub-journal. */
41078         if( sqlite3IsMemJournal(pPager->sjfd) ){
41079           rc = sqlite3OsTruncate(pPager->sjfd, 0);
41080           assert( rc==SQLITE_OK );
41081         }
41082         pPager->nSubRec = 0;
41083       }
41084     }
41085     /* Else this is a rollback operation, playback the specified savepoint.
41086     ** If this is a temp-file, it is possible that the journal file has
41087     ** not yet been opened. In this case there have been no changes to
41088     ** the database file, so the playback operation can be skipped.
41089     */
41090     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
41091       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
41092       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
41093       assert(rc!=SQLITE_DONE);
41094     }
41095   }
41096
41097   return rc;
41098 }
41099
41100 /*
41101 ** Return the full pathname of the database file.
41102 */
41103 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
41104   return pPager->zFilename;
41105 }
41106
41107 /*
41108 ** Return the VFS structure for the pager.
41109 */
41110 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
41111   return pPager->pVfs;
41112 }
41113
41114 /*
41115 ** Return the file handle for the database file associated
41116 ** with the pager.  This might return NULL if the file has
41117 ** not yet been opened.
41118 */
41119 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
41120   return pPager->fd;
41121 }
41122
41123 /*
41124 ** Return the full pathname of the journal file.
41125 */
41126 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
41127   return pPager->zJournal;
41128 }
41129
41130 /*
41131 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
41132 ** if fsync()s are executed normally.
41133 */
41134 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
41135   return pPager->noSync;
41136 }
41137
41138 #ifdef SQLITE_HAS_CODEC
41139 /*
41140 ** Set or retrieve the codec for this pager
41141 */
41142 SQLITE_PRIVATE void sqlite3PagerSetCodec(
41143   Pager *pPager,
41144   void *(*xCodec)(void*,void*,Pgno,int),
41145   void (*xCodecSizeChng)(void*,int,int),
41146   void (*xCodecFree)(void*),
41147   void *pCodec
41148 ){
41149   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
41150   pPager->xCodec = pPager->memDb ? 0 : xCodec;
41151   pPager->xCodecSizeChng = xCodecSizeChng;
41152   pPager->xCodecFree = xCodecFree;
41153   pPager->pCodec = pCodec;
41154   pagerReportSize(pPager);
41155 }
41156 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
41157   return pPager->pCodec;
41158 }
41159 #endif
41160
41161 #ifndef SQLITE_OMIT_AUTOVACUUM
41162 /*
41163 ** Move the page pPg to location pgno in the file.
41164 **
41165 ** There must be no references to the page previously located at
41166 ** pgno (which we call pPgOld) though that page is allowed to be
41167 ** in cache.  If the page previously located at pgno is not already
41168 ** in the rollback journal, it is not put there by by this routine.
41169 **
41170 ** References to the page pPg remain valid. Updating any
41171 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
41172 ** allocated along with the page) is the responsibility of the caller.
41173 **
41174 ** A transaction must be active when this routine is called. It used to be
41175 ** required that a statement transaction was not active, but this restriction
41176 ** has been removed (CREATE INDEX needs to move a page when a statement
41177 ** transaction is active).
41178 **
41179 ** If the fourth argument, isCommit, is non-zero, then this page is being
41180 ** moved as part of a database reorganization just before the transaction 
41181 ** is being committed. In this case, it is guaranteed that the database page 
41182 ** pPg refers to will not be written to again within this transaction.
41183 **
41184 ** This function may return SQLITE_NOMEM or an IO error code if an error
41185 ** occurs. Otherwise, it returns SQLITE_OK.
41186 */
41187 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
41188   PgHdr *pPgOld;               /* The page being overwritten. */
41189   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
41190   int rc;                      /* Return code */
41191   Pgno origPgno;               /* The original page number */
41192
41193   assert( pPg->nRef>0 );
41194   assert( pPager->eState==PAGER_WRITER_CACHEMOD
41195        || pPager->eState==PAGER_WRITER_DBMOD
41196   );
41197   assert( assert_pager_state(pPager) );
41198
41199   /* In order to be able to rollback, an in-memory database must journal
41200   ** the page we are moving from.
41201   */
41202   if( MEMDB ){
41203     rc = sqlite3PagerWrite(pPg);
41204     if( rc ) return rc;
41205   }
41206
41207   /* If the page being moved is dirty and has not been saved by the latest
41208   ** savepoint, then save the current contents of the page into the 
41209   ** sub-journal now. This is required to handle the following scenario:
41210   **
41211   **   BEGIN;
41212   **     <journal page X, then modify it in memory>
41213   **     SAVEPOINT one;
41214   **       <Move page X to location Y>
41215   **     ROLLBACK TO one;
41216   **
41217   ** If page X were not written to the sub-journal here, it would not
41218   ** be possible to restore its contents when the "ROLLBACK TO one"
41219   ** statement were is processed.
41220   **
41221   ** subjournalPage() may need to allocate space to store pPg->pgno into
41222   ** one or more savepoint bitvecs. This is the reason this function
41223   ** may return SQLITE_NOMEM.
41224   */
41225   if( pPg->flags&PGHDR_DIRTY
41226    && subjRequiresPage(pPg)
41227    && SQLITE_OK!=(rc = subjournalPage(pPg))
41228   ){
41229     return rc;
41230   }
41231
41232   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", 
41233       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
41234   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
41235
41236   /* If the journal needs to be sync()ed before page pPg->pgno can
41237   ** be written to, store pPg->pgno in local variable needSyncPgno.
41238   **
41239   ** If the isCommit flag is set, there is no need to remember that
41240   ** the journal needs to be sync()ed before database page pPg->pgno 
41241   ** can be written to. The caller has already promised not to write to it.
41242   */
41243   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
41244     needSyncPgno = pPg->pgno;
41245     assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
41246     assert( pPg->flags&PGHDR_DIRTY );
41247   }
41248
41249   /* If the cache contains a page with page-number pgno, remove it
41250   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for 
41251   ** page pgno before the 'move' operation, it needs to be retained 
41252   ** for the page moved there.
41253   */
41254   pPg->flags &= ~PGHDR_NEED_SYNC;
41255   pPgOld = pager_lookup(pPager, pgno);
41256   assert( !pPgOld || pPgOld->nRef==1 );
41257   if( pPgOld ){
41258     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
41259     if( MEMDB ){
41260       /* Do not discard pages from an in-memory database since we might
41261       ** need to rollback later.  Just move the page out of the way. */
41262       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
41263     }else{
41264       sqlite3PcacheDrop(pPgOld);
41265     }
41266   }
41267
41268   origPgno = pPg->pgno;
41269   sqlite3PcacheMove(pPg, pgno);
41270   sqlite3PcacheMakeDirty(pPg);
41271
41272   /* For an in-memory database, make sure the original page continues
41273   ** to exist, in case the transaction needs to roll back.  Use pPgOld
41274   ** as the original page since it has already been allocated.
41275   */
41276   if( MEMDB ){
41277     assert( pPgOld );
41278     sqlite3PcacheMove(pPgOld, origPgno);
41279     sqlite3PagerUnref(pPgOld);
41280   }
41281
41282   if( needSyncPgno ){
41283     /* If needSyncPgno is non-zero, then the journal file needs to be 
41284     ** sync()ed before any data is written to database file page needSyncPgno.
41285     ** Currently, no such page exists in the page-cache and the 
41286     ** "is journaled" bitvec flag has been set. This needs to be remedied by
41287     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
41288     ** flag.
41289     **
41290     ** If the attempt to load the page into the page-cache fails, (due
41291     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
41292     ** array. Otherwise, if the page is loaded and written again in
41293     ** this transaction, it may be written to the database file before
41294     ** it is synced into the journal file. This way, it may end up in
41295     ** the journal file twice, but that is not a problem.
41296     */
41297     PgHdr *pPgHdr;
41298     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
41299     if( rc!=SQLITE_OK ){
41300       if( needSyncPgno<=pPager->dbOrigSize ){
41301         assert( pPager->pTmpSpace!=0 );
41302         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
41303       }
41304       return rc;
41305     }
41306     pPgHdr->flags |= PGHDR_NEED_SYNC;
41307     sqlite3PcacheMakeDirty(pPgHdr);
41308     sqlite3PagerUnref(pPgHdr);
41309   }
41310
41311   return SQLITE_OK;
41312 }
41313 #endif
41314
41315 /*
41316 ** Return a pointer to the data for the specified page.
41317 */
41318 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
41319   assert( pPg->nRef>0 || pPg->pPager->memDb );
41320   return pPg->pData;
41321 }
41322
41323 /*
41324 ** Return a pointer to the Pager.nExtra bytes of "extra" space 
41325 ** allocated along with the specified page.
41326 */
41327 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
41328   return pPg->pExtra;
41329 }
41330
41331 /*
41332 ** Get/set the locking-mode for this pager. Parameter eMode must be one
41333 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
41334 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
41335 ** the locking-mode is set to the value specified.
41336 **
41337 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
41338 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
41339 ** locking-mode.
41340 */
41341 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
41342   assert( eMode==PAGER_LOCKINGMODE_QUERY
41343             || eMode==PAGER_LOCKINGMODE_NORMAL
41344             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
41345   assert( PAGER_LOCKINGMODE_QUERY<0 );
41346   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
41347   assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
41348   if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
41349     pPager->exclusiveMode = (u8)eMode;
41350   }
41351   return (int)pPager->exclusiveMode;
41352 }
41353
41354 /*
41355 ** Set the journal-mode for this pager. Parameter eMode must be one of:
41356 **
41357 **    PAGER_JOURNALMODE_DELETE
41358 **    PAGER_JOURNALMODE_TRUNCATE
41359 **    PAGER_JOURNALMODE_PERSIST
41360 **    PAGER_JOURNALMODE_OFF
41361 **    PAGER_JOURNALMODE_MEMORY
41362 **    PAGER_JOURNALMODE_WAL
41363 **
41364 ** The journalmode is set to the value specified if the change is allowed.
41365 ** The change may be disallowed for the following reasons:
41366 **
41367 **   *  An in-memory database can only have its journal_mode set to _OFF
41368 **      or _MEMORY.
41369 **
41370 **   *  Temporary databases cannot have _WAL journalmode.
41371 **
41372 ** The returned indicate the current (possibly updated) journal-mode.
41373 */
41374 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
41375   u8 eOld = pPager->journalMode;    /* Prior journalmode */
41376
41377 #ifdef SQLITE_DEBUG
41378   /* The print_pager_state() routine is intended to be used by the debugger
41379   ** only.  We invoke it once here to suppress a compiler warning. */
41380   print_pager_state(pPager);
41381 #endif
41382
41383
41384   /* The eMode parameter is always valid */
41385   assert(      eMode==PAGER_JOURNALMODE_DELETE
41386             || eMode==PAGER_JOURNALMODE_TRUNCATE
41387             || eMode==PAGER_JOURNALMODE_PERSIST
41388             || eMode==PAGER_JOURNALMODE_OFF 
41389             || eMode==PAGER_JOURNALMODE_WAL 
41390             || eMode==PAGER_JOURNALMODE_MEMORY );
41391
41392   /* This routine is only called from the OP_JournalMode opcode, and
41393   ** the logic there will never allow a temporary file to be changed
41394   ** to WAL mode.
41395   */
41396   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
41397
41398   /* Do allow the journalmode of an in-memory database to be set to
41399   ** anything other than MEMORY or OFF
41400   */
41401   if( MEMDB ){
41402     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
41403     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
41404       eMode = eOld;
41405     }
41406   }
41407
41408   if( eMode!=eOld ){
41409
41410     /* Change the journal mode. */
41411     assert( pPager->eState!=PAGER_ERROR );
41412     pPager->journalMode = (u8)eMode;
41413
41414     /* When transistioning from TRUNCATE or PERSIST to any other journal
41415     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
41416     ** delete the journal file.
41417     */
41418     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
41419     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
41420     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
41421     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
41422     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
41423     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
41424
41425     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
41426     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
41427
41428       /* In this case we would like to delete the journal file. If it is
41429       ** not possible, then that is not a problem. Deleting the journal file
41430       ** here is an optimization only.
41431       **
41432       ** Before deleting the journal file, obtain a RESERVED lock on the
41433       ** database file. This ensures that the journal file is not deleted
41434       ** while it is in use by some other client.
41435       */
41436       sqlite3OsClose(pPager->jfd);
41437       if( pPager->eLock>=RESERVED_LOCK ){
41438         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
41439       }else{
41440         int rc = SQLITE_OK;
41441         int state = pPager->eState;
41442         assert( state==PAGER_OPEN || state==PAGER_READER );
41443         if( state==PAGER_OPEN ){
41444           rc = sqlite3PagerSharedLock(pPager);
41445         }
41446         if( pPager->eState==PAGER_READER ){
41447           assert( rc==SQLITE_OK );
41448           rc = pagerLockDb(pPager, RESERVED_LOCK);
41449         }
41450         if( rc==SQLITE_OK ){
41451           sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
41452         }
41453         if( rc==SQLITE_OK && state==PAGER_READER ){
41454           pagerUnlockDb(pPager, SHARED_LOCK);
41455         }else if( state==PAGER_OPEN ){
41456           pager_unlock(pPager);
41457         }
41458         assert( state==pPager->eState );
41459       }
41460     }
41461   }
41462
41463   /* Return the new journal mode */
41464   return (int)pPager->journalMode;
41465 }
41466
41467 /*
41468 ** Return the current journal mode.
41469 */
41470 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
41471   return (int)pPager->journalMode;
41472 }
41473
41474 /*
41475 ** Return TRUE if the pager is in a state where it is OK to change the
41476 ** journalmode.  Journalmode changes can only happen when the database
41477 ** is unmodified.
41478 */
41479 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
41480   assert( assert_pager_state(pPager) );
41481   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
41482   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
41483   return 1;
41484 }
41485
41486 /*
41487 ** Get/set the size-limit used for persistent journal files.
41488 **
41489 ** Setting the size limit to -1 means no limit is enforced.
41490 ** An attempt to set a limit smaller than -1 is a no-op.
41491 */
41492 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
41493   if( iLimit>=-1 ){
41494     pPager->journalSizeLimit = iLimit;
41495   }
41496   return pPager->journalSizeLimit;
41497 }
41498
41499 /*
41500 ** Return a pointer to the pPager->pBackup variable. The backup module
41501 ** in backup.c maintains the content of this variable. This module
41502 ** uses it opaquely as an argument to sqlite3BackupRestart() and
41503 ** sqlite3BackupUpdate() only.
41504 */
41505 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
41506   return &pPager->pBackup;
41507 }
41508
41509 #ifndef SQLITE_OMIT_WAL
41510 /*
41511 ** This function is called when the user invokes "PRAGMA checkpoint".
41512 */
41513 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager){
41514   int rc = SQLITE_OK;
41515   if( pPager->pWal ){
41516     u8 *zBuf = (u8 *)pPager->pTmpSpace;
41517     rc = sqlite3WalCheckpoint(pPager->pWal, pPager->ckptSyncFlags,
41518                               pPager->pageSize, zBuf);
41519   }
41520   return rc;
41521 }
41522
41523 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
41524   return sqlite3WalCallback(pPager->pWal);
41525 }
41526
41527 /*
41528 ** Return true if the underlying VFS for the given pager supports the
41529 ** primitives necessary for write-ahead logging.
41530 */
41531 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
41532   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
41533   return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
41534 }
41535
41536 /*
41537 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
41538 ** is obtained instead, immediately release it.
41539 */
41540 static int pagerExclusiveLock(Pager *pPager){
41541   int rc;                         /* Return code */
41542
41543   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
41544   rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
41545   if( rc!=SQLITE_OK ){
41546     /* If the attempt to grab the pending lock failed, release the 
41547     ** exclusive lock that may have been obtained instead.  */
41548     pagerUnlockDb(pPager, SHARED_LOCK);
41549   }
41550
41551   return rc;
41552 }
41553
41554 /*
41555 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in 
41556 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
41557 ** lock on the database file and use heap-memory to store the wal-index
41558 ** in. Otherwise, use the normal shared-memory.
41559 */
41560 static int pagerOpenWal(Pager *pPager){
41561   int rc = SQLITE_OK;
41562
41563   assert( pPager->pWal==0 && pPager->tempFile==0 );
41564   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK || pPager->noReadlock);
41565
41566   /* If the pager is already in exclusive-mode, the WAL module will use 
41567   ** heap-memory for the wal-index instead of the VFS shared-memory 
41568   ** implementation. Take the exclusive lock now, before opening the WAL
41569   ** file, to make sure this is safe.
41570   */
41571   if( pPager->exclusiveMode ){
41572     rc = pagerExclusiveLock(pPager);
41573   }
41574
41575   /* Open the connection to the log file. If this operation fails, 
41576   ** (e.g. due to malloc() failure), return an error code.
41577   */
41578   if( rc==SQLITE_OK ){
41579     rc = sqlite3WalOpen(pPager->pVfs, 
41580         pPager->fd, pPager->zWal, pPager->exclusiveMode, &pPager->pWal
41581     );
41582   }
41583
41584   return rc;
41585 }
41586
41587
41588 /*
41589 ** The caller must be holding a SHARED lock on the database file to call
41590 ** this function.
41591 **
41592 ** If the pager passed as the first argument is open on a real database
41593 ** file (not a temp file or an in-memory database), and the WAL file
41594 ** is not already open, make an attempt to open it now. If successful,
41595 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does 
41596 ** not support the xShmXXX() methods, return an error code. *pbOpen is
41597 ** not modified in either case.
41598 **
41599 ** If the pager is open on a temp-file (or in-memory database), or if
41600 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
41601 ** without doing anything.
41602 */
41603 SQLITE_PRIVATE int sqlite3PagerOpenWal(
41604   Pager *pPager,                  /* Pager object */
41605   int *pbOpen                     /* OUT: Set to true if call is a no-op */
41606 ){
41607   int rc = SQLITE_OK;             /* Return code */
41608
41609   assert( assert_pager_state(pPager) );
41610   assert( pPager->eState==PAGER_OPEN   || pbOpen );
41611   assert( pPager->eState==PAGER_READER || !pbOpen );
41612   assert( pbOpen==0 || *pbOpen==0 );
41613   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
41614
41615   if( !pPager->tempFile && !pPager->pWal ){
41616     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
41617
41618     /* Close any rollback journal previously open */
41619     sqlite3OsClose(pPager->jfd);
41620
41621     rc = pagerOpenWal(pPager);
41622     if( rc==SQLITE_OK ){
41623       pPager->journalMode = PAGER_JOURNALMODE_WAL;
41624       pPager->eState = PAGER_OPEN;
41625     }
41626   }else{
41627     *pbOpen = 1;
41628   }
41629
41630   return rc;
41631 }
41632
41633 /*
41634 ** This function is called to close the connection to the log file prior
41635 ** to switching from WAL to rollback mode.
41636 **
41637 ** Before closing the log file, this function attempts to take an 
41638 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
41639 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
41640 ** If successful, the EXCLUSIVE lock is not released before returning.
41641 */
41642 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
41643   int rc = SQLITE_OK;
41644
41645   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
41646
41647   /* If the log file is not already open, but does exist in the file-system,
41648   ** it may need to be checkpointed before the connection can switch to
41649   ** rollback mode. Open it now so this can happen.
41650   */
41651   if( !pPager->pWal ){
41652     int logexists = 0;
41653     rc = pagerLockDb(pPager, SHARED_LOCK);
41654     if( rc==SQLITE_OK ){
41655       rc = sqlite3OsAccess(
41656           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
41657       );
41658     }
41659     if( rc==SQLITE_OK && logexists ){
41660       rc = pagerOpenWal(pPager);
41661     }
41662   }
41663     
41664   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
41665   ** the database file, the log and log-summary files will be deleted.
41666   */
41667   if( rc==SQLITE_OK && pPager->pWal ){
41668     rc = pagerExclusiveLock(pPager);
41669     if( rc==SQLITE_OK ){
41670       rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
41671                            pPager->pageSize, (u8*)pPager->pTmpSpace);
41672       pPager->pWal = 0;
41673     }
41674   }
41675   return rc;
41676 }
41677
41678 #ifdef SQLITE_HAS_CODEC
41679 /*
41680 ** This function is called by the wal module when writing page content
41681 ** into the log file.
41682 **
41683 ** This function returns a pointer to a buffer containing the encrypted
41684 ** page content. If a malloc fails, this function may return NULL.
41685 */
41686 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
41687   void *aData = 0;
41688   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
41689   return aData;
41690 }
41691 #endif /* SQLITE_HAS_CODEC */
41692
41693 #endif /* !SQLITE_OMIT_WAL */
41694
41695 #endif /* SQLITE_OMIT_DISKIO */
41696
41697 /************** End of pager.c ***********************************************/
41698 /************** Begin file wal.c *********************************************/
41699 /*
41700 ** 2010 February 1
41701 **
41702 ** The author disclaims copyright to this source code.  In place of
41703 ** a legal notice, here is a blessing:
41704 **
41705 **    May you do good and not evil.
41706 **    May you find forgiveness for yourself and forgive others.
41707 **    May you share freely, never taking more than you give.
41708 **
41709 *************************************************************************
41710 **
41711 ** This file contains the implementation of a write-ahead log (WAL) used in 
41712 ** "journal_mode=WAL" mode.
41713 **
41714 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
41715 **
41716 ** A WAL file consists of a header followed by zero or more "frames".
41717 ** Each frame records the revised content of a single page from the
41718 ** database file.  All changes to the database are recorded by writing
41719 ** frames into the WAL.  Transactions commit when a frame is written that
41720 ** contains a commit marker.  A single WAL can and usually does record 
41721 ** multiple transactions.  Periodically, the content of the WAL is
41722 ** transferred back into the database file in an operation called a
41723 ** "checkpoint".
41724 **
41725 ** A single WAL file can be used multiple times.  In other words, the
41726 ** WAL can fill up with frames and then be checkpointed and then new
41727 ** frames can overwrite the old ones.  A WAL always grows from beginning
41728 ** toward the end.  Checksums and counters attached to each frame are
41729 ** used to determine which frames within the WAL are valid and which
41730 ** are leftovers from prior checkpoints.
41731 **
41732 ** The WAL header is 32 bytes in size and consists of the following eight
41733 ** big-endian 32-bit unsigned integer values:
41734 **
41735 **     0: Magic number.  0x377f0682 or 0x377f0683
41736 **     4: File format version.  Currently 3007000
41737 **     8: Database page size.  Example: 1024
41738 **    12: Checkpoint sequence number
41739 **    16: Salt-1, random integer incremented with each checkpoint
41740 **    20: Salt-2, a different random integer changing with each ckpt
41741 **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
41742 **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
41743 **
41744 ** Immediately following the wal-header are zero or more frames. Each
41745 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
41746 ** of page data. The frame-header is six big-endian 32-bit unsigned 
41747 ** integer values, as follows:
41748 **
41749 **     0: Page number.
41750 **     4: For commit records, the size of the database image in pages 
41751 **        after the commit. For all other records, zero.
41752 **     8: Salt-1 (copied from the header)
41753 **    12: Salt-2 (copied from the header)
41754 **    16: Checksum-1.
41755 **    20: Checksum-2.
41756 **
41757 ** A frame is considered valid if and only if the following conditions are
41758 ** true:
41759 **
41760 **    (1) The salt-1 and salt-2 values in the frame-header match
41761 **        salt values in the wal-header
41762 **
41763 **    (2) The checksum values in the final 8 bytes of the frame-header
41764 **        exactly match the checksum computed consecutively on the
41765 **        WAL header and the first 8 bytes and the content of all frames
41766 **        up to and including the current frame.
41767 **
41768 ** The checksum is computed using 32-bit big-endian integers if the
41769 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
41770 ** is computed using little-endian if the magic number is 0x377f0682.
41771 ** The checksum values are always stored in the frame header in a
41772 ** big-endian format regardless of which byte order is used to compute
41773 ** the checksum.  The checksum is computed by interpreting the input as
41774 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
41775 ** algorithm used for the checksum is as follows:
41776 ** 
41777 **   for i from 0 to n-1 step 2:
41778 **     s0 += x[i] + s1;
41779 **     s1 += x[i+1] + s0;
41780 **   endfor
41781 **
41782 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
41783 ** in reverse order (the largest fibonacci weight occurs on the first element
41784 ** of the sequence being summed.)  The s1 value spans all 32-bit 
41785 ** terms of the sequence whereas s0 omits the final term.
41786 **
41787 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
41788 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
41789 ** The VFS.xSync operations serve as write barriers - all writes launched
41790 ** before the xSync must complete before any write that launches after the
41791 ** xSync begins.
41792 **
41793 ** After each checkpoint, the salt-1 value is incremented and the salt-2
41794 ** value is randomized.  This prevents old and new frames in the WAL from
41795 ** being considered valid at the same time and being checkpointing together
41796 ** following a crash.
41797 **
41798 ** READER ALGORITHM
41799 **
41800 ** To read a page from the database (call it page number P), a reader
41801 ** first checks the WAL to see if it contains page P.  If so, then the
41802 ** last valid instance of page P that is a followed by a commit frame
41803 ** or is a commit frame itself becomes the value read.  If the WAL
41804 ** contains no copies of page P that are valid and which are a commit
41805 ** frame or are followed by a commit frame, then page P is read from
41806 ** the database file.
41807 **
41808 ** To start a read transaction, the reader records the index of the last
41809 ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
41810 ** for all subsequent read operations.  New transactions can be appended
41811 ** to the WAL, but as long as the reader uses its original mxFrame value
41812 ** and ignores the newly appended content, it will see a consistent snapshot
41813 ** of the database from a single point in time.  This technique allows
41814 ** multiple concurrent readers to view different versions of the database
41815 ** content simultaneously.
41816 **
41817 ** The reader algorithm in the previous paragraphs works correctly, but 
41818 ** because frames for page P can appear anywhere within the WAL, the
41819 ** reader has to scan the entire WAL looking for page P frames.  If the
41820 ** WAL is large (multiple megabytes is typical) that scan can be slow,
41821 ** and read performance suffers.  To overcome this problem, a separate
41822 ** data structure called the wal-index is maintained to expedite the
41823 ** search for frames of a particular page.
41824 ** 
41825 ** WAL-INDEX FORMAT
41826 **
41827 ** Conceptually, the wal-index is shared memory, though VFS implementations
41828 ** might choose to implement the wal-index using a mmapped file.  Because
41829 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL 
41830 ** on a network filesystem.  All users of the database must be able to
41831 ** share memory.
41832 **
41833 ** The wal-index is transient.  After a crash, the wal-index can (and should
41834 ** be) reconstructed from the original WAL file.  In fact, the VFS is required
41835 ** to either truncate or zero the header of the wal-index when the last
41836 ** connection to it closes.  Because the wal-index is transient, it can
41837 ** use an architecture-specific format; it does not have to be cross-platform.
41838 ** Hence, unlike the database and WAL file formats which store all values
41839 ** as big endian, the wal-index can store multi-byte values in the native
41840 ** byte order of the host computer.
41841 **
41842 ** The purpose of the wal-index is to answer this question quickly:  Given
41843 ** a page number P, return the index of the last frame for page P in the WAL,
41844 ** or return NULL if there are no frames for page P in the WAL.
41845 **
41846 ** The wal-index consists of a header region, followed by an one or
41847 ** more index blocks.  
41848 **
41849 ** The wal-index header contains the total number of frames within the WAL
41850 ** in the the mxFrame field.  
41851 **
41852 ** Each index block except for the first contains information on 
41853 ** HASHTABLE_NPAGE frames. The first index block contains information on
41854 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and 
41855 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
41856 ** first index block are the same size as all other index blocks in the
41857 ** wal-index.
41858 **
41859 ** Each index block contains two sections, a page-mapping that contains the
41860 ** database page number associated with each wal frame, and a hash-table 
41861 ** that allows readers to query an index block for a specific page number.
41862 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
41863 ** for the first index block) 32-bit page numbers. The first entry in the 
41864 ** first index-block contains the database page number corresponding to the
41865 ** first frame in the WAL file. The first entry in the second index block
41866 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
41867 ** the log, and so on.
41868 **
41869 ** The last index block in a wal-index usually contains less than the full
41870 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
41871 ** depending on the contents of the WAL file. This does not change the
41872 ** allocated size of the page-mapping array - the page-mapping array merely
41873 ** contains unused entries.
41874 **
41875 ** Even without using the hash table, the last frame for page P
41876 ** can be found by scanning the page-mapping sections of each index block
41877 ** starting with the last index block and moving toward the first, and
41878 ** within each index block, starting at the end and moving toward the
41879 ** beginning.  The first entry that equals P corresponds to the frame
41880 ** holding the content for that page.
41881 **
41882 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
41883 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
41884 ** hash table for each page number in the mapping section, so the hash 
41885 ** table is never more than half full.  The expected number of collisions 
41886 ** prior to finding a match is 1.  Each entry of the hash table is an
41887 ** 1-based index of an entry in the mapping section of the same
41888 ** index block.   Let K be the 1-based index of the largest entry in
41889 ** the mapping section.  (For index blocks other than the last, K will
41890 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
41891 ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
41892 ** contain a value of 0.
41893 **
41894 ** To look for page P in the hash table, first compute a hash iKey on
41895 ** P as follows:
41896 **
41897 **      iKey = (P * 383) % HASHTABLE_NSLOT
41898 **
41899 ** Then start scanning entries of the hash table, starting with iKey
41900 ** (wrapping around to the beginning when the end of the hash table is
41901 ** reached) until an unused hash slot is found. Let the first unused slot
41902 ** be at index iUnused.  (iUnused might be less than iKey if there was
41903 ** wrap-around.) Because the hash table is never more than half full,
41904 ** the search is guaranteed to eventually hit an unused entry.  Let 
41905 ** iMax be the value between iKey and iUnused, closest to iUnused,
41906 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
41907 ** no hash slot such that aHash[i]==p) then page P is not in the
41908 ** current index block.  Otherwise the iMax-th mapping entry of the
41909 ** current index block corresponds to the last entry that references 
41910 ** page P.
41911 **
41912 ** A hash search begins with the last index block and moves toward the
41913 ** first index block, looking for entries corresponding to page P.  On
41914 ** average, only two or three slots in each index block need to be
41915 ** examined in order to either find the last entry for page P, or to
41916 ** establish that no such entry exists in the block.  Each index block
41917 ** holds over 4000 entries.  So two or three index blocks are sufficient
41918 ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
41919 ** comparisons (on average) suffice to either locate a frame in the
41920 ** WAL or to establish that the frame does not exist in the WAL.  This
41921 ** is much faster than scanning the entire 10MB WAL.
41922 **
41923 ** Note that entries are added in order of increasing K.  Hence, one
41924 ** reader might be using some value K0 and a second reader that started
41925 ** at a later time (after additional transactions were added to the WAL
41926 ** and to the wal-index) might be using a different value K1, where K1>K0.
41927 ** Both readers can use the same hash table and mapping section to get
41928 ** the correct result.  There may be entries in the hash table with
41929 ** K>K0 but to the first reader, those entries will appear to be unused
41930 ** slots in the hash table and so the first reader will get an answer as
41931 ** if no values greater than K0 had ever been inserted into the hash table
41932 ** in the first place - which is what reader one wants.  Meanwhile, the
41933 ** second reader using K1 will see additional values that were inserted
41934 ** later, which is exactly what reader two wants.  
41935 **
41936 ** When a rollback occurs, the value of K is decreased. Hash table entries
41937 ** that correspond to frames greater than the new K value are removed
41938 ** from the hash table at this point.
41939 */
41940 #ifndef SQLITE_OMIT_WAL
41941
41942
41943 /*
41944 ** Trace output macros
41945 */
41946 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
41947 SQLITE_PRIVATE int sqlite3WalTrace = 0;
41948 # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
41949 #else
41950 # define WALTRACE(X)
41951 #endif
41952
41953 /*
41954 ** The maximum (and only) versions of the wal and wal-index formats
41955 ** that may be interpreted by this version of SQLite.
41956 **
41957 ** If a client begins recovering a WAL file and finds that (a) the checksum
41958 ** values in the wal-header are correct and (b) the version field is not
41959 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
41960 **
41961 ** Similarly, if a client successfully reads a wal-index header (i.e. the 
41962 ** checksum test is successful) and finds that the version field is not
41963 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
41964 ** returns SQLITE_CANTOPEN.
41965 */
41966 #define WAL_MAX_VERSION      3007000
41967 #define WALINDEX_MAX_VERSION 3007000
41968
41969 /*
41970 ** Indices of various locking bytes.   WAL_NREADER is the number
41971 ** of available reader locks and should be at least 3.
41972 */
41973 #define WAL_WRITE_LOCK         0
41974 #define WAL_ALL_BUT_WRITE      1
41975 #define WAL_CKPT_LOCK          1
41976 #define WAL_RECOVER_LOCK       2
41977 #define WAL_READ_LOCK(I)       (3+(I))
41978 #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
41979
41980
41981 /* Object declarations */
41982 typedef struct WalIndexHdr WalIndexHdr;
41983 typedef struct WalIterator WalIterator;
41984 typedef struct WalCkptInfo WalCkptInfo;
41985
41986
41987 /*
41988 ** The following object holds a copy of the wal-index header content.
41989 **
41990 ** The actual header in the wal-index consists of two copies of this
41991 ** object.
41992 **
41993 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
41994 ** Or it can be 1 to represent a 65536-byte page.  The latter case was
41995 ** added in 3.7.1 when support for 64K pages was added.  
41996 */
41997 struct WalIndexHdr {
41998   u32 iVersion;                   /* Wal-index version */
41999   u32 unused;                     /* Unused (padding) field */
42000   u32 iChange;                    /* Counter incremented each transaction */
42001   u8 isInit;                      /* 1 when initialized */
42002   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
42003   u16 szPage;                     /* Database page size in bytes. 1==64K */
42004   u32 mxFrame;                    /* Index of last valid frame in the WAL */
42005   u32 nPage;                      /* Size of database in pages */
42006   u32 aFrameCksum[2];             /* Checksum of last frame in log */
42007   u32 aSalt[2];                   /* Two salt values copied from WAL header */
42008   u32 aCksum[2];                  /* Checksum over all prior fields */
42009 };
42010
42011 /*
42012 ** A copy of the following object occurs in the wal-index immediately
42013 ** following the second copy of the WalIndexHdr.  This object stores
42014 ** information used by checkpoint.
42015 **
42016 ** nBackfill is the number of frames in the WAL that have been written
42017 ** back into the database. (We call the act of moving content from WAL to
42018 ** database "backfilling".)  The nBackfill number is never greater than
42019 ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
42020 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
42021 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
42022 ** mxFrame back to zero when the WAL is reset.
42023 **
42024 ** There is one entry in aReadMark[] for each reader lock.  If a reader
42025 ** holds read-lock K, then the value in aReadMark[K] is no greater than
42026 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
42027 ** for any aReadMark[] means that entry is unused.  aReadMark[0] is 
42028 ** a special case; its value is never used and it exists as a place-holder
42029 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
42030 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
42031 ** directly from the database.
42032 **
42033 ** The value of aReadMark[K] may only be changed by a thread that
42034 ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
42035 ** aReadMark[K] cannot changed while there is a reader is using that mark
42036 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
42037 **
42038 ** The checkpointer may only transfer frames from WAL to database where
42039 ** the frame numbers are less than or equal to every aReadMark[] that is
42040 ** in use (that is, every aReadMark[j] for which there is a corresponding
42041 ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
42042 ** largest value and will increase an unused aReadMark[] to mxFrame if there
42043 ** is not already an aReadMark[] equal to mxFrame.  The exception to the
42044 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
42045 ** in the WAL has been backfilled into the database) then new readers
42046 ** will choose aReadMark[0] which has value 0 and hence such reader will
42047 ** get all their all content directly from the database file and ignore 
42048 ** the WAL.
42049 **
42050 ** Writers normally append new frames to the end of the WAL.  However,
42051 ** if nBackfill equals mxFrame (meaning that all WAL content has been
42052 ** written back into the database) and if no readers are using the WAL
42053 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
42054 ** the writer will first "reset" the WAL back to the beginning and start
42055 ** writing new content beginning at frame 1.
42056 **
42057 ** We assume that 32-bit loads are atomic and so no locks are needed in
42058 ** order to read from any aReadMark[] entries.
42059 */
42060 struct WalCkptInfo {
42061   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
42062   u32 aReadMark[WAL_NREADER];     /* Reader marks */
42063 };
42064 #define READMARK_NOT_USED  0xffffffff
42065
42066
42067 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
42068 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
42069 ** only support mandatory file-locks, we do not read or write data
42070 ** from the region of the file on which locks are applied.
42071 */
42072 #define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
42073 #define WALINDEX_LOCK_RESERVED 16
42074 #define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
42075
42076 /* Size of header before each frame in wal */
42077 #define WAL_FRAME_HDRSIZE 24
42078
42079 /* Size of write ahead log header, including checksum. */
42080 /* #define WAL_HDRSIZE 24 */
42081 #define WAL_HDRSIZE 32
42082
42083 /* WAL magic value. Either this value, or the same value with the least
42084 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
42085 ** big-endian format in the first 4 bytes of a WAL file.
42086 **
42087 ** If the LSB is set, then the checksums for each frame within the WAL
42088 ** file are calculated by treating all data as an array of 32-bit 
42089 ** big-endian words. Otherwise, they are calculated by interpreting 
42090 ** all data as 32-bit little-endian words.
42091 */
42092 #define WAL_MAGIC 0x377f0682
42093
42094 /*
42095 ** Return the offset of frame iFrame in the write-ahead log file, 
42096 ** assuming a database page size of szPage bytes. The offset returned
42097 ** is to the start of the write-ahead log frame-header.
42098 */
42099 #define walFrameOffset(iFrame, szPage) (                               \
42100   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
42101 )
42102
42103 /*
42104 ** An open write-ahead log file is represented by an instance of the
42105 ** following object.
42106 */
42107 struct Wal {
42108   sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
42109   sqlite3_file *pDbFd;       /* File handle for the database file */
42110   sqlite3_file *pWalFd;      /* File handle for WAL file */
42111   u32 iCallback;             /* Value to pass to log callback (or 0) */
42112   int nWiData;               /* Size of array apWiData */
42113   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
42114   u32 szPage;                /* Database page size */
42115   i16 readLock;              /* Which read lock is being held.  -1 for none */
42116   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
42117   u8 writeLock;              /* True if in a write transaction */
42118   u8 ckptLock;               /* True if holding a checkpoint lock */
42119   u8 readOnly;               /* True if the WAL file is open read-only */
42120   WalIndexHdr hdr;           /* Wal-index header for current transaction */
42121   const char *zWalName;      /* Name of WAL file */
42122   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
42123 #ifdef SQLITE_DEBUG
42124   u8 lockError;              /* True if a locking error has occurred */
42125 #endif
42126 };
42127
42128 /*
42129 ** Candidate values for Wal.exclusiveMode.
42130 */
42131 #define WAL_NORMAL_MODE     0
42132 #define WAL_EXCLUSIVE_MODE  1     
42133 #define WAL_HEAPMEMORY_MODE 2
42134
42135 /*
42136 ** Each page of the wal-index mapping contains a hash-table made up of
42137 ** an array of HASHTABLE_NSLOT elements of the following type.
42138 */
42139 typedef u16 ht_slot;
42140
42141 /*
42142 ** This structure is used to implement an iterator that loops through
42143 ** all frames in the WAL in database page order. Where two or more frames
42144 ** correspond to the same database page, the iterator visits only the 
42145 ** frame most recently written to the WAL (in other words, the frame with
42146 ** the largest index).
42147 **
42148 ** The internals of this structure are only accessed by:
42149 **
42150 **   walIteratorInit() - Create a new iterator,
42151 **   walIteratorNext() - Step an iterator,
42152 **   walIteratorFree() - Free an iterator.
42153 **
42154 ** This functionality is used by the checkpoint code (see walCheckpoint()).
42155 */
42156 struct WalIterator {
42157   int iPrior;                     /* Last result returned from the iterator */
42158   int nSegment;                   /* Number of entries in aSegment[] */
42159   struct WalSegment {
42160     int iNext;                    /* Next slot in aIndex[] not yet returned */
42161     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
42162     u32 *aPgno;                   /* Array of page numbers. */
42163     int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
42164     int iZero;                    /* Frame number associated with aPgno[0] */
42165   } aSegment[1];                  /* One for every 32KB page in the wal-index */
42166 };
42167
42168 /*
42169 ** Define the parameters of the hash tables in the wal-index file. There
42170 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
42171 ** wal-index.
42172 **
42173 ** Changing any of these constants will alter the wal-index format and
42174 ** create incompatibilities.
42175 */
42176 #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
42177 #define HASHTABLE_HASH_1     383                  /* Should be prime */
42178 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
42179
42180 /* 
42181 ** The block of page numbers associated with the first hash-table in a
42182 ** wal-index is smaller than usual. This is so that there is a complete
42183 ** hash-table on each aligned 32KB page of the wal-index.
42184 */
42185 #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
42186
42187 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
42188 #define WALINDEX_PGSZ   (                                         \
42189     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
42190 )
42191
42192 /*
42193 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
42194 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
42195 ** numbered from zero.
42196 **
42197 ** If this call is successful, *ppPage is set to point to the wal-index
42198 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
42199 ** then an SQLite error code is returned and *ppPage is set to 0.
42200 */
42201 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
42202   int rc = SQLITE_OK;
42203
42204   /* Enlarge the pWal->apWiData[] array if required */
42205   if( pWal->nWiData<=iPage ){
42206     int nByte = sizeof(u32*)*(iPage+1);
42207     volatile u32 **apNew;
42208     apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
42209     if( !apNew ){
42210       *ppPage = 0;
42211       return SQLITE_NOMEM;
42212     }
42213     memset((void*)&apNew[pWal->nWiData], 0,
42214            sizeof(u32*)*(iPage+1-pWal->nWiData));
42215     pWal->apWiData = apNew;
42216     pWal->nWiData = iPage+1;
42217   }
42218
42219   /* Request a pointer to the required page from the VFS */
42220   if( pWal->apWiData[iPage]==0 ){
42221     if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
42222       pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
42223       if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
42224     }else{
42225       rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, 
42226           pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
42227       );
42228     }
42229   }
42230
42231   *ppPage = pWal->apWiData[iPage];
42232   assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
42233   return rc;
42234 }
42235
42236 /*
42237 ** Return a pointer to the WalCkptInfo structure in the wal-index.
42238 */
42239 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
42240   assert( pWal->nWiData>0 && pWal->apWiData[0] );
42241   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
42242 }
42243
42244 /*
42245 ** Return a pointer to the WalIndexHdr structure in the wal-index.
42246 */
42247 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
42248   assert( pWal->nWiData>0 && pWal->apWiData[0] );
42249   return (volatile WalIndexHdr*)pWal->apWiData[0];
42250 }
42251
42252 /*
42253 ** The argument to this macro must be of type u32. On a little-endian
42254 ** architecture, it returns the u32 value that results from interpreting
42255 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
42256 ** returns the value that would be produced by intepreting the 4 bytes
42257 ** of the input value as a little-endian integer.
42258 */
42259 #define BYTESWAP32(x) ( \
42260     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
42261   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
42262 )
42263
42264 /*
42265 ** Generate or extend an 8 byte checksum based on the data in 
42266 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
42267 ** initial values of 0 and 0 if aIn==NULL).
42268 **
42269 ** The checksum is written back into aOut[] before returning.
42270 **
42271 ** nByte must be a positive multiple of 8.
42272 */
42273 static void walChecksumBytes(
42274   int nativeCksum, /* True for native byte-order, false for non-native */
42275   u8 *a,           /* Content to be checksummed */
42276   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
42277   const u32 *aIn,  /* Initial checksum value input */
42278   u32 *aOut        /* OUT: Final checksum value output */
42279 ){
42280   u32 s1, s2;
42281   u32 *aData = (u32 *)a;
42282   u32 *aEnd = (u32 *)&a[nByte];
42283
42284   if( aIn ){
42285     s1 = aIn[0];
42286     s2 = aIn[1];
42287   }else{
42288     s1 = s2 = 0;
42289   }
42290
42291   assert( nByte>=8 );
42292   assert( (nByte&0x00000007)==0 );
42293
42294   if( nativeCksum ){
42295     do {
42296       s1 += *aData++ + s2;
42297       s2 += *aData++ + s1;
42298     }while( aData<aEnd );
42299   }else{
42300     do {
42301       s1 += BYTESWAP32(aData[0]) + s2;
42302       s2 += BYTESWAP32(aData[1]) + s1;
42303       aData += 2;
42304     }while( aData<aEnd );
42305   }
42306
42307   aOut[0] = s1;
42308   aOut[1] = s2;
42309 }
42310
42311 static void walShmBarrier(Wal *pWal){
42312   if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
42313     sqlite3OsShmBarrier(pWal->pDbFd);
42314   }
42315 }
42316
42317 /*
42318 ** Write the header information in pWal->hdr into the wal-index.
42319 **
42320 ** The checksum on pWal->hdr is updated before it is written.
42321 */
42322 static void walIndexWriteHdr(Wal *pWal){
42323   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
42324   const int nCksum = offsetof(WalIndexHdr, aCksum);
42325
42326   assert( pWal->writeLock );
42327   pWal->hdr.isInit = 1;
42328   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
42329   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
42330   memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
42331   walShmBarrier(pWal);
42332   memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
42333 }
42334
42335 /*
42336 ** This function encodes a single frame header and writes it to a buffer
42337 ** supplied by the caller. A frame-header is made up of a series of 
42338 ** 4-byte big-endian integers, as follows:
42339 **
42340 **     0: Page number.
42341 **     4: For commit records, the size of the database image in pages 
42342 **        after the commit. For all other records, zero.
42343 **     8: Salt-1 (copied from the wal-header)
42344 **    12: Salt-2 (copied from the wal-header)
42345 **    16: Checksum-1.
42346 **    20: Checksum-2.
42347 */
42348 static void walEncodeFrame(
42349   Wal *pWal,                      /* The write-ahead log */
42350   u32 iPage,                      /* Database page number for frame */
42351   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
42352   u8 *aData,                      /* Pointer to page data */
42353   u8 *aFrame                      /* OUT: Write encoded frame here */
42354 ){
42355   int nativeCksum;                /* True for native byte-order checksums */
42356   u32 *aCksum = pWal->hdr.aFrameCksum;
42357   assert( WAL_FRAME_HDRSIZE==24 );
42358   sqlite3Put4byte(&aFrame[0], iPage);
42359   sqlite3Put4byte(&aFrame[4], nTruncate);
42360   memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
42361
42362   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
42363   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
42364   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
42365
42366   sqlite3Put4byte(&aFrame[16], aCksum[0]);
42367   sqlite3Put4byte(&aFrame[20], aCksum[1]);
42368 }
42369
42370 /*
42371 ** Check to see if the frame with header in aFrame[] and content
42372 ** in aData[] is valid.  If it is a valid frame, fill *piPage and
42373 ** *pnTruncate and return true.  Return if the frame is not valid.
42374 */
42375 static int walDecodeFrame(
42376   Wal *pWal,                      /* The write-ahead log */
42377   u32 *piPage,                    /* OUT: Database page number for frame */
42378   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
42379   u8 *aData,                      /* Pointer to page data (for checksum) */
42380   u8 *aFrame                      /* Frame data */
42381 ){
42382   int nativeCksum;                /* True for native byte-order checksums */
42383   u32 *aCksum = pWal->hdr.aFrameCksum;
42384   u32 pgno;                       /* Page number of the frame */
42385   assert( WAL_FRAME_HDRSIZE==24 );
42386
42387   /* A frame is only valid if the salt values in the frame-header
42388   ** match the salt values in the wal-header. 
42389   */
42390   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
42391     return 0;
42392   }
42393
42394   /* A frame is only valid if the page number is creater than zero.
42395   */
42396   pgno = sqlite3Get4byte(&aFrame[0]);
42397   if( pgno==0 ){
42398     return 0;
42399   }
42400
42401   /* A frame is only valid if a checksum of the WAL header,
42402   ** all prior frams, the first 16 bytes of this frame-header, 
42403   ** and the frame-data matches the checksum in the last 8 
42404   ** bytes of this frame-header.
42405   */
42406   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
42407   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
42408   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
42409   if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) 
42410    || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) 
42411   ){
42412     /* Checksum failed. */
42413     return 0;
42414   }
42415
42416   /* If we reach this point, the frame is valid.  Return the page number
42417   ** and the new database size.
42418   */
42419   *piPage = pgno;
42420   *pnTruncate = sqlite3Get4byte(&aFrame[4]);
42421   return 1;
42422 }
42423
42424
42425 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
42426 /*
42427 ** Names of locks.  This routine is used to provide debugging output and is not
42428 ** a part of an ordinary build.
42429 */
42430 static const char *walLockName(int lockIdx){
42431   if( lockIdx==WAL_WRITE_LOCK ){
42432     return "WRITE-LOCK";
42433   }else if( lockIdx==WAL_CKPT_LOCK ){
42434     return "CKPT-LOCK";
42435   }else if( lockIdx==WAL_RECOVER_LOCK ){
42436     return "RECOVER-LOCK";
42437   }else{
42438     static char zName[15];
42439     sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
42440                      lockIdx-WAL_READ_LOCK(0));
42441     return zName;
42442   }
42443 }
42444 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
42445     
42446
42447 /*
42448 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
42449 ** A lock cannot be moved directly between shared and exclusive - it must go
42450 ** through the unlocked state first.
42451 **
42452 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
42453 */
42454 static int walLockShared(Wal *pWal, int lockIdx){
42455   int rc;
42456   if( pWal->exclusiveMode ) return SQLITE_OK;
42457   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
42458                         SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
42459   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
42460             walLockName(lockIdx), rc ? "failed" : "ok"));
42461   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
42462   return rc;
42463 }
42464 static void walUnlockShared(Wal *pWal, int lockIdx){
42465   if( pWal->exclusiveMode ) return;
42466   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
42467                          SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
42468   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
42469 }
42470 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
42471   int rc;
42472   if( pWal->exclusiveMode ) return SQLITE_OK;
42473   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
42474                         SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
42475   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
42476             walLockName(lockIdx), n, rc ? "failed" : "ok"));
42477   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
42478   return rc;
42479 }
42480 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
42481   if( pWal->exclusiveMode ) return;
42482   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
42483                          SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
42484   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
42485              walLockName(lockIdx), n));
42486 }
42487
42488 /*
42489 ** Compute a hash on a page number.  The resulting hash value must land
42490 ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
42491 ** the hash to the next value in the event of a collision.
42492 */
42493 static int walHash(u32 iPage){
42494   assert( iPage>0 );
42495   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
42496   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
42497 }
42498 static int walNextHash(int iPriorHash){
42499   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
42500 }
42501
42502 /* 
42503 ** Return pointers to the hash table and page number array stored on
42504 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
42505 ** numbered starting from 0.
42506 **
42507 ** Set output variable *paHash to point to the start of the hash table
42508 ** in the wal-index file. Set *piZero to one less than the frame 
42509 ** number of the first frame indexed by this hash table. If a
42510 ** slot in the hash table is set to N, it refers to frame number 
42511 ** (*piZero+N) in the log.
42512 **
42513 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
42514 ** first frame indexed by the hash table, frame (*piZero+1).
42515 */
42516 static int walHashGet(
42517   Wal *pWal,                      /* WAL handle */
42518   int iHash,                      /* Find the iHash'th table */
42519   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
42520   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
42521   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
42522 ){
42523   int rc;                         /* Return code */
42524   volatile u32 *aPgno;
42525
42526   rc = walIndexPage(pWal, iHash, &aPgno);
42527   assert( rc==SQLITE_OK || iHash>0 );
42528
42529   if( rc==SQLITE_OK ){
42530     u32 iZero;
42531     volatile ht_slot *aHash;
42532
42533     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
42534     if( iHash==0 ){
42535       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
42536       iZero = 0;
42537     }else{
42538       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
42539     }
42540   
42541     *paPgno = &aPgno[-1];
42542     *paHash = aHash;
42543     *piZero = iZero;
42544   }
42545   return rc;
42546 }
42547
42548 /*
42549 ** Return the number of the wal-index page that contains the hash-table
42550 ** and page-number array that contain entries corresponding to WAL frame
42551 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages 
42552 ** are numbered starting from 0.
42553 */
42554 static int walFramePage(u32 iFrame){
42555   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
42556   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
42557        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
42558        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
42559        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
42560        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
42561   );
42562   return iHash;
42563 }
42564
42565 /*
42566 ** Return the page number associated with frame iFrame in this WAL.
42567 */
42568 static u32 walFramePgno(Wal *pWal, u32 iFrame){
42569   int iHash = walFramePage(iFrame);
42570   if( iHash==0 ){
42571     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
42572   }
42573   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
42574 }
42575
42576 /*
42577 ** Remove entries from the hash table that point to WAL slots greater
42578 ** than pWal->hdr.mxFrame.
42579 **
42580 ** This function is called whenever pWal->hdr.mxFrame is decreased due
42581 ** to a rollback or savepoint.
42582 **
42583 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
42584 ** updated.  Any later hash tables will be automatically cleared when
42585 ** pWal->hdr.mxFrame advances to the point where those hash tables are
42586 ** actually needed.
42587 */
42588 static void walCleanupHash(Wal *pWal){
42589   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
42590   volatile u32 *aPgno = 0;        /* Page number array for hash table */
42591   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
42592   int iLimit = 0;                 /* Zero values greater than this */
42593   int nByte;                      /* Number of bytes to zero in aPgno[] */
42594   int i;                          /* Used to iterate through aHash[] */
42595
42596   assert( pWal->writeLock );
42597   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
42598   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
42599   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
42600
42601   if( pWal->hdr.mxFrame==0 ) return;
42602
42603   /* Obtain pointers to the hash-table and page-number array containing 
42604   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
42605   ** that the page said hash-table and array reside on is already mapped.
42606   */
42607   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
42608   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
42609   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
42610
42611   /* Zero all hash-table entries that correspond to frame numbers greater
42612   ** than pWal->hdr.mxFrame.
42613   */
42614   iLimit = pWal->hdr.mxFrame - iZero;
42615   assert( iLimit>0 );
42616   for(i=0; i<HASHTABLE_NSLOT; i++){
42617     if( aHash[i]>iLimit ){
42618       aHash[i] = 0;
42619     }
42620   }
42621   
42622   /* Zero the entries in the aPgno array that correspond to frames with
42623   ** frame numbers greater than pWal->hdr.mxFrame. 
42624   */
42625   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
42626   memset((void *)&aPgno[iLimit+1], 0, nByte);
42627
42628 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
42629   /* Verify that the every entry in the mapping region is still reachable
42630   ** via the hash table even after the cleanup.
42631   */
42632   if( iLimit ){
42633     int i;           /* Loop counter */
42634     int iKey;        /* Hash key */
42635     for(i=1; i<=iLimit; i++){
42636       for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
42637         if( aHash[iKey]==i ) break;
42638       }
42639       assert( aHash[iKey]==i );
42640     }
42641   }
42642 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
42643 }
42644
42645
42646 /*
42647 ** Set an entry in the wal-index that will map database page number
42648 ** pPage into WAL frame iFrame.
42649 */
42650 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
42651   int rc;                         /* Return code */
42652   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
42653   volatile u32 *aPgno = 0;        /* Page number array */
42654   volatile ht_slot *aHash = 0;    /* Hash table */
42655
42656   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
42657
42658   /* Assuming the wal-index file was successfully mapped, populate the
42659   ** page number array and hash table entry.
42660   */
42661   if( rc==SQLITE_OK ){
42662     int iKey;                     /* Hash table key */
42663     int idx;                      /* Value to write to hash-table slot */
42664     int nCollide;                 /* Number of hash collisions */
42665
42666     idx = iFrame - iZero;
42667     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
42668     
42669     /* If this is the first entry to be added to this hash-table, zero the
42670     ** entire hash table and aPgno[] array before proceding. 
42671     */
42672     if( idx==1 ){
42673       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
42674       memset((void*)&aPgno[1], 0, nByte);
42675     }
42676
42677     /* If the entry in aPgno[] is already set, then the previous writer
42678     ** must have exited unexpectedly in the middle of a transaction (after
42679     ** writing one or more dirty pages to the WAL to free up memory). 
42680     ** Remove the remnants of that writers uncommitted transaction from 
42681     ** the hash-table before writing any new entries.
42682     */
42683     if( aPgno[idx] ){
42684       walCleanupHash(pWal);
42685       assert( !aPgno[idx] );
42686     }
42687
42688     /* Write the aPgno[] array entry and the hash-table slot. */
42689     nCollide = idx;
42690     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
42691       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
42692     }
42693     aPgno[idx] = iPage;
42694     aHash[iKey] = (ht_slot)idx;
42695
42696 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
42697     /* Verify that the number of entries in the hash table exactly equals
42698     ** the number of entries in the mapping region.
42699     */
42700     {
42701       int i;           /* Loop counter */
42702       int nEntry = 0;  /* Number of entries in the hash table */
42703       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
42704       assert( nEntry==idx );
42705     }
42706
42707     /* Verify that the every entry in the mapping region is reachable
42708     ** via the hash table.  This turns out to be a really, really expensive
42709     ** thing to check, so only do this occasionally - not on every
42710     ** iteration.
42711     */
42712     if( (idx&0x3ff)==0 ){
42713       int i;           /* Loop counter */
42714       for(i=1; i<=idx; i++){
42715         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
42716           if( aHash[iKey]==i ) break;
42717         }
42718         assert( aHash[iKey]==i );
42719       }
42720     }
42721 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
42722   }
42723
42724
42725   return rc;
42726 }
42727
42728
42729 /*
42730 ** Recover the wal-index by reading the write-ahead log file. 
42731 **
42732 ** This routine first tries to establish an exclusive lock on the
42733 ** wal-index to prevent other threads/processes from doing anything
42734 ** with the WAL or wal-index while recovery is running.  The
42735 ** WAL_RECOVER_LOCK is also held so that other threads will know
42736 ** that this thread is running recovery.  If unable to establish
42737 ** the necessary locks, this routine returns SQLITE_BUSY.
42738 */
42739 static int walIndexRecover(Wal *pWal){
42740   int rc;                         /* Return Code */
42741   i64 nSize;                      /* Size of log file */
42742   u32 aFrameCksum[2] = {0, 0};
42743   int iLock;                      /* Lock offset to lock for checkpoint */
42744   int nLock;                      /* Number of locks to hold */
42745
42746   /* Obtain an exclusive lock on all byte in the locking range not already
42747   ** locked by the caller. The caller is guaranteed to have locked the
42748   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
42749   ** If successful, the same bytes that are locked here are unlocked before
42750   ** this function returns.
42751   */
42752   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
42753   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
42754   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
42755   assert( pWal->writeLock );
42756   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
42757   nLock = SQLITE_SHM_NLOCK - iLock;
42758   rc = walLockExclusive(pWal, iLock, nLock);
42759   if( rc ){
42760     return rc;
42761   }
42762   WALTRACE(("WAL%p: recovery begin...\n", pWal));
42763
42764   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
42765
42766   rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
42767   if( rc!=SQLITE_OK ){
42768     goto recovery_error;
42769   }
42770
42771   if( nSize>WAL_HDRSIZE ){
42772     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
42773     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
42774     int szFrame;                  /* Number of bytes in buffer aFrame[] */
42775     u8 *aData;                    /* Pointer to data part of aFrame buffer */
42776     int iFrame;                   /* Index of last frame read */
42777     i64 iOffset;                  /* Next offset to read from log file */
42778     int szPage;                   /* Page size according to the log */
42779     u32 magic;                    /* Magic value read from WAL header */
42780     u32 version;                  /* Magic value read from WAL header */
42781
42782     /* Read in the WAL header. */
42783     rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
42784     if( rc!=SQLITE_OK ){
42785       goto recovery_error;
42786     }
42787
42788     /* If the database page size is not a power of two, or is greater than
42789     ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid 
42790     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
42791     ** WAL file.
42792     */
42793     magic = sqlite3Get4byte(&aBuf[0]);
42794     szPage = sqlite3Get4byte(&aBuf[8]);
42795     if( (magic&0xFFFFFFFE)!=WAL_MAGIC 
42796      || szPage&(szPage-1) 
42797      || szPage>SQLITE_MAX_PAGE_SIZE 
42798      || szPage<512 
42799     ){
42800       goto finished;
42801     }
42802     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
42803     pWal->szPage = szPage;
42804     pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
42805     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
42806
42807     /* Verify that the WAL header checksum is correct */
42808     walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, 
42809         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
42810     );
42811     if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
42812      || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
42813     ){
42814       goto finished;
42815     }
42816
42817     /* Verify that the version number on the WAL format is one that
42818     ** are able to understand */
42819     version = sqlite3Get4byte(&aBuf[4]);
42820     if( version!=WAL_MAX_VERSION ){
42821       rc = SQLITE_CANTOPEN_BKPT;
42822       goto finished;
42823     }
42824
42825     /* Malloc a buffer to read frames into. */
42826     szFrame = szPage + WAL_FRAME_HDRSIZE;
42827     aFrame = (u8 *)sqlite3_malloc(szFrame);
42828     if( !aFrame ){
42829       rc = SQLITE_NOMEM;
42830       goto recovery_error;
42831     }
42832     aData = &aFrame[WAL_FRAME_HDRSIZE];
42833
42834     /* Read all frames from the log file. */
42835     iFrame = 0;
42836     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
42837       u32 pgno;                   /* Database page number for frame */
42838       u32 nTruncate;              /* dbsize field from frame header */
42839       int isValid;                /* True if this frame is valid */
42840
42841       /* Read and decode the next log frame. */
42842       rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
42843       if( rc!=SQLITE_OK ) break;
42844       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
42845       if( !isValid ) break;
42846       rc = walIndexAppend(pWal, ++iFrame, pgno);
42847       if( rc!=SQLITE_OK ) break;
42848
42849       /* If nTruncate is non-zero, this is a commit record. */
42850       if( nTruncate ){
42851         pWal->hdr.mxFrame = iFrame;
42852         pWal->hdr.nPage = nTruncate;
42853         pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
42854         testcase( szPage<=32768 );
42855         testcase( szPage>=65536 );
42856         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
42857         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
42858       }
42859     }
42860
42861     sqlite3_free(aFrame);
42862   }
42863
42864 finished:
42865   if( rc==SQLITE_OK ){
42866     volatile WalCkptInfo *pInfo;
42867     int i;
42868     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
42869     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
42870     walIndexWriteHdr(pWal);
42871
42872     /* Reset the checkpoint-header. This is safe because this thread is 
42873     ** currently holding locks that exclude all other readers, writers and
42874     ** checkpointers.
42875     */
42876     pInfo = walCkptInfo(pWal);
42877     pInfo->nBackfill = 0;
42878     pInfo->aReadMark[0] = 0;
42879     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
42880
42881     /* If more than one frame was recovered from the log file, report an
42882     ** event via sqlite3_log(). This is to help with identifying performance
42883     ** problems caused by applications routinely shutting down without
42884     ** checkpointing the log file.
42885     */
42886     if( pWal->hdr.nPage ){
42887       sqlite3_log(SQLITE_OK, "Recovered %d frames from WAL file %s",
42888           pWal->hdr.nPage, pWal->zWalName
42889       );
42890     }
42891   }
42892
42893 recovery_error:
42894   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
42895   walUnlockExclusive(pWal, iLock, nLock);
42896   return rc;
42897 }
42898
42899 /*
42900 ** Close an open wal-index.
42901 */
42902 static void walIndexClose(Wal *pWal, int isDelete){
42903   if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
42904     int i;
42905     for(i=0; i<pWal->nWiData; i++){
42906       sqlite3_free((void *)pWal->apWiData[i]);
42907       pWal->apWiData[i] = 0;
42908     }
42909   }else{
42910     sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
42911   }
42912 }
42913
42914 /* 
42915 ** Open a connection to the WAL file zWalName. The database file must 
42916 ** already be opened on connection pDbFd. The buffer that zWalName points
42917 ** to must remain valid for the lifetime of the returned Wal* handle.
42918 **
42919 ** A SHARED lock should be held on the database file when this function
42920 ** is called. The purpose of this SHARED lock is to prevent any other
42921 ** client from unlinking the WAL or wal-index file. If another process
42922 ** were to do this just after this client opened one of these files, the
42923 ** system would be badly broken.
42924 **
42925 ** If the log file is successfully opened, SQLITE_OK is returned and 
42926 ** *ppWal is set to point to a new WAL handle. If an error occurs,
42927 ** an SQLite error code is returned and *ppWal is left unmodified.
42928 */
42929 SQLITE_PRIVATE int sqlite3WalOpen(
42930   sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
42931   sqlite3_file *pDbFd,            /* The open database file */
42932   const char *zWalName,           /* Name of the WAL file */
42933   int bNoShm,                     /* True to run in heap-memory mode */
42934   Wal **ppWal                     /* OUT: Allocated Wal handle */
42935 ){
42936   int rc;                         /* Return Code */
42937   Wal *pRet;                      /* Object to allocate and return */
42938   int flags;                      /* Flags passed to OsOpen() */
42939
42940   assert( zWalName && zWalName[0] );
42941   assert( pDbFd );
42942
42943   /* In the amalgamation, the os_unix.c and os_win.c source files come before
42944   ** this source file.  Verify that the #defines of the locking byte offsets
42945   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
42946   */
42947 #ifdef WIN_SHM_BASE
42948   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
42949 #endif
42950 #ifdef UNIX_SHM_BASE
42951   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
42952 #endif
42953
42954
42955   /* Allocate an instance of struct Wal to return. */
42956   *ppWal = 0;
42957   pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
42958   if( !pRet ){
42959     return SQLITE_NOMEM;
42960   }
42961
42962   pRet->pVfs = pVfs;
42963   pRet->pWalFd = (sqlite3_file *)&pRet[1];
42964   pRet->pDbFd = pDbFd;
42965   pRet->readLock = -1;
42966   pRet->zWalName = zWalName;
42967   pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
42968
42969   /* Open file handle on the write-ahead log file. */
42970   flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
42971   rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
42972   if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
42973     pRet->readOnly = 1;
42974   }
42975
42976   if( rc!=SQLITE_OK ){
42977     walIndexClose(pRet, 0);
42978     sqlite3OsClose(pRet->pWalFd);
42979     sqlite3_free(pRet);
42980   }else{
42981     *ppWal = pRet;
42982     WALTRACE(("WAL%d: opened\n", pRet));
42983   }
42984   return rc;
42985 }
42986
42987 /*
42988 ** Find the smallest page number out of all pages held in the WAL that
42989 ** has not been returned by any prior invocation of this method on the
42990 ** same WalIterator object.   Write into *piFrame the frame index where
42991 ** that page was last written into the WAL.  Write into *piPage the page
42992 ** number.
42993 **
42994 ** Return 0 on success.  If there are no pages in the WAL with a page
42995 ** number larger than *piPage, then return 1.
42996 */
42997 static int walIteratorNext(
42998   WalIterator *p,               /* Iterator */
42999   u32 *piPage,                  /* OUT: The page number of the next page */
43000   u32 *piFrame                  /* OUT: Wal frame index of next page */
43001 ){
43002   u32 iMin;                     /* Result pgno must be greater than iMin */
43003   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
43004   int i;                        /* For looping through segments */
43005
43006   iMin = p->iPrior;
43007   assert( iMin<0xffffffff );
43008   for(i=p->nSegment-1; i>=0; i--){
43009     struct WalSegment *pSegment = &p->aSegment[i];
43010     while( pSegment->iNext<pSegment->nEntry ){
43011       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
43012       if( iPg>iMin ){
43013         if( iPg<iRet ){
43014           iRet = iPg;
43015           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
43016         }
43017         break;
43018       }
43019       pSegment->iNext++;
43020     }
43021   }
43022
43023   *piPage = p->iPrior = iRet;
43024   return (iRet==0xFFFFFFFF);
43025 }
43026
43027 /*
43028 ** This function merges two sorted lists into a single sorted list.
43029 **
43030 ** aLeft[] and aRight[] are arrays of indices.  The sort key is
43031 ** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
43032 ** is guaranteed for all J<K:
43033 **
43034 **        aContent[aLeft[J]] < aContent[aLeft[K]]
43035 **        aContent[aRight[J]] < aContent[aRight[K]]
43036 **
43037 ** This routine overwrites aRight[] with a new (probably longer) sequence
43038 ** of indices such that the aRight[] contains every index that appears in
43039 ** either aLeft[] or the old aRight[] and such that the second condition
43040 ** above is still met.
43041 **
43042 ** The aContent[aLeft[X]] values will be unique for all X.  And the
43043 ** aContent[aRight[X]] values will be unique too.  But there might be
43044 ** one or more combinations of X and Y such that
43045 **
43046 **      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
43047 **
43048 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
43049 */
43050 static void walMerge(
43051   const u32 *aContent,            /* Pages in wal - keys for the sort */
43052   ht_slot *aLeft,                 /* IN: Left hand input list */
43053   int nLeft,                      /* IN: Elements in array *paLeft */
43054   ht_slot **paRight,              /* IN/OUT: Right hand input list */
43055   int *pnRight,                   /* IN/OUT: Elements in *paRight */
43056   ht_slot *aTmp                   /* Temporary buffer */
43057 ){
43058   int iLeft = 0;                  /* Current index in aLeft */
43059   int iRight = 0;                 /* Current index in aRight */
43060   int iOut = 0;                   /* Current index in output buffer */
43061   int nRight = *pnRight;
43062   ht_slot *aRight = *paRight;
43063
43064   assert( nLeft>0 && nRight>0 );
43065   while( iRight<nRight || iLeft<nLeft ){
43066     ht_slot logpage;
43067     Pgno dbpage;
43068
43069     if( (iLeft<nLeft) 
43070      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
43071     ){
43072       logpage = aLeft[iLeft++];
43073     }else{
43074       logpage = aRight[iRight++];
43075     }
43076     dbpage = aContent[logpage];
43077
43078     aTmp[iOut++] = logpage;
43079     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
43080
43081     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
43082     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
43083   }
43084
43085   *paRight = aLeft;
43086   *pnRight = iOut;
43087   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
43088 }
43089
43090 /*
43091 ** Sort the elements in list aList using aContent[] as the sort key.
43092 ** Remove elements with duplicate keys, preferring to keep the
43093 ** larger aList[] values.
43094 **
43095 ** The aList[] entries are indices into aContent[].  The values in
43096 ** aList[] are to be sorted so that for all J<K:
43097 **
43098 **      aContent[aList[J]] < aContent[aList[K]]
43099 **
43100 ** For any X and Y such that
43101 **
43102 **      aContent[aList[X]] == aContent[aList[Y]]
43103 **
43104 ** Keep the larger of the two values aList[X] and aList[Y] and discard
43105 ** the smaller.
43106 */
43107 static void walMergesort(
43108   const u32 *aContent,            /* Pages in wal */
43109   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
43110   ht_slot *aList,                 /* IN/OUT: List to sort */
43111   int *pnList                     /* IN/OUT: Number of elements in aList[] */
43112 ){
43113   struct Sublist {
43114     int nList;                    /* Number of elements in aList */
43115     ht_slot *aList;               /* Pointer to sub-list content */
43116   };
43117
43118   const int nList = *pnList;      /* Size of input list */
43119   int nMerge = 0;                 /* Number of elements in list aMerge */
43120   ht_slot *aMerge = 0;            /* List to be merged */
43121   int iList;                      /* Index into input list */
43122   int iSub = 0;                   /* Index into aSub array */
43123   struct Sublist aSub[13];        /* Array of sub-lists */
43124
43125   memset(aSub, 0, sizeof(aSub));
43126   assert( nList<=HASHTABLE_NPAGE && nList>0 );
43127   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
43128
43129   for(iList=0; iList<nList; iList++){
43130     nMerge = 1;
43131     aMerge = &aList[iList];
43132     for(iSub=0; iList & (1<<iSub); iSub++){
43133       struct Sublist *p = &aSub[iSub];
43134       assert( p->aList && p->nList<=(1<<iSub) );
43135       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
43136       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
43137     }
43138     aSub[iSub].aList = aMerge;
43139     aSub[iSub].nList = nMerge;
43140   }
43141
43142   for(iSub++; iSub<ArraySize(aSub); iSub++){
43143     if( nList & (1<<iSub) ){
43144       struct Sublist *p = &aSub[iSub];
43145       assert( p->nList<=(1<<iSub) );
43146       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
43147       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
43148     }
43149   }
43150   assert( aMerge==aList );
43151   *pnList = nMerge;
43152
43153 #ifdef SQLITE_DEBUG
43154   {
43155     int i;
43156     for(i=1; i<*pnList; i++){
43157       assert( aContent[aList[i]] > aContent[aList[i-1]] );
43158     }
43159   }
43160 #endif
43161 }
43162
43163 /* 
43164 ** Free an iterator allocated by walIteratorInit().
43165 */
43166 static void walIteratorFree(WalIterator *p){
43167   sqlite3ScratchFree(p);
43168 }
43169
43170 /*
43171 ** Construct a WalInterator object that can be used to loop over all 
43172 ** pages in the WAL in ascending order. The caller must hold the checkpoint
43173 ** lock.
43174 **
43175 ** On success, make *pp point to the newly allocated WalInterator object
43176 ** return SQLITE_OK. Otherwise, return an error code. If this routine
43177 ** returns an error, the value of *pp is undefined.
43178 **
43179 ** The calling routine should invoke walIteratorFree() to destroy the
43180 ** WalIterator object when it has finished with it.
43181 */
43182 static int walIteratorInit(Wal *pWal, WalIterator **pp){
43183   WalIterator *p;                 /* Return value */
43184   int nSegment;                   /* Number of segments to merge */
43185   u32 iLast;                      /* Last frame in log */
43186   int nByte;                      /* Number of bytes to allocate */
43187   int i;                          /* Iterator variable */
43188   ht_slot *aTmp;                  /* Temp space used by merge-sort */
43189   int rc = SQLITE_OK;             /* Return Code */
43190
43191   /* This routine only runs while holding the checkpoint lock. And
43192   ** it only runs if there is actually content in the log (mxFrame>0).
43193   */
43194   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
43195   iLast = pWal->hdr.mxFrame;
43196
43197   /* Allocate space for the WalIterator object. */
43198   nSegment = walFramePage(iLast) + 1;
43199   nByte = sizeof(WalIterator) 
43200         + (nSegment-1)*sizeof(struct WalSegment)
43201         + iLast*sizeof(ht_slot);
43202   p = (WalIterator *)sqlite3ScratchMalloc(nByte);
43203   if( !p ){
43204     return SQLITE_NOMEM;
43205   }
43206   memset(p, 0, nByte);
43207   p->nSegment = nSegment;
43208
43209   /* Allocate temporary space used by the merge-sort routine. This block
43210   ** of memory will be freed before this function returns.
43211   */
43212   aTmp = (ht_slot *)sqlite3ScratchMalloc(
43213       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
43214   );
43215   if( !aTmp ){
43216     rc = SQLITE_NOMEM;
43217   }
43218
43219   for(i=0; rc==SQLITE_OK && i<nSegment; i++){
43220     volatile ht_slot *aHash;
43221     u32 iZero;
43222     volatile u32 *aPgno;
43223
43224     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
43225     if( rc==SQLITE_OK ){
43226       int j;                      /* Counter variable */
43227       int nEntry;                 /* Number of entries in this segment */
43228       ht_slot *aIndex;            /* Sorted index for this segment */
43229
43230       aPgno++;
43231       if( (i+1)==nSegment ){
43232         nEntry = (int)(iLast - iZero);
43233       }else{
43234         nEntry = (int)((u32*)aHash - (u32*)aPgno);
43235       }
43236       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
43237       iZero++;
43238   
43239       for(j=0; j<nEntry; j++){
43240         aIndex[j] = (ht_slot)j;
43241       }
43242       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
43243       p->aSegment[i].iZero = iZero;
43244       p->aSegment[i].nEntry = nEntry;
43245       p->aSegment[i].aIndex = aIndex;
43246       p->aSegment[i].aPgno = (u32 *)aPgno;
43247     }
43248   }
43249   sqlite3ScratchFree(aTmp);
43250
43251   if( rc!=SQLITE_OK ){
43252     walIteratorFree(p);
43253   }
43254   *pp = p;
43255   return rc;
43256 }
43257
43258 /*
43259 ** Copy as much content as we can from the WAL back into the database file
43260 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
43261 **
43262 ** The amount of information copies from WAL to database might be limited
43263 ** by active readers.  This routine will never overwrite a database page
43264 ** that a concurrent reader might be using.
43265 **
43266 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
43267 ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if 
43268 ** checkpoints are always run by a background thread or background 
43269 ** process, foreground threads will never block on a lengthy fsync call.
43270 **
43271 ** Fsync is called on the WAL before writing content out of the WAL and
43272 ** into the database.  This ensures that if the new content is persistent
43273 ** in the WAL and can be recovered following a power-loss or hard reset.
43274 **
43275 ** Fsync is also called on the database file if (and only if) the entire
43276 ** WAL content is copied into the database file.  This second fsync makes
43277 ** it safe to delete the WAL since the new content will persist in the
43278 ** database file.
43279 **
43280 ** This routine uses and updates the nBackfill field of the wal-index header.
43281 ** This is the only routine tha will increase the value of nBackfill.  
43282 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
43283 ** its value.)
43284 **
43285 ** The caller must be holding sufficient locks to ensure that no other
43286 ** checkpoint is running (in any other thread or process) at the same
43287 ** time.
43288 */
43289 static int walCheckpoint(
43290   Wal *pWal,                      /* Wal connection */
43291   int sync_flags,                 /* Flags for OsSync() (or 0) */
43292   int nBuf,                       /* Size of zBuf in bytes */
43293   u8 *zBuf                        /* Temporary buffer to use */
43294 ){
43295   int rc;                         /* Return code */
43296   int szPage;                     /* Database page-size */
43297   WalIterator *pIter = 0;         /* Wal iterator context */
43298   u32 iDbpage = 0;                /* Next database page to write */
43299   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
43300   u32 mxSafeFrame;                /* Max frame that can be backfilled */
43301   u32 mxPage;                     /* Max database page to write */
43302   int i;                          /* Loop counter */
43303   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
43304
43305   szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
43306   testcase( szPage<=32768 );
43307   testcase( szPage>=65536 );
43308   pInfo = walCkptInfo(pWal);
43309   if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
43310
43311   /* Allocate the iterator */
43312   rc = walIteratorInit(pWal, &pIter);
43313   if( rc!=SQLITE_OK ){
43314     return rc;
43315   }
43316   assert( pIter );
43317
43318   /*** TODO:  Move this test out to the caller.  Make it an assert() here ***/
43319   if( szPage!=nBuf ){
43320     rc = SQLITE_CORRUPT_BKPT;
43321     goto walcheckpoint_out;
43322   }
43323
43324   /* Compute in mxSafeFrame the index of the last frame of the WAL that is
43325   ** safe to write into the database.  Frames beyond mxSafeFrame might
43326   ** overwrite database pages that are in use by active readers and thus
43327   ** cannot be backfilled from the WAL.
43328   */
43329   mxSafeFrame = pWal->hdr.mxFrame;
43330   mxPage = pWal->hdr.nPage;
43331   for(i=1; i<WAL_NREADER; i++){
43332     u32 y = pInfo->aReadMark[i];
43333     if( mxSafeFrame>=y ){
43334       assert( y<=pWal->hdr.mxFrame );
43335       rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
43336       if( rc==SQLITE_OK ){
43337         pInfo->aReadMark[i] = READMARK_NOT_USED;
43338         walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
43339       }else if( rc==SQLITE_BUSY ){
43340         mxSafeFrame = y;
43341       }else{
43342         goto walcheckpoint_out;
43343       }
43344     }
43345   }
43346
43347   if( pInfo->nBackfill<mxSafeFrame
43348    && (rc = walLockExclusive(pWal, WAL_READ_LOCK(0), 1))==SQLITE_OK
43349   ){
43350     i64 nSize;                    /* Current size of database file */
43351     u32 nBackfill = pInfo->nBackfill;
43352
43353     /* Sync the WAL to disk */
43354     if( sync_flags ){
43355       rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
43356     }
43357
43358     /* If the database file may grow as a result of this checkpoint, hint
43359     ** about the eventual size of the db file to the VFS layer. 
43360     */
43361     if( rc==SQLITE_OK ){
43362       i64 nReq = ((i64)mxPage * szPage);
43363       rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
43364       if( rc==SQLITE_OK && nSize<nReq ){
43365         sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
43366       }
43367     }
43368
43369     /* Iterate through the contents of the WAL, copying data to the db file. */
43370     while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
43371       i64 iOffset;
43372       assert( walFramePgno(pWal, iFrame)==iDbpage );
43373       if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
43374       iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
43375       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
43376       rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
43377       if( rc!=SQLITE_OK ) break;
43378       iOffset = (iDbpage-1)*(i64)szPage;
43379       testcase( IS_BIG_INT(iOffset) );
43380       rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
43381       if( rc!=SQLITE_OK ) break;
43382     }
43383
43384     /* If work was actually accomplished... */
43385     if( rc==SQLITE_OK ){
43386       if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
43387         i64 szDb = pWal->hdr.nPage*(i64)szPage;
43388         testcase( IS_BIG_INT(szDb) );
43389         rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
43390         if( rc==SQLITE_OK && sync_flags ){
43391           rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
43392         }
43393       }
43394       if( rc==SQLITE_OK ){
43395         pInfo->nBackfill = mxSafeFrame;
43396       }
43397     }
43398
43399     /* Release the reader lock held while backfilling */
43400     walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
43401   }else if( rc==SQLITE_BUSY ){
43402     /* Reset the return code so as not to report a checkpoint failure
43403     ** just because active readers prevent any backfill.
43404     */
43405     rc = SQLITE_OK;
43406   }
43407
43408  walcheckpoint_out:
43409   walIteratorFree(pIter);
43410   return rc;
43411 }
43412
43413 /*
43414 ** Close a connection to a log file.
43415 */
43416 SQLITE_PRIVATE int sqlite3WalClose(
43417   Wal *pWal,                      /* Wal to close */
43418   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
43419   int nBuf,
43420   u8 *zBuf                        /* Buffer of at least nBuf bytes */
43421 ){
43422   int rc = SQLITE_OK;
43423   if( pWal ){
43424     int isDelete = 0;             /* True to unlink wal and wal-index files */
43425
43426     /* If an EXCLUSIVE lock can be obtained on the database file (using the
43427     ** ordinary, rollback-mode locking methods, this guarantees that the
43428     ** connection associated with this log file is the only connection to
43429     ** the database. In this case checkpoint the database and unlink both
43430     ** the wal and wal-index files.
43431     **
43432     ** The EXCLUSIVE lock is not released before returning.
43433     */
43434     rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
43435     if( rc==SQLITE_OK ){
43436       if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
43437         pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
43438       }
43439       rc = sqlite3WalCheckpoint(pWal, sync_flags, nBuf, zBuf);
43440       if( rc==SQLITE_OK ){
43441         isDelete = 1;
43442       }
43443     }
43444
43445     walIndexClose(pWal, isDelete);
43446     sqlite3OsClose(pWal->pWalFd);
43447     if( isDelete ){
43448       sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
43449     }
43450     WALTRACE(("WAL%p: closed\n", pWal));
43451     sqlite3_free((void *)pWal->apWiData);
43452     sqlite3_free(pWal);
43453   }
43454   return rc;
43455 }
43456
43457 /*
43458 ** Try to read the wal-index header.  Return 0 on success and 1 if
43459 ** there is a problem.
43460 **
43461 ** The wal-index is in shared memory.  Another thread or process might
43462 ** be writing the header at the same time this procedure is trying to
43463 ** read it, which might result in inconsistency.  A dirty read is detected
43464 ** by verifying that both copies of the header are the same and also by
43465 ** a checksum on the header.
43466 **
43467 ** If and only if the read is consistent and the header is different from
43468 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
43469 ** and *pChanged is set to 1.
43470 **
43471 ** If the checksum cannot be verified return non-zero. If the header
43472 ** is read successfully and the checksum verified, return zero.
43473 */
43474 static int walIndexTryHdr(Wal *pWal, int *pChanged){
43475   u32 aCksum[2];                  /* Checksum on the header content */
43476   WalIndexHdr h1, h2;             /* Two copies of the header content */
43477   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
43478
43479   /* The first page of the wal-index must be mapped at this point. */
43480   assert( pWal->nWiData>0 && pWal->apWiData[0] );
43481
43482   /* Read the header. This might happen concurrently with a write to the
43483   ** same area of shared memory on a different CPU in a SMP,
43484   ** meaning it is possible that an inconsistent snapshot is read
43485   ** from the file. If this happens, return non-zero.
43486   **
43487   ** There are two copies of the header at the beginning of the wal-index.
43488   ** When reading, read [0] first then [1].  Writes are in the reverse order.
43489   ** Memory barriers are used to prevent the compiler or the hardware from
43490   ** reordering the reads and writes.
43491   */
43492   aHdr = walIndexHdr(pWal);
43493   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
43494   walShmBarrier(pWal);
43495   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
43496
43497   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
43498     return 1;   /* Dirty read */
43499   }  
43500   if( h1.isInit==0 ){
43501     return 1;   /* Malformed header - probably all zeros */
43502   }
43503   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
43504   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
43505     return 1;   /* Checksum does not match */
43506   }
43507
43508   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
43509     *pChanged = 1;
43510     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
43511     pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
43512     testcase( pWal->szPage<=32768 );
43513     testcase( pWal->szPage>=65536 );
43514   }
43515
43516   /* The header was successfully read. Return zero. */
43517   return 0;
43518 }
43519
43520 /*
43521 ** Read the wal-index header from the wal-index and into pWal->hdr.
43522 ** If the wal-header appears to be corrupt, try to reconstruct the
43523 ** wal-index from the WAL before returning.
43524 **
43525 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
43526 ** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
43527 ** to 0.
43528 **
43529 ** If the wal-index header is successfully read, return SQLITE_OK. 
43530 ** Otherwise an SQLite error code.
43531 */
43532 static int walIndexReadHdr(Wal *pWal, int *pChanged){
43533   int rc;                         /* Return code */
43534   int badHdr;                     /* True if a header read failed */
43535   volatile u32 *page0;            /* Chunk of wal-index containing header */
43536
43537   /* Ensure that page 0 of the wal-index (the page that contains the 
43538   ** wal-index header) is mapped. Return early if an error occurs here.
43539   */
43540   assert( pChanged );
43541   rc = walIndexPage(pWal, 0, &page0);
43542   if( rc!=SQLITE_OK ){
43543     return rc;
43544   };
43545   assert( page0 || pWal->writeLock==0 );
43546
43547   /* If the first page of the wal-index has been mapped, try to read the
43548   ** wal-index header immediately, without holding any lock. This usually
43549   ** works, but may fail if the wal-index header is corrupt or currently 
43550   ** being modified by another thread or process.
43551   */
43552   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
43553
43554   /* If the first attempt failed, it might have been due to a race
43555   ** with a writer.  So get a WRITE lock and try again.
43556   */
43557   assert( badHdr==0 || pWal->writeLock==0 );
43558   if( badHdr && SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
43559     pWal->writeLock = 1;
43560     if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
43561       badHdr = walIndexTryHdr(pWal, pChanged);
43562       if( badHdr ){
43563         /* If the wal-index header is still malformed even while holding
43564         ** a WRITE lock, it can only mean that the header is corrupted and
43565         ** needs to be reconstructed.  So run recovery to do exactly that.
43566         */
43567         rc = walIndexRecover(pWal);
43568         *pChanged = 1;
43569       }
43570     }
43571     pWal->writeLock = 0;
43572     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
43573   }
43574
43575   /* If the header is read successfully, check the version number to make
43576   ** sure the wal-index was not constructed with some future format that
43577   ** this version of SQLite cannot understand.
43578   */
43579   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
43580     rc = SQLITE_CANTOPEN_BKPT;
43581   }
43582
43583   return rc;
43584 }
43585
43586 /*
43587 ** This is the value that walTryBeginRead returns when it needs to
43588 ** be retried.
43589 */
43590 #define WAL_RETRY  (-1)
43591
43592 /*
43593 ** Attempt to start a read transaction.  This might fail due to a race or
43594 ** other transient condition.  When that happens, it returns WAL_RETRY to
43595 ** indicate to the caller that it is safe to retry immediately.
43596 **
43597 ** On success return SQLITE_OK.  On a permanent failure (such an
43598 ** I/O error or an SQLITE_BUSY because another process is running
43599 ** recovery) return a positive error code.
43600 **
43601 ** The useWal parameter is true to force the use of the WAL and disable
43602 ** the case where the WAL is bypassed because it has been completely
43603 ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr() 
43604 ** to make a copy of the wal-index header into pWal->hdr.  If the 
43605 ** wal-index header has changed, *pChanged is set to 1 (as an indication 
43606 ** to the caller that the local paget cache is obsolete and needs to be 
43607 ** flushed.)  When useWal==1, the wal-index header is assumed to already
43608 ** be loaded and the pChanged parameter is unused.
43609 **
43610 ** The caller must set the cnt parameter to the number of prior calls to
43611 ** this routine during the current read attempt that returned WAL_RETRY.
43612 ** This routine will start taking more aggressive measures to clear the
43613 ** race conditions after multiple WAL_RETRY returns, and after an excessive
43614 ** number of errors will ultimately return SQLITE_PROTOCOL.  The
43615 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
43616 ** and is not honoring the locking protocol.  There is a vanishingly small
43617 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
43618 ** bad luck when there is lots of contention for the wal-index, but that
43619 ** possibility is so small that it can be safely neglected, we believe.
43620 **
43621 ** On success, this routine obtains a read lock on 
43622 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
43623 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
43624 ** that means the Wal does not hold any read lock.  The reader must not
43625 ** access any database page that is modified by a WAL frame up to and
43626 ** including frame number aReadMark[pWal->readLock].  The reader will
43627 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
43628 ** Or if pWal->readLock==0, then the reader will ignore the WAL
43629 ** completely and get all content directly from the database file.
43630 ** If the useWal parameter is 1 then the WAL will never be ignored and
43631 ** this routine will always set pWal->readLock>0 on success.
43632 ** When the read transaction is completed, the caller must release the
43633 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
43634 **
43635 ** This routine uses the nBackfill and aReadMark[] fields of the header
43636 ** to select a particular WAL_READ_LOCK() that strives to let the
43637 ** checkpoint process do as much work as possible.  This routine might
43638 ** update values of the aReadMark[] array in the header, but if it does
43639 ** so it takes care to hold an exclusive lock on the corresponding
43640 ** WAL_READ_LOCK() while changing values.
43641 */
43642 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
43643   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
43644   u32 mxReadMark;                 /* Largest aReadMark[] value */
43645   int mxI;                        /* Index of largest aReadMark[] value */
43646   int i;                          /* Loop counter */
43647   int rc = SQLITE_OK;             /* Return code  */
43648
43649   assert( pWal->readLock<0 );     /* Not currently locked */
43650
43651   /* Take steps to avoid spinning forever if there is a protocol error. */
43652   if( cnt>5 ){
43653     if( cnt>100 ) return SQLITE_PROTOCOL;
43654     sqlite3OsSleep(pWal->pVfs, 1);
43655   }
43656
43657   if( !useWal ){
43658     rc = walIndexReadHdr(pWal, pChanged);
43659     if( rc==SQLITE_BUSY ){
43660       /* If there is not a recovery running in another thread or process
43661       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
43662       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
43663       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
43664       ** would be technically correct.  But the race is benign since with
43665       ** WAL_RETRY this routine will be called again and will probably be
43666       ** right on the second iteration.
43667       */
43668       if( pWal->apWiData[0]==0 ){
43669         /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
43670         ** We assume this is a transient condition, so return WAL_RETRY. The
43671         ** xShmMap() implementation used by the default unix and win32 VFS 
43672         ** modules may return SQLITE_BUSY due to a race condition in the 
43673         ** code that determines whether or not the shared-memory region 
43674         ** must be zeroed before the requested page is returned.
43675         */
43676         rc = WAL_RETRY;
43677       }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
43678         walUnlockShared(pWal, WAL_RECOVER_LOCK);
43679         rc = WAL_RETRY;
43680       }else if( rc==SQLITE_BUSY ){
43681         rc = SQLITE_BUSY_RECOVERY;
43682       }
43683     }
43684     if( rc!=SQLITE_OK ){
43685       return rc;
43686     }
43687   }
43688
43689   pInfo = walCkptInfo(pWal);
43690   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
43691     /* The WAL has been completely backfilled (or it is empty).
43692     ** and can be safely ignored.
43693     */
43694     rc = walLockShared(pWal, WAL_READ_LOCK(0));
43695     walShmBarrier(pWal);
43696     if( rc==SQLITE_OK ){
43697       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
43698         /* It is not safe to allow the reader to continue here if frames
43699         ** may have been appended to the log before READ_LOCK(0) was obtained.
43700         ** When holding READ_LOCK(0), the reader ignores the entire log file,
43701         ** which implies that the database file contains a trustworthy
43702         ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
43703         ** happening, this is usually correct.
43704         **
43705         ** However, if frames have been appended to the log (or if the log 
43706         ** is wrapped and written for that matter) before the READ_LOCK(0)
43707         ** is obtained, that is not necessarily true. A checkpointer may
43708         ** have started to backfill the appended frames but crashed before
43709         ** it finished. Leaving a corrupt image in the database file.
43710         */
43711         walUnlockShared(pWal, WAL_READ_LOCK(0));
43712         return WAL_RETRY;
43713       }
43714       pWal->readLock = 0;
43715       return SQLITE_OK;
43716     }else if( rc!=SQLITE_BUSY ){
43717       return rc;
43718     }
43719   }
43720
43721   /* If we get this far, it means that the reader will want to use
43722   ** the WAL to get at content from recent commits.  The job now is
43723   ** to select one of the aReadMark[] entries that is closest to
43724   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
43725   */
43726   mxReadMark = 0;
43727   mxI = 0;
43728   for(i=1; i<WAL_NREADER; i++){
43729     u32 thisMark = pInfo->aReadMark[i];
43730     if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
43731       assert( thisMark!=READMARK_NOT_USED );
43732       mxReadMark = thisMark;
43733       mxI = i;
43734     }
43735   }
43736   if( mxI==0 ){
43737     /* If we get here, it means that all of the aReadMark[] entries between
43738     ** 1 and WAL_NREADER-1 are zero.  Try to initialize aReadMark[1] to
43739     ** be mxFrame, then retry.
43740     */
43741     rc = walLockExclusive(pWal, WAL_READ_LOCK(1), 1);
43742     if( rc==SQLITE_OK ){
43743       pInfo->aReadMark[1] = pWal->hdr.mxFrame;
43744       walUnlockExclusive(pWal, WAL_READ_LOCK(1), 1);
43745       rc = WAL_RETRY;
43746     }else if( rc==SQLITE_BUSY ){
43747       rc = WAL_RETRY;
43748     }
43749     return rc;
43750   }else{
43751     if( mxReadMark < pWal->hdr.mxFrame ){
43752       for(i=1; i<WAL_NREADER; i++){
43753         rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
43754         if( rc==SQLITE_OK ){
43755           mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
43756           mxI = i;
43757           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
43758           break;
43759         }else if( rc!=SQLITE_BUSY ){
43760           return rc;
43761         }
43762       }
43763     }
43764
43765     rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
43766     if( rc ){
43767       return rc==SQLITE_BUSY ? WAL_RETRY : rc;
43768     }
43769     /* Now that the read-lock has been obtained, check that neither the
43770     ** value in the aReadMark[] array or the contents of the wal-index
43771     ** header have changed.
43772     **
43773     ** It is necessary to check that the wal-index header did not change
43774     ** between the time it was read and when the shared-lock was obtained
43775     ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
43776     ** that the log file may have been wrapped by a writer, or that frames
43777     ** that occur later in the log than pWal->hdr.mxFrame may have been
43778     ** copied into the database by a checkpointer. If either of these things
43779     ** happened, then reading the database with the current value of
43780     ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
43781     ** instead.
43782     **
43783     ** This does not guarantee that the copy of the wal-index header is up to
43784     ** date before proceeding. That would not be possible without somehow
43785     ** blocking writers. It only guarantees that a dangerous checkpoint or 
43786     ** log-wrap (either of which would require an exclusive lock on
43787     ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
43788     */
43789     walShmBarrier(pWal);
43790     if( pInfo->aReadMark[mxI]!=mxReadMark
43791      || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
43792     ){
43793       walUnlockShared(pWal, WAL_READ_LOCK(mxI));
43794       return WAL_RETRY;
43795     }else{
43796       assert( mxReadMark<=pWal->hdr.mxFrame );
43797       pWal->readLock = (i16)mxI;
43798     }
43799   }
43800   return rc;
43801 }
43802
43803 /*
43804 ** Begin a read transaction on the database.
43805 **
43806 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
43807 ** it takes a snapshot of the state of the WAL and wal-index for the current
43808 ** instant in time.  The current thread will continue to use this snapshot.
43809 ** Other threads might append new content to the WAL and wal-index but
43810 ** that extra content is ignored by the current thread.
43811 **
43812 ** If the database contents have changes since the previous read
43813 ** transaction, then *pChanged is set to 1 before returning.  The
43814 ** Pager layer will use this to know that is cache is stale and
43815 ** needs to be flushed.
43816 */
43817 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
43818   int rc;                         /* Return code */
43819   int cnt = 0;                    /* Number of TryBeginRead attempts */
43820
43821   do{
43822     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
43823   }while( rc==WAL_RETRY );
43824   return rc;
43825 }
43826
43827 /*
43828 ** Finish with a read transaction.  All this does is release the
43829 ** read-lock.
43830 */
43831 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
43832   sqlite3WalEndWriteTransaction(pWal);
43833   if( pWal->readLock>=0 ){
43834     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
43835     pWal->readLock = -1;
43836   }
43837 }
43838
43839 /*
43840 ** Read a page from the WAL, if it is present in the WAL and if the 
43841 ** current read transaction is configured to use the WAL.  
43842 **
43843 ** The *pInWal is set to 1 if the requested page is in the WAL and
43844 ** has been loaded.  Or *pInWal is set to 0 if the page was not in 
43845 ** the WAL and needs to be read out of the database.
43846 */
43847 SQLITE_PRIVATE int sqlite3WalRead(
43848   Wal *pWal,                      /* WAL handle */
43849   Pgno pgno,                      /* Database page number to read data for */
43850   int *pInWal,                    /* OUT: True if data is read from WAL */
43851   int nOut,                       /* Size of buffer pOut in bytes */
43852   u8 *pOut                        /* Buffer to write page data to */
43853 ){
43854   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
43855   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
43856   int iHash;                      /* Used to loop through N hash tables */
43857
43858   /* This routine is only be called from within a read transaction. */
43859   assert( pWal->readLock>=0 || pWal->lockError );
43860
43861   /* If the "last page" field of the wal-index header snapshot is 0, then
43862   ** no data will be read from the wal under any circumstances. Return early
43863   ** in this case as an optimization.  Likewise, if pWal->readLock==0, 
43864   ** then the WAL is ignored by the reader so return early, as if the 
43865   ** WAL were empty.
43866   */
43867   if( iLast==0 || pWal->readLock==0 ){
43868     *pInWal = 0;
43869     return SQLITE_OK;
43870   }
43871
43872   /* Search the hash table or tables for an entry matching page number
43873   ** pgno. Each iteration of the following for() loop searches one
43874   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
43875   **
43876   ** This code might run concurrently to the code in walIndexAppend()
43877   ** that adds entries to the wal-index (and possibly to this hash 
43878   ** table). This means the value just read from the hash 
43879   ** slot (aHash[iKey]) may have been added before or after the 
43880   ** current read transaction was opened. Values added after the
43881   ** read transaction was opened may have been written incorrectly -
43882   ** i.e. these slots may contain garbage data. However, we assume
43883   ** that any slots written before the current read transaction was
43884   ** opened remain unmodified.
43885   **
43886   ** For the reasons above, the if(...) condition featured in the inner
43887   ** loop of the following block is more stringent that would be required 
43888   ** if we had exclusive access to the hash-table:
43889   **
43890   **   (aPgno[iFrame]==pgno): 
43891   **     This condition filters out normal hash-table collisions.
43892   **
43893   **   (iFrame<=iLast): 
43894   **     This condition filters out entries that were added to the hash
43895   **     table after the current read-transaction had started.
43896   */
43897   for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
43898     volatile ht_slot *aHash;      /* Pointer to hash table */
43899     volatile u32 *aPgno;          /* Pointer to array of page numbers */
43900     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
43901     int iKey;                     /* Hash slot index */
43902     int nCollide;                 /* Number of hash collisions remaining */
43903     int rc;                       /* Error code */
43904
43905     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
43906     if( rc!=SQLITE_OK ){
43907       return rc;
43908     }
43909     nCollide = HASHTABLE_NSLOT;
43910     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
43911       u32 iFrame = aHash[iKey] + iZero;
43912       if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
43913         assert( iFrame>iRead );
43914         iRead = iFrame;
43915       }
43916       if( (nCollide--)==0 ){
43917         return SQLITE_CORRUPT_BKPT;
43918       }
43919     }
43920   }
43921
43922 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
43923   /* If expensive assert() statements are available, do a linear search
43924   ** of the wal-index file content. Make sure the results agree with the
43925   ** result obtained using the hash indexes above.  */
43926   {
43927     u32 iRead2 = 0;
43928     u32 iTest;
43929     for(iTest=iLast; iTest>0; iTest--){
43930       if( walFramePgno(pWal, iTest)==pgno ){
43931         iRead2 = iTest;
43932         break;
43933       }
43934     }
43935     assert( iRead==iRead2 );
43936   }
43937 #endif
43938
43939   /* If iRead is non-zero, then it is the log frame number that contains the
43940   ** required page. Read and return data from the log file.
43941   */
43942   if( iRead ){
43943     int sz;
43944     i64 iOffset;
43945     sz = pWal->hdr.szPage;
43946     sz = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
43947     testcase( sz<=32768 );
43948     testcase( sz>=65536 );
43949     iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
43950     *pInWal = 1;
43951     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
43952     return sqlite3OsRead(pWal->pWalFd, pOut, nOut, iOffset);
43953   }
43954
43955   *pInWal = 0;
43956   return SQLITE_OK;
43957 }
43958
43959
43960 /* 
43961 ** Return the size of the database in pages (or zero, if unknown).
43962 */
43963 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
43964   if( pWal && ALWAYS(pWal->readLock>=0) ){
43965     return pWal->hdr.nPage;
43966   }
43967   return 0;
43968 }
43969
43970
43971 /* 
43972 ** This function starts a write transaction on the WAL.
43973 **
43974 ** A read transaction must have already been started by a prior call
43975 ** to sqlite3WalBeginReadTransaction().
43976 **
43977 ** If another thread or process has written into the database since
43978 ** the read transaction was started, then it is not possible for this
43979 ** thread to write as doing so would cause a fork.  So this routine
43980 ** returns SQLITE_BUSY in that case and no write transaction is started.
43981 **
43982 ** There can only be a single writer active at a time.
43983 */
43984 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
43985   int rc;
43986
43987   /* Cannot start a write transaction without first holding a read
43988   ** transaction. */
43989   assert( pWal->readLock>=0 );
43990
43991   if( pWal->readOnly ){
43992     return SQLITE_READONLY;
43993   }
43994
43995   /* Only one writer allowed at a time.  Get the write lock.  Return
43996   ** SQLITE_BUSY if unable.
43997   */
43998   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
43999   if( rc ){
44000     return rc;
44001   }
44002   pWal->writeLock = 1;
44003
44004   /* If another connection has written to the database file since the
44005   ** time the read transaction on this connection was started, then
44006   ** the write is disallowed.
44007   */
44008   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
44009     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
44010     pWal->writeLock = 0;
44011     rc = SQLITE_BUSY;
44012   }
44013
44014   return rc;
44015 }
44016
44017 /*
44018 ** End a write transaction.  The commit has already been done.  This
44019 ** routine merely releases the lock.
44020 */
44021 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
44022   if( pWal->writeLock ){
44023     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
44024     pWal->writeLock = 0;
44025   }
44026   return SQLITE_OK;
44027 }
44028
44029 /*
44030 ** If any data has been written (but not committed) to the log file, this
44031 ** function moves the write-pointer back to the start of the transaction.
44032 **
44033 ** Additionally, the callback function is invoked for each frame written
44034 ** to the WAL since the start of the transaction. If the callback returns
44035 ** other than SQLITE_OK, it is not invoked again and the error code is
44036 ** returned to the caller.
44037 **
44038 ** Otherwise, if the callback function does not return an error, this
44039 ** function returns SQLITE_OK.
44040 */
44041 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
44042   int rc = SQLITE_OK;
44043   if( ALWAYS(pWal->writeLock) ){
44044     Pgno iMax = pWal->hdr.mxFrame;
44045     Pgno iFrame;
44046   
44047     /* Restore the clients cache of the wal-index header to the state it
44048     ** was in before the client began writing to the database. 
44049     */
44050     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
44051
44052     for(iFrame=pWal->hdr.mxFrame+1; 
44053         ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; 
44054         iFrame++
44055     ){
44056       /* This call cannot fail. Unless the page for which the page number
44057       ** is passed as the second argument is (a) in the cache and 
44058       ** (b) has an outstanding reference, then xUndo is either a no-op
44059       ** (if (a) is false) or simply expels the page from the cache (if (b)
44060       ** is false).
44061       **
44062       ** If the upper layer is doing a rollback, it is guaranteed that there
44063       ** are no outstanding references to any page other than page 1. And
44064       ** page 1 is never written to the log until the transaction is
44065       ** committed. As a result, the call to xUndo may not fail.
44066       */
44067       assert( walFramePgno(pWal, iFrame)!=1 );
44068       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
44069     }
44070     walCleanupHash(pWal);
44071   }
44072   assert( rc==SQLITE_OK );
44073   return rc;
44074 }
44075
44076 /* 
44077 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 
44078 ** values. This function populates the array with values required to 
44079 ** "rollback" the write position of the WAL handle back to the current 
44080 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
44081 */
44082 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
44083   assert( pWal->writeLock );
44084   aWalData[0] = pWal->hdr.mxFrame;
44085   aWalData[1] = pWal->hdr.aFrameCksum[0];
44086   aWalData[2] = pWal->hdr.aFrameCksum[1];
44087   aWalData[3] = pWal->nCkpt;
44088 }
44089
44090 /* 
44091 ** Move the write position of the WAL back to the point identified by
44092 ** the values in the aWalData[] array. aWalData must point to an array
44093 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
44094 ** by a call to WalSavepoint().
44095 */
44096 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
44097   int rc = SQLITE_OK;
44098
44099   assert( pWal->writeLock );
44100   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
44101
44102   if( aWalData[3]!=pWal->nCkpt ){
44103     /* This savepoint was opened immediately after the write-transaction
44104     ** was started. Right after that, the writer decided to wrap around
44105     ** to the start of the log. Update the savepoint values to match.
44106     */
44107     aWalData[0] = 0;
44108     aWalData[3] = pWal->nCkpt;
44109   }
44110
44111   if( aWalData[0]<pWal->hdr.mxFrame ){
44112     pWal->hdr.mxFrame = aWalData[0];
44113     pWal->hdr.aFrameCksum[0] = aWalData[1];
44114     pWal->hdr.aFrameCksum[1] = aWalData[2];
44115     walCleanupHash(pWal);
44116   }
44117
44118   return rc;
44119 }
44120
44121 /*
44122 ** This function is called just before writing a set of frames to the log
44123 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
44124 ** to the current log file, it is possible to overwrite the start of the
44125 ** existing log file with the new frames (i.e. "reset" the log). If so,
44126 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
44127 ** unchanged.
44128 **
44129 ** SQLITE_OK is returned if no error is encountered (regardless of whether
44130 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
44131 ** if an error occurs.
44132 */
44133 static int walRestartLog(Wal *pWal){
44134   int rc = SQLITE_OK;
44135   int cnt;
44136
44137   if( pWal->readLock==0 ){
44138     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
44139     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
44140     if( pInfo->nBackfill>0 ){
44141       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
44142       if( rc==SQLITE_OK ){
44143         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
44144         ** readers are currently using the WAL), then the transactions
44145         ** frames will overwrite the start of the existing log. Update the
44146         ** wal-index header to reflect this.
44147         **
44148         ** In theory it would be Ok to update the cache of the header only
44149         ** at this point. But updating the actual wal-index header is also
44150         ** safe and means there is no special case for sqlite3WalUndo()
44151         ** to handle if this transaction is rolled back.
44152         */
44153         int i;                    /* Loop counter */
44154         u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
44155         pWal->nCkpt++;
44156         pWal->hdr.mxFrame = 0;
44157         sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
44158         sqlite3_randomness(4, &aSalt[1]);
44159         walIndexWriteHdr(pWal);
44160         pInfo->nBackfill = 0;
44161         for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
44162         assert( pInfo->aReadMark[0]==0 );
44163         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
44164       }else if( rc!=SQLITE_BUSY ){
44165         return rc;
44166       }
44167     }
44168     walUnlockShared(pWal, WAL_READ_LOCK(0));
44169     pWal->readLock = -1;
44170     cnt = 0;
44171     do{
44172       int notUsed;
44173       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
44174     }while( rc==WAL_RETRY );
44175   }
44176   return rc;
44177 }
44178
44179 /* 
44180 ** Write a set of frames to the log. The caller must hold the write-lock
44181 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
44182 */
44183 SQLITE_PRIVATE int sqlite3WalFrames(
44184   Wal *pWal,                      /* Wal handle to write to */
44185   int szPage,                     /* Database page-size in bytes */
44186   PgHdr *pList,                   /* List of dirty pages to write */
44187   Pgno nTruncate,                 /* Database size after this commit */
44188   int isCommit,                   /* True if this is a commit */
44189   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
44190 ){
44191   int rc;                         /* Used to catch return codes */
44192   u32 iFrame;                     /* Next frame address */
44193   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
44194   PgHdr *p;                       /* Iterator to run through pList with. */
44195   PgHdr *pLast = 0;               /* Last frame in list */
44196   int nLast = 0;                  /* Number of extra copies of last page */
44197
44198   assert( pList );
44199   assert( pWal->writeLock );
44200
44201 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
44202   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
44203     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
44204               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
44205   }
44206 #endif
44207
44208   /* See if it is possible to write these frames into the start of the
44209   ** log file, instead of appending to it at pWal->hdr.mxFrame.
44210   */
44211   if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
44212     return rc;
44213   }
44214
44215   /* If this is the first frame written into the log, write the WAL
44216   ** header to the start of the WAL file. See comments at the top of
44217   ** this source file for a description of the WAL header format.
44218   */
44219   iFrame = pWal->hdr.mxFrame;
44220   if( iFrame==0 ){
44221     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
44222     u32 aCksum[2];                /* Checksum for wal-header */
44223
44224     sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
44225     sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
44226     sqlite3Put4byte(&aWalHdr[8], szPage);
44227     sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
44228     sqlite3_randomness(8, pWal->hdr.aSalt);
44229     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
44230     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
44231     sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
44232     sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
44233     
44234     pWal->szPage = szPage;
44235     pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
44236     pWal->hdr.aFrameCksum[0] = aCksum[0];
44237     pWal->hdr.aFrameCksum[1] = aCksum[1];
44238
44239     rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
44240     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
44241     if( rc!=SQLITE_OK ){
44242       return rc;
44243     }
44244   }
44245   assert( (int)pWal->szPage==szPage );
44246
44247   /* Write the log file. */
44248   for(p=pList; p; p=p->pDirty){
44249     u32 nDbsize;                  /* Db-size field for frame header */
44250     i64 iOffset;                  /* Write offset in log file */
44251     void *pData;
44252    
44253     iOffset = walFrameOffset(++iFrame, szPage);
44254     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
44255     
44256     /* Populate and write the frame header */
44257     nDbsize = (isCommit && p->pDirty==0) ? nTruncate : 0;
44258 #if defined(SQLITE_HAS_CODEC)
44259     if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
44260 #else
44261     pData = p->pData;
44262 #endif
44263     walEncodeFrame(pWal, p->pgno, nDbsize, pData, aFrame);
44264     rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
44265     if( rc!=SQLITE_OK ){
44266       return rc;
44267     }
44268
44269     /* Write the page data */
44270     rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset+sizeof(aFrame));
44271     if( rc!=SQLITE_OK ){
44272       return rc;
44273     }
44274     pLast = p;
44275   }
44276
44277   /* Sync the log file if the 'isSync' flag was specified. */
44278   if( sync_flags ){
44279     i64 iSegment = sqlite3OsSectorSize(pWal->pWalFd);
44280     i64 iOffset = walFrameOffset(iFrame+1, szPage);
44281
44282     assert( isCommit );
44283     assert( iSegment>0 );
44284
44285     iSegment = (((iOffset+iSegment-1)/iSegment) * iSegment);
44286     while( iOffset<iSegment ){
44287       void *pData;
44288 #if defined(SQLITE_HAS_CODEC)
44289       if( (pData = sqlite3PagerCodec(pLast))==0 ) return SQLITE_NOMEM;
44290 #else
44291       pData = pLast->pData;
44292 #endif
44293       walEncodeFrame(pWal, pLast->pgno, nTruncate, pData, aFrame);
44294       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
44295       rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
44296       if( rc!=SQLITE_OK ){
44297         return rc;
44298       }
44299       iOffset += WAL_FRAME_HDRSIZE;
44300       rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset); 
44301       if( rc!=SQLITE_OK ){
44302         return rc;
44303       }
44304       nLast++;
44305       iOffset += szPage;
44306     }
44307
44308     rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
44309   }
44310
44311   /* Append data to the wal-index. It is not necessary to lock the 
44312   ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
44313   ** guarantees that there are no other writers, and no data that may
44314   ** be in use by existing readers is being overwritten.
44315   */
44316   iFrame = pWal->hdr.mxFrame;
44317   for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
44318     iFrame++;
44319     rc = walIndexAppend(pWal, iFrame, p->pgno);
44320   }
44321   while( nLast>0 && rc==SQLITE_OK ){
44322     iFrame++;
44323     nLast--;
44324     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
44325   }
44326
44327   if( rc==SQLITE_OK ){
44328     /* Update the private copy of the header. */
44329     pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
44330     testcase( szPage<=32768 );
44331     testcase( szPage>=65536 );
44332     pWal->hdr.mxFrame = iFrame;
44333     if( isCommit ){
44334       pWal->hdr.iChange++;
44335       pWal->hdr.nPage = nTruncate;
44336     }
44337     /* If this is a commit, update the wal-index header too. */
44338     if( isCommit ){
44339       walIndexWriteHdr(pWal);
44340       pWal->iCallback = iFrame;
44341     }
44342   }
44343
44344   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
44345   return rc;
44346 }
44347
44348 /* 
44349 ** This routine is called to implement sqlite3_wal_checkpoint() and
44350 ** related interfaces.
44351 **
44352 ** Obtain a CHECKPOINT lock and then backfill as much information as
44353 ** we can from WAL into the database.
44354 */
44355 SQLITE_PRIVATE int sqlite3WalCheckpoint(
44356   Wal *pWal,                      /* Wal connection */
44357   int sync_flags,                 /* Flags to sync db file with (or 0) */
44358   int nBuf,                       /* Size of temporary buffer */
44359   u8 *zBuf                        /* Temporary buffer to use */
44360 ){
44361   int rc;                         /* Return code */
44362   int isChanged = 0;              /* True if a new wal-index header is loaded */
44363
44364   assert( pWal->ckptLock==0 );
44365
44366   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
44367   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
44368   if( rc ){
44369     /* Usually this is SQLITE_BUSY meaning that another thread or process
44370     ** is already running a checkpoint, or maybe a recovery.  But it might
44371     ** also be SQLITE_IOERR. */
44372     return rc;
44373   }
44374   pWal->ckptLock = 1;
44375
44376   /* Copy data from the log to the database file. */
44377   rc = walIndexReadHdr(pWal, &isChanged);
44378   if( rc==SQLITE_OK ){
44379     rc = walCheckpoint(pWal, sync_flags, nBuf, zBuf);
44380   }
44381   if( isChanged ){
44382     /* If a new wal-index header was loaded before the checkpoint was 
44383     ** performed, then the pager-cache associated with pWal is now
44384     ** out of date. So zero the cached wal-index header to ensure that
44385     ** next time the pager opens a snapshot on this database it knows that
44386     ** the cache needs to be reset.
44387     */
44388     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
44389   }
44390
44391   /* Release the locks. */
44392   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
44393   pWal->ckptLock = 0;
44394   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
44395   return rc;
44396 }
44397
44398 /* Return the value to pass to a sqlite3_wal_hook callback, the
44399 ** number of frames in the WAL at the point of the last commit since
44400 ** sqlite3WalCallback() was called.  If no commits have occurred since
44401 ** the last call, then return 0.
44402 */
44403 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
44404   u32 ret = 0;
44405   if( pWal ){
44406     ret = pWal->iCallback;
44407     pWal->iCallback = 0;
44408   }
44409   return (int)ret;
44410 }
44411
44412 /*
44413 ** This function is called to change the WAL subsystem into or out
44414 ** of locking_mode=EXCLUSIVE.
44415 **
44416 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
44417 ** into locking_mode=NORMAL.  This means that we must acquire a lock
44418 ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
44419 ** or if the acquisition of the lock fails, then return 0.  If the
44420 ** transition out of exclusive-mode is successful, return 1.  This
44421 ** operation must occur while the pager is still holding the exclusive
44422 ** lock on the main database file.
44423 **
44424 ** If op is one, then change from locking_mode=NORMAL into 
44425 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
44426 ** be released.  Return 1 if the transition is made and 0 if the
44427 ** WAL is already in exclusive-locking mode - meaning that this
44428 ** routine is a no-op.  The pager must already hold the exclusive lock
44429 ** on the main database file before invoking this operation.
44430 **
44431 ** If op is negative, then do a dry-run of the op==1 case but do
44432 ** not actually change anything. The pager uses this to see if it
44433 ** should acquire the database exclusive lock prior to invoking
44434 ** the op==1 case.
44435 */
44436 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
44437   int rc;
44438   assert( pWal->writeLock==0 );
44439   assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
44440
44441   /* pWal->readLock is usually set, but might be -1 if there was a 
44442   ** prior error while attempting to acquire are read-lock. This cannot 
44443   ** happen if the connection is actually in exclusive mode (as no xShmLock
44444   ** locks are taken in this case). Nor should the pager attempt to
44445   ** upgrade to exclusive-mode following such an error.
44446   */
44447   assert( pWal->readLock>=0 || pWal->lockError );
44448   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
44449
44450   if( op==0 ){
44451     if( pWal->exclusiveMode ){
44452       pWal->exclusiveMode = 0;
44453       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
44454         pWal->exclusiveMode = 1;
44455       }
44456       rc = pWal->exclusiveMode==0;
44457     }else{
44458       /* Already in locking_mode=NORMAL */
44459       rc = 0;
44460     }
44461   }else if( op>0 ){
44462     assert( pWal->exclusiveMode==0 );
44463     assert( pWal->readLock>=0 );
44464     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
44465     pWal->exclusiveMode = 1;
44466     rc = 1;
44467   }else{
44468     rc = pWal->exclusiveMode==0;
44469   }
44470   return rc;
44471 }
44472
44473 /* 
44474 ** Return true if the argument is non-NULL and the WAL module is using
44475 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
44476 ** WAL module is using shared-memory, return false. 
44477 */
44478 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
44479   return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
44480 }
44481
44482 #endif /* #ifndef SQLITE_OMIT_WAL */
44483
44484 /************** End of wal.c *************************************************/
44485 /************** Begin file btmutex.c *****************************************/
44486 /*
44487 ** 2007 August 27
44488 **
44489 ** The author disclaims copyright to this source code.  In place of
44490 ** a legal notice, here is a blessing:
44491 **
44492 **    May you do good and not evil.
44493 **    May you find forgiveness for yourself and forgive others.
44494 **    May you share freely, never taking more than you give.
44495 **
44496 *************************************************************************
44497 **
44498 ** This file contains code used to implement mutexes on Btree objects.
44499 ** This code really belongs in btree.c.  But btree.c is getting too
44500 ** big and we want to break it down some.  This packaged seemed like
44501 ** a good breakout.
44502 */
44503 /************** Include btreeInt.h in the middle of btmutex.c ****************/
44504 /************** Begin file btreeInt.h ****************************************/
44505 /*
44506 ** 2004 April 6
44507 **
44508 ** The author disclaims copyright to this source code.  In place of
44509 ** a legal notice, here is a blessing:
44510 **
44511 **    May you do good and not evil.
44512 **    May you find forgiveness for yourself and forgive others.
44513 **    May you share freely, never taking more than you give.
44514 **
44515 *************************************************************************
44516 ** This file implements a external (disk-based) database using BTrees.
44517 ** For a detailed discussion of BTrees, refer to
44518 **
44519 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
44520 **     "Sorting And Searching", pages 473-480. Addison-Wesley
44521 **     Publishing Company, Reading, Massachusetts.
44522 **
44523 ** The basic idea is that each page of the file contains N database
44524 ** entries and N+1 pointers to subpages.
44525 **
44526 **   ----------------------------------------------------------------
44527 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
44528 **   ----------------------------------------------------------------
44529 **
44530 ** All of the keys on the page that Ptr(0) points to have values less
44531 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
44532 ** values greater than Key(0) and less than Key(1).  All of the keys
44533 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
44534 ** so forth.
44535 **
44536 ** Finding a particular key requires reading O(log(M)) pages from the 
44537 ** disk where M is the number of entries in the tree.
44538 **
44539 ** In this implementation, a single file can hold one or more separate 
44540 ** BTrees.  Each BTree is identified by the index of its root page.  The
44541 ** key and data for any entry are combined to form the "payload".  A
44542 ** fixed amount of payload can be carried directly on the database
44543 ** page.  If the payload is larger than the preset amount then surplus
44544 ** bytes are stored on overflow pages.  The payload for an entry
44545 ** and the preceding pointer are combined to form a "Cell".  Each 
44546 ** page has a small header which contains the Ptr(N) pointer and other
44547 ** information such as the size of key and data.
44548 **
44549 ** FORMAT DETAILS
44550 **
44551 ** The file is divided into pages.  The first page is called page 1,
44552 ** the second is page 2, and so forth.  A page number of zero indicates
44553 ** "no such page".  The page size can be any power of 2 between 512 and 65536.
44554 ** Each page can be either a btree page, a freelist page, an overflow
44555 ** page, or a pointer-map page.
44556 **
44557 ** The first page is always a btree page.  The first 100 bytes of the first
44558 ** page contain a special header (the "file header") that describes the file.
44559 ** The format of the file header is as follows:
44560 **
44561 **   OFFSET   SIZE    DESCRIPTION
44562 **      0      16     Header string: "SQLite format 3\000"
44563 **     16       2     Page size in bytes.  
44564 **     18       1     File format write version
44565 **     19       1     File format read version
44566 **     20       1     Bytes of unused space at the end of each page
44567 **     21       1     Max embedded payload fraction
44568 **     22       1     Min embedded payload fraction
44569 **     23       1     Min leaf payload fraction
44570 **     24       4     File change counter
44571 **     28       4     Reserved for future use
44572 **     32       4     First freelist page
44573 **     36       4     Number of freelist pages in the file
44574 **     40      60     15 4-byte meta values passed to higher layers
44575 **
44576 **     40       4     Schema cookie
44577 **     44       4     File format of schema layer
44578 **     48       4     Size of page cache
44579 **     52       4     Largest root-page (auto/incr_vacuum)
44580 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
44581 **     60       4     User version
44582 **     64       4     Incremental vacuum mode
44583 **     68       4     unused
44584 **     72       4     unused
44585 **     76       4     unused
44586 **
44587 ** All of the integer values are big-endian (most significant byte first).
44588 **
44589 ** The file change counter is incremented when the database is changed
44590 ** This counter allows other processes to know when the file has changed
44591 ** and thus when they need to flush their cache.
44592 **
44593 ** The max embedded payload fraction is the amount of the total usable
44594 ** space in a page that can be consumed by a single cell for standard
44595 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
44596 ** is to limit the maximum cell size so that at least 4 cells will fit
44597 ** on one page.  Thus the default max embedded payload fraction is 64.
44598 **
44599 ** If the payload for a cell is larger than the max payload, then extra
44600 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
44601 ** as many bytes as possible are moved into the overflow pages without letting
44602 ** the cell size drop below the min embedded payload fraction.
44603 **
44604 ** The min leaf payload fraction is like the min embedded payload fraction
44605 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
44606 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
44607 ** not specified in the header.
44608 **
44609 ** Each btree pages is divided into three sections:  The header, the
44610 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
44611 ** file header that occurs before the page header.
44612 **
44613 **      |----------------|
44614 **      | file header    |   100 bytes.  Page 1 only.
44615 **      |----------------|
44616 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
44617 **      |----------------|
44618 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
44619 **      | array          |   |  Grows downward
44620 **      |                |   v
44621 **      |----------------|
44622 **      | unallocated    |
44623 **      | space          |
44624 **      |----------------|   ^  Grows upwards
44625 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
44626 **      | area           |   |  and free space fragments.
44627 **      |----------------|
44628 **
44629 ** The page headers looks like this:
44630 **
44631 **   OFFSET   SIZE     DESCRIPTION
44632 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
44633 **      1       2      byte offset to the first freeblock
44634 **      3       2      number of cells on this page
44635 **      5       2      first byte of the cell content area
44636 **      7       1      number of fragmented free bytes
44637 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
44638 **
44639 ** The flags define the format of this btree page.  The leaf flag means that
44640 ** this page has no children.  The zerodata flag means that this page carries
44641 ** only keys and no data.  The intkey flag means that the key is a integer
44642 ** which is stored in the key size entry of the cell header rather than in
44643 ** the payload area.
44644 **
44645 ** The cell pointer array begins on the first byte after the page header.
44646 ** The cell pointer array contains zero or more 2-byte numbers which are
44647 ** offsets from the beginning of the page to the cell content in the cell
44648 ** content area.  The cell pointers occur in sorted order.  The system strives
44649 ** to keep free space after the last cell pointer so that new cells can
44650 ** be easily added without having to defragment the page.
44651 **
44652 ** Cell content is stored at the very end of the page and grows toward the
44653 ** beginning of the page.
44654 **
44655 ** Unused space within the cell content area is collected into a linked list of
44656 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
44657 ** to the first freeblock is given in the header.  Freeblocks occur in
44658 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
44659 ** any group of 3 or fewer unused bytes in the cell content area cannot
44660 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
44661 ** a fragment.  The total number of bytes in all fragments is recorded.
44662 ** in the page header at offset 7.
44663 **
44664 **    SIZE    DESCRIPTION
44665 **      2     Byte offset of the next freeblock
44666 **      2     Bytes in this freeblock
44667 **
44668 ** Cells are of variable length.  Cells are stored in the cell content area at
44669 ** the end of the page.  Pointers to the cells are in the cell pointer array
44670 ** that immediately follows the page header.  Cells is not necessarily
44671 ** contiguous or in order, but cell pointers are contiguous and in order.
44672 **
44673 ** Cell content makes use of variable length integers.  A variable
44674 ** length integer is 1 to 9 bytes where the lower 7 bits of each 
44675 ** byte are used.  The integer consists of all bytes that have bit 8 set and
44676 ** the first byte with bit 8 clear.  The most significant byte of the integer
44677 ** appears first.  A variable-length integer may not be more than 9 bytes long.
44678 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
44679 ** allows a 64-bit integer to be encoded in 9 bytes.
44680 **
44681 **    0x00                      becomes  0x00000000
44682 **    0x7f                      becomes  0x0000007f
44683 **    0x81 0x00                 becomes  0x00000080
44684 **    0x82 0x00                 becomes  0x00000100
44685 **    0x80 0x7f                 becomes  0x0000007f
44686 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
44687 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
44688 **
44689 ** Variable length integers are used for rowids and to hold the number of
44690 ** bytes of key and data in a btree cell.
44691 **
44692 ** The content of a cell looks like this:
44693 **
44694 **    SIZE    DESCRIPTION
44695 **      4     Page number of the left child. Omitted if leaf flag is set.
44696 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
44697 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
44698 **      *     Payload
44699 **      4     First page of the overflow chain.  Omitted if no overflow
44700 **
44701 ** Overflow pages form a linked list.  Each page except the last is completely
44702 ** filled with data (pagesize - 4 bytes).  The last page can have as little
44703 ** as 1 byte of data.
44704 **
44705 **    SIZE    DESCRIPTION
44706 **      4     Page number of next overflow page
44707 **      *     Data
44708 **
44709 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
44710 ** file header points to the first in a linked list of trunk page.  Each trunk
44711 ** page points to multiple leaf pages.  The content of a leaf page is
44712 ** unspecified.  A trunk page looks like this:
44713 **
44714 **    SIZE    DESCRIPTION
44715 **      4     Page number of next trunk page
44716 **      4     Number of leaf pointers on this page
44717 **      *     zero or more pages numbers of leaves
44718 */
44719
44720
44721 /* The following value is the maximum cell size assuming a maximum page
44722 ** size give above.
44723 */
44724 #define MX_CELL_SIZE(pBt)  (pBt->pageSize-8)
44725
44726 /* The maximum number of cells on a single page of the database.  This
44727 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
44728 ** plus 2 bytes for the index to the cell in the page header).  Such
44729 ** small cells will be rare, but they are possible.
44730 */
44731 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
44732
44733 /* Forward declarations */
44734 typedef struct MemPage MemPage;
44735 typedef struct BtLock BtLock;
44736
44737 /*
44738 ** This is a magic string that appears at the beginning of every
44739 ** SQLite database in order to identify the file as a real database.
44740 **
44741 ** You can change this value at compile-time by specifying a
44742 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
44743 ** header must be exactly 16 bytes including the zero-terminator so
44744 ** the string itself should be 15 characters long.  If you change
44745 ** the header, then your custom library will not be able to read 
44746 ** databases generated by the standard tools and the standard tools
44747 ** will not be able to read databases created by your custom library.
44748 */
44749 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
44750 #  define SQLITE_FILE_HEADER "SQLite format 3"
44751 #endif
44752
44753 /*
44754 ** Page type flags.  An ORed combination of these flags appear as the
44755 ** first byte of on-disk image of every BTree page.
44756 */
44757 #define PTF_INTKEY    0x01
44758 #define PTF_ZERODATA  0x02
44759 #define PTF_LEAFDATA  0x04
44760 #define PTF_LEAF      0x08
44761
44762 /*
44763 ** As each page of the file is loaded into memory, an instance of the following
44764 ** structure is appended and initialized to zero.  This structure stores
44765 ** information about the page that is decoded from the raw file page.
44766 **
44767 ** The pParent field points back to the parent page.  This allows us to
44768 ** walk up the BTree from any leaf to the root.  Care must be taken to
44769 ** unref() the parent page pointer when this page is no longer referenced.
44770 ** The pageDestructor() routine handles that chore.
44771 **
44772 ** Access to all fields of this structure is controlled by the mutex
44773 ** stored in MemPage.pBt->mutex.
44774 */
44775 struct MemPage {
44776   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
44777   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
44778   u8 intKey;           /* True if intkey flag is set */
44779   u8 leaf;             /* True if leaf flag is set */
44780   u8 hasData;          /* True if this page stores data */
44781   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
44782   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
44783   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
44784   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
44785   u16 cellOffset;      /* Index in aData of first cell pointer */
44786   u16 nFree;           /* Number of free bytes on the page */
44787   u16 nCell;           /* Number of cells on this page, local and ovfl */
44788   u16 maskPage;        /* Mask for page offset */
44789   struct _OvflCell {   /* Cells that will not fit on aData[] */
44790     u8 *pCell;          /* Pointers to the body of the overflow cell */
44791     u16 idx;            /* Insert this cell before idx-th non-overflow cell */
44792   } aOvfl[5];
44793   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
44794   u8 *aData;           /* Pointer to disk image of the page data */
44795   DbPage *pDbPage;     /* Pager page handle */
44796   Pgno pgno;           /* Page number for this page */
44797 };
44798
44799 /*
44800 ** The in-memory image of a disk page has the auxiliary information appended
44801 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
44802 ** that extra information.
44803 */
44804 #define EXTRA_SIZE sizeof(MemPage)
44805
44806 /*
44807 ** A linked list of the following structures is stored at BtShared.pLock.
44808 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
44809 ** is opened on the table with root page BtShared.iTable. Locks are removed
44810 ** from this list when a transaction is committed or rolled back, or when
44811 ** a btree handle is closed.
44812 */
44813 struct BtLock {
44814   Btree *pBtree;        /* Btree handle holding this lock */
44815   Pgno iTable;          /* Root page of table */
44816   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
44817   BtLock *pNext;        /* Next in BtShared.pLock list */
44818 };
44819
44820 /* Candidate values for BtLock.eLock */
44821 #define READ_LOCK     1
44822 #define WRITE_LOCK    2
44823
44824 /* A Btree handle
44825 **
44826 ** A database connection contains a pointer to an instance of
44827 ** this object for every database file that it has open.  This structure
44828 ** is opaque to the database connection.  The database connection cannot
44829 ** see the internals of this structure and only deals with pointers to
44830 ** this structure.
44831 **
44832 ** For some database files, the same underlying database cache might be 
44833 ** shared between multiple connections.  In that case, each connection
44834 ** has it own instance of this object.  But each instance of this object
44835 ** points to the same BtShared object.  The database cache and the
44836 ** schema associated with the database file are all contained within
44837 ** the BtShared object.
44838 **
44839 ** All fields in this structure are accessed under sqlite3.mutex.
44840 ** The pBt pointer itself may not be changed while there exists cursors 
44841 ** in the referenced BtShared that point back to this Btree since those
44842 ** cursors have to do go through this Btree to find their BtShared and
44843 ** they often do so without holding sqlite3.mutex.
44844 */
44845 struct Btree {
44846   sqlite3 *db;       /* The database connection holding this btree */
44847   BtShared *pBt;     /* Sharable content of this btree */
44848   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
44849   u8 sharable;       /* True if we can share pBt with another db */
44850   u8 locked;         /* True if db currently has pBt locked */
44851   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
44852   int nBackup;       /* Number of backup operations reading this btree */
44853   Btree *pNext;      /* List of other sharable Btrees from the same db */
44854   Btree *pPrev;      /* Back pointer of the same list */
44855 #ifndef SQLITE_OMIT_SHARED_CACHE
44856   BtLock lock;       /* Object used to lock page 1 */
44857 #endif
44858 };
44859
44860 /*
44861 ** Btree.inTrans may take one of the following values.
44862 **
44863 ** If the shared-data extension is enabled, there may be multiple users
44864 ** of the Btree structure. At most one of these may open a write transaction,
44865 ** but any number may have active read transactions.
44866 */
44867 #define TRANS_NONE  0
44868 #define TRANS_READ  1
44869 #define TRANS_WRITE 2
44870
44871 /*
44872 ** An instance of this object represents a single database file.
44873 ** 
44874 ** A single database file can be in use as the same time by two
44875 ** or more database connections.  When two or more connections are
44876 ** sharing the same database file, each connection has it own
44877 ** private Btree object for the file and each of those Btrees points
44878 ** to this one BtShared object.  BtShared.nRef is the number of
44879 ** connections currently sharing this database file.
44880 **
44881 ** Fields in this structure are accessed under the BtShared.mutex
44882 ** mutex, except for nRef and pNext which are accessed under the
44883 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
44884 ** may not be modified once it is initially set as long as nRef>0.
44885 ** The pSchema field may be set once under BtShared.mutex and
44886 ** thereafter is unchanged as long as nRef>0.
44887 **
44888 ** isPending:
44889 **
44890 **   If a BtShared client fails to obtain a write-lock on a database
44891 **   table (because there exists one or more read-locks on the table),
44892 **   the shared-cache enters 'pending-lock' state and isPending is
44893 **   set to true.
44894 **
44895 **   The shared-cache leaves the 'pending lock' state when either of
44896 **   the following occur:
44897 **
44898 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
44899 **     2) The number of locks held by other connections drops to zero.
44900 **
44901 **   while in the 'pending-lock' state, no connection may start a new
44902 **   transaction.
44903 **
44904 **   This feature is included to help prevent writer-starvation.
44905 */
44906 struct BtShared {
44907   Pager *pPager;        /* The page cache */
44908   sqlite3 *db;          /* Database connection currently using this Btree */
44909   BtCursor *pCursor;    /* A list of all open cursors */
44910   MemPage *pPage1;      /* First page of the database */
44911   u8 readOnly;          /* True if the underlying file is readonly */
44912   u8 pageSizeFixed;     /* True if the page size can no longer be changed */
44913   u8 secureDelete;      /* True if secure_delete is enabled */
44914   u8 initiallyEmpty;    /* Database is empty at start of transaction */
44915   u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
44916 #ifndef SQLITE_OMIT_AUTOVACUUM
44917   u8 autoVacuum;        /* True if auto-vacuum is enabled */
44918   u8 incrVacuum;        /* True if incr-vacuum is enabled */
44919 #endif
44920   u8 inTransaction;     /* Transaction state */
44921   u8 doNotUseWAL;       /* If true, do not open write-ahead-log file */
44922   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
44923   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
44924   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
44925   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
44926   u32 pageSize;         /* Total number of bytes on a page */
44927   u32 usableSize;       /* Number of usable bytes on each page */
44928   int nTransaction;     /* Number of open transactions (read + write) */
44929   u32 nPage;            /* Number of pages in the database */
44930   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
44931   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
44932   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
44933   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
44934 #ifndef SQLITE_OMIT_SHARED_CACHE
44935   int nRef;             /* Number of references to this structure */
44936   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
44937   BtLock *pLock;        /* List of locks held on this shared-btree struct */
44938   Btree *pWriter;       /* Btree with currently open write transaction */
44939   u8 isExclusive;       /* True if pWriter has an EXCLUSIVE lock on the db */
44940   u8 isPending;         /* If waiting for read-locks to clear */
44941 #endif
44942   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
44943 };
44944
44945 /*
44946 ** An instance of the following structure is used to hold information
44947 ** about a cell.  The parseCellPtr() function fills in this structure
44948 ** based on information extract from the raw disk page.
44949 */
44950 typedef struct CellInfo CellInfo;
44951 struct CellInfo {
44952   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
44953   u8 *pCell;     /* Pointer to the start of cell content */
44954   u32 nData;     /* Number of bytes of data */
44955   u32 nPayload;  /* Total amount of payload */
44956   u16 nHeader;   /* Size of the cell content header in bytes */
44957   u16 nLocal;    /* Amount of payload held locally */
44958   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
44959   u16 nSize;     /* Size of the cell content on the main b-tree page */
44960 };
44961
44962 /*
44963 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
44964 ** this will be declared corrupt. This value is calculated based on a
44965 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
44966 ** root-node and 3 for all other internal nodes.
44967 **
44968 ** If a tree that appears to be taller than this is encountered, it is
44969 ** assumed that the database is corrupt.
44970 */
44971 #define BTCURSOR_MAX_DEPTH 20
44972
44973 /*
44974 ** A cursor is a pointer to a particular entry within a particular
44975 ** b-tree within a database file.
44976 **
44977 ** The entry is identified by its MemPage and the index in
44978 ** MemPage.aCell[] of the entry.
44979 **
44980 ** A single database file can shared by two more database connections,
44981 ** but cursors cannot be shared.  Each cursor is associated with a
44982 ** particular database connection identified BtCursor.pBtree.db.
44983 **
44984 ** Fields in this structure are accessed under the BtShared.mutex
44985 ** found at self->pBt->mutex. 
44986 */
44987 struct BtCursor {
44988   Btree *pBtree;            /* The Btree to which this cursor belongs */
44989   BtShared *pBt;            /* The BtShared this cursor points to */
44990   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
44991   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
44992   Pgno pgnoRoot;            /* The root page of this tree */
44993   sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
44994   CellInfo info;            /* A parse of the cell we are pointing at */
44995   i64 nKey;        /* Size of pKey, or last integer key */
44996   void *pKey;      /* Saved key that was cursor's last known position */
44997   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
44998   u8 wrFlag;                /* True if writable */
44999   u8 atLast;                /* Cursor pointing to the last entry */
45000   u8 validNKey;             /* True if info.nKey is valid */
45001   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
45002 #ifndef SQLITE_OMIT_INCRBLOB
45003   Pgno *aOverflow;          /* Cache of overflow page locations */
45004   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
45005 #endif
45006   i16 iPage;                            /* Index of current page in apPage */
45007   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
45008   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
45009 };
45010
45011 /*
45012 ** Potential values for BtCursor.eState.
45013 **
45014 ** CURSOR_VALID:
45015 **   Cursor points to a valid entry. getPayload() etc. may be called.
45016 **
45017 ** CURSOR_INVALID:
45018 **   Cursor does not point to a valid entry. This can happen (for example) 
45019 **   because the table is empty or because BtreeCursorFirst() has not been
45020 **   called.
45021 **
45022 ** CURSOR_REQUIRESEEK:
45023 **   The table that this cursor was opened on still exists, but has been 
45024 **   modified since the cursor was last used. The cursor position is saved
45025 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
45026 **   this state, restoreCursorPosition() can be called to attempt to
45027 **   seek the cursor to the saved position.
45028 **
45029 ** CURSOR_FAULT:
45030 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
45031 **   on a different connection that shares the BtShared cache with this
45032 **   cursor.  The error has left the cache in an inconsistent state.
45033 **   Do nothing else with this cursor.  Any attempt to use the cursor
45034 **   should return the error code stored in BtCursor.skip
45035 */
45036 #define CURSOR_INVALID           0
45037 #define CURSOR_VALID             1
45038 #define CURSOR_REQUIRESEEK       2
45039 #define CURSOR_FAULT             3
45040
45041 /* 
45042 ** The database page the PENDING_BYTE occupies. This page is never used.
45043 */
45044 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
45045
45046 /*
45047 ** These macros define the location of the pointer-map entry for a 
45048 ** database page. The first argument to each is the number of usable
45049 ** bytes on each page of the database (often 1024). The second is the
45050 ** page number to look up in the pointer map.
45051 **
45052 ** PTRMAP_PAGENO returns the database page number of the pointer-map
45053 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
45054 ** the offset of the requested map entry.
45055 **
45056 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
45057 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
45058 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
45059 ** this test.
45060 */
45061 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
45062 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
45063 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
45064
45065 /*
45066 ** The pointer map is a lookup table that identifies the parent page for
45067 ** each child page in the database file.  The parent page is the page that
45068 ** contains a pointer to the child.  Every page in the database contains
45069 ** 0 or 1 parent pages.  (In this context 'database page' refers
45070 ** to any page that is not part of the pointer map itself.)  Each pointer map
45071 ** entry consists of a single byte 'type' and a 4 byte parent page number.
45072 ** The PTRMAP_XXX identifiers below are the valid types.
45073 **
45074 ** The purpose of the pointer map is to facility moving pages from one
45075 ** position in the file to another as part of autovacuum.  When a page
45076 ** is moved, the pointer in its parent must be updated to point to the
45077 ** new location.  The pointer map is used to locate the parent page quickly.
45078 **
45079 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
45080 **                  used in this case.
45081 **
45082 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
45083 **                  is not used in this case.
45084 **
45085 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
45086 **                   overflow pages. The page number identifies the page that
45087 **                   contains the cell with a pointer to this overflow page.
45088 **
45089 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
45090 **                   overflow pages. The page-number identifies the previous
45091 **                   page in the overflow page list.
45092 **
45093 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
45094 **               identifies the parent page in the btree.
45095 */
45096 #define PTRMAP_ROOTPAGE 1
45097 #define PTRMAP_FREEPAGE 2
45098 #define PTRMAP_OVERFLOW1 3
45099 #define PTRMAP_OVERFLOW2 4
45100 #define PTRMAP_BTREE 5
45101
45102 /* A bunch of assert() statements to check the transaction state variables
45103 ** of handle p (type Btree*) are internally consistent.
45104 */
45105 #define btreeIntegrity(p) \
45106   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
45107   assert( p->pBt->inTransaction>=p->inTrans ); 
45108
45109
45110 /*
45111 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
45112 ** if the database supports auto-vacuum or not. Because it is used
45113 ** within an expression that is an argument to another macro 
45114 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
45115 ** So, this macro is defined instead.
45116 */
45117 #ifndef SQLITE_OMIT_AUTOVACUUM
45118 #define ISAUTOVACUUM (pBt->autoVacuum)
45119 #else
45120 #define ISAUTOVACUUM 0
45121 #endif
45122
45123
45124 /*
45125 ** This structure is passed around through all the sanity checking routines
45126 ** in order to keep track of some global state information.
45127 */
45128 typedef struct IntegrityCk IntegrityCk;
45129 struct IntegrityCk {
45130   BtShared *pBt;    /* The tree being checked out */
45131   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
45132   Pgno nPage;       /* Number of pages in the database */
45133   int *anRef;       /* Number of times each page is referenced */
45134   int mxErr;        /* Stop accumulating errors when this reaches zero */
45135   int nErr;         /* Number of messages written to zErrMsg so far */
45136   int mallocFailed; /* A memory allocation error has occurred */
45137   StrAccum errMsg;  /* Accumulate the error message text here */
45138 };
45139
45140 /*
45141 ** Read or write a two- and four-byte big-endian integer values.
45142 */
45143 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
45144 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
45145 #define get4byte sqlite3Get4byte
45146 #define put4byte sqlite3Put4byte
45147
45148 /************** End of btreeInt.h ********************************************/
45149 /************** Continuing where we left off in btmutex.c ********************/
45150 #ifndef SQLITE_OMIT_SHARED_CACHE
45151 #if SQLITE_THREADSAFE
45152
45153 /*
45154 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
45155 ** set BtShared.db to the database handle associated with p and the
45156 ** p->locked boolean to true.
45157 */
45158 static void lockBtreeMutex(Btree *p){
45159   assert( p->locked==0 );
45160   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
45161   assert( sqlite3_mutex_held(p->db->mutex) );
45162
45163   sqlite3_mutex_enter(p->pBt->mutex);
45164   p->pBt->db = p->db;
45165   p->locked = 1;
45166 }
45167
45168 /*
45169 ** Release the BtShared mutex associated with B-Tree handle p and
45170 ** clear the p->locked boolean.
45171 */
45172 static void unlockBtreeMutex(Btree *p){
45173   assert( p->locked==1 );
45174   assert( sqlite3_mutex_held(p->pBt->mutex) );
45175   assert( sqlite3_mutex_held(p->db->mutex) );
45176   assert( p->db==p->pBt->db );
45177
45178   sqlite3_mutex_leave(p->pBt->mutex);
45179   p->locked = 0;
45180 }
45181
45182 /*
45183 ** Enter a mutex on the given BTree object.
45184 **
45185 ** If the object is not sharable, then no mutex is ever required
45186 ** and this routine is a no-op.  The underlying mutex is non-recursive.
45187 ** But we keep a reference count in Btree.wantToLock so the behavior
45188 ** of this interface is recursive.
45189 **
45190 ** To avoid deadlocks, multiple Btrees are locked in the same order
45191 ** by all database connections.  The p->pNext is a list of other
45192 ** Btrees belonging to the same database connection as the p Btree
45193 ** which need to be locked after p.  If we cannot get a lock on
45194 ** p, then first unlock all of the others on p->pNext, then wait
45195 ** for the lock to become available on p, then relock all of the
45196 ** subsequent Btrees that desire a lock.
45197 */
45198 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
45199   Btree *pLater;
45200
45201   /* Some basic sanity checking on the Btree.  The list of Btrees
45202   ** connected by pNext and pPrev should be in sorted order by
45203   ** Btree.pBt value. All elements of the list should belong to
45204   ** the same connection. Only shared Btrees are on the list. */
45205   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
45206   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
45207   assert( p->pNext==0 || p->pNext->db==p->db );
45208   assert( p->pPrev==0 || p->pPrev->db==p->db );
45209   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
45210
45211   /* Check for locking consistency */
45212   assert( !p->locked || p->wantToLock>0 );
45213   assert( p->sharable || p->wantToLock==0 );
45214
45215   /* We should already hold a lock on the database connection */
45216   assert( sqlite3_mutex_held(p->db->mutex) );
45217
45218   /* Unless the database is sharable and unlocked, then BtShared.db
45219   ** should already be set correctly. */
45220   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
45221
45222   if( !p->sharable ) return;
45223   p->wantToLock++;
45224   if( p->locked ) return;
45225
45226   /* In most cases, we should be able to acquire the lock we
45227   ** want without having to go throught the ascending lock
45228   ** procedure that follows.  Just be sure not to block.
45229   */
45230   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
45231     p->pBt->db = p->db;
45232     p->locked = 1;
45233     return;
45234   }
45235
45236   /* To avoid deadlock, first release all locks with a larger
45237   ** BtShared address.  Then acquire our lock.  Then reacquire
45238   ** the other BtShared locks that we used to hold in ascending
45239   ** order.
45240   */
45241   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
45242     assert( pLater->sharable );
45243     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
45244     assert( !pLater->locked || pLater->wantToLock>0 );
45245     if( pLater->locked ){
45246       unlockBtreeMutex(pLater);
45247     }
45248   }
45249   lockBtreeMutex(p);
45250   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
45251     if( pLater->wantToLock ){
45252       lockBtreeMutex(pLater);
45253     }
45254   }
45255 }
45256
45257 /*
45258 ** Exit the recursive mutex on a Btree.
45259 */
45260 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
45261   if( p->sharable ){
45262     assert( p->wantToLock>0 );
45263     p->wantToLock--;
45264     if( p->wantToLock==0 ){
45265       unlockBtreeMutex(p);
45266     }
45267   }
45268 }
45269
45270 #ifndef NDEBUG
45271 /*
45272 ** Return true if the BtShared mutex is held on the btree, or if the
45273 ** B-Tree is not marked as sharable.
45274 **
45275 ** This routine is used only from within assert() statements.
45276 */
45277 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
45278   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
45279   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
45280   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
45281   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
45282
45283   return (p->sharable==0 || p->locked);
45284 }
45285 #endif
45286
45287
45288 #ifndef SQLITE_OMIT_INCRBLOB
45289 /*
45290 ** Enter and leave a mutex on a Btree given a cursor owned by that
45291 ** Btree.  These entry points are used by incremental I/O and can be
45292 ** omitted if that module is not used.
45293 */
45294 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
45295   sqlite3BtreeEnter(pCur->pBtree);
45296 }
45297 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
45298   sqlite3BtreeLeave(pCur->pBtree);
45299 }
45300 #endif /* SQLITE_OMIT_INCRBLOB */
45301
45302
45303 /*
45304 ** Enter the mutex on every Btree associated with a database
45305 ** connection.  This is needed (for example) prior to parsing
45306 ** a statement since we will be comparing table and column names
45307 ** against all schemas and we do not want those schemas being
45308 ** reset out from under us.
45309 **
45310 ** There is a corresponding leave-all procedures.
45311 **
45312 ** Enter the mutexes in accending order by BtShared pointer address
45313 ** to avoid the possibility of deadlock when two threads with
45314 ** two or more btrees in common both try to lock all their btrees
45315 ** at the same instant.
45316 */
45317 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
45318   int i;
45319   Btree *p, *pLater;
45320   assert( sqlite3_mutex_held(db->mutex) );
45321   for(i=0; i<db->nDb; i++){
45322     p = db->aDb[i].pBt;
45323     assert( !p || (p->locked==0 && p->sharable) || p->pBt->db==p->db );
45324     if( p && p->sharable ){
45325       p->wantToLock++;
45326       if( !p->locked ){
45327         assert( p->wantToLock==1 );
45328         while( p->pPrev ) p = p->pPrev;
45329         /* Reason for ALWAYS:  There must be at least on unlocked Btree in
45330         ** the chain.  Otherwise the !p->locked test above would have failed */
45331         while( p->locked && ALWAYS(p->pNext) ) p = p->pNext;
45332         for(pLater = p->pNext; pLater; pLater=pLater->pNext){
45333           if( pLater->locked ){
45334             unlockBtreeMutex(pLater);
45335           }
45336         }
45337         while( p ){
45338           lockBtreeMutex(p);
45339           p = p->pNext;
45340         }
45341       }
45342     }
45343   }
45344 }
45345 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
45346   int i;
45347   Btree *p;
45348   assert( sqlite3_mutex_held(db->mutex) );
45349   for(i=0; i<db->nDb; i++){
45350     p = db->aDb[i].pBt;
45351     if( p && p->sharable ){
45352       assert( p->wantToLock>0 );
45353       p->wantToLock--;
45354       if( p->wantToLock==0 ){
45355         unlockBtreeMutex(p);
45356       }
45357     }
45358   }
45359 }
45360
45361 #ifndef NDEBUG
45362 /*
45363 ** Return true if the current thread holds the database connection
45364 ** mutex and all required BtShared mutexes.
45365 **
45366 ** This routine is used inside assert() statements only.
45367 */
45368 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
45369   int i;
45370   if( !sqlite3_mutex_held(db->mutex) ){
45371     return 0;
45372   }
45373   for(i=0; i<db->nDb; i++){
45374     Btree *p;
45375     p = db->aDb[i].pBt;
45376     if( p && p->sharable &&
45377          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
45378       return 0;
45379     }
45380   }
45381   return 1;
45382 }
45383 #endif /* NDEBUG */
45384
45385 /*
45386 ** Add a new Btree pointer to a BtreeMutexArray. 
45387 ** if the pointer can possibly be shared with
45388 ** another database connection.
45389 **
45390 ** The pointers are kept in sorted order by pBtree->pBt.  That
45391 ** way when we go to enter all the mutexes, we can enter them
45392 ** in order without every having to backup and retry and without
45393 ** worrying about deadlock.
45394 **
45395 ** The number of shared btrees will always be small (usually 0 or 1)
45396 ** so an insertion sort is an adequate algorithm here.
45397 */
45398 SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){
45399   int i, j;
45400   BtShared *pBt;
45401   if( pBtree==0 || pBtree->sharable==0 ) return;
45402 #ifndef NDEBUG
45403   {
45404     for(i=0; i<pArray->nMutex; i++){
45405       assert( pArray->aBtree[i]!=pBtree );
45406     }
45407   }
45408 #endif
45409   assert( pArray->nMutex>=0 );
45410   assert( pArray->nMutex<ArraySize(pArray->aBtree)-1 );
45411   pBt = pBtree->pBt;
45412   for(i=0; i<pArray->nMutex; i++){
45413     assert( pArray->aBtree[i]!=pBtree );
45414     if( pArray->aBtree[i]->pBt>pBt ){
45415       for(j=pArray->nMutex; j>i; j--){
45416         pArray->aBtree[j] = pArray->aBtree[j-1];
45417       }
45418       pArray->aBtree[i] = pBtree;
45419       pArray->nMutex++;
45420       return;
45421     }
45422   }
45423   pArray->aBtree[pArray->nMutex++] = pBtree;
45424 }
45425
45426 /*
45427 ** Enter the mutex of every btree in the array.  This routine is
45428 ** called at the beginning of sqlite3VdbeExec().  The mutexes are
45429 ** exited at the end of the same function.
45430 */
45431 SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){
45432   int i;
45433   for(i=0; i<pArray->nMutex; i++){
45434     Btree *p = pArray->aBtree[i];
45435     /* Some basic sanity checking */
45436     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
45437     assert( !p->locked || p->wantToLock>0 );
45438
45439     /* We should already hold a lock on the database connection */
45440     assert( sqlite3_mutex_held(p->db->mutex) );
45441
45442     /* The Btree is sharable because only sharable Btrees are entered
45443     ** into the array in the first place. */
45444     assert( p->sharable );
45445
45446     p->wantToLock++;
45447     if( !p->locked ){
45448       lockBtreeMutex(p);
45449     }
45450   }
45451 }
45452
45453 /*
45454 ** Leave the mutex of every btree in the group.
45455 */
45456 SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){
45457   int i;
45458   for(i=0; i<pArray->nMutex; i++){
45459     Btree *p = pArray->aBtree[i];
45460     /* Some basic sanity checking */
45461     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
45462     assert( p->locked );
45463     assert( p->wantToLock>0 );
45464
45465     /* We should already hold a lock on the database connection */
45466     assert( sqlite3_mutex_held(p->db->mutex) );
45467
45468     p->wantToLock--;
45469     if( p->wantToLock==0 ){
45470       unlockBtreeMutex(p);
45471     }
45472   }
45473 }
45474
45475 #else
45476 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
45477   p->pBt->db = p->db;
45478 }
45479 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
45480   int i;
45481   for(i=0; i<db->nDb; i++){
45482     Btree *p = db->aDb[i].pBt;
45483     if( p ){
45484       p->pBt->db = p->db;
45485     }
45486   }
45487 }
45488 #endif /* if SQLITE_THREADSAFE */
45489 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
45490
45491 /************** End of btmutex.c *********************************************/
45492 /************** Begin file btree.c *******************************************/
45493 /*
45494 ** 2004 April 6
45495 **
45496 ** The author disclaims copyright to this source code.  In place of
45497 ** a legal notice, here is a blessing:
45498 **
45499 **    May you do good and not evil.
45500 **    May you find forgiveness for yourself and forgive others.
45501 **    May you share freely, never taking more than you give.
45502 **
45503 *************************************************************************
45504 ** This file implements a external (disk-based) database using BTrees.
45505 ** See the header comment on "btreeInt.h" for additional information.
45506 ** Including a description of file format and an overview of operation.
45507 */
45508
45509 /*
45510 ** The header string that appears at the beginning of every
45511 ** SQLite database.
45512 */
45513 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
45514
45515 /*
45516 ** Set this global variable to 1 to enable tracing using the TRACE
45517 ** macro.
45518 */
45519 #if 0
45520 int sqlite3BtreeTrace=1;  /* True to enable tracing */
45521 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
45522 #else
45523 # define TRACE(X)
45524 #endif
45525
45526 /*
45527 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
45528 ** But if the value is zero, make it 65536.
45529 **
45530 ** This routine is used to extract the "offset to cell content area" value
45531 ** from the header of a btree page.  If the page size is 65536 and the page
45532 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
45533 ** This routine makes the necessary adjustment to 65536.
45534 */
45535 #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
45536
45537 #ifndef SQLITE_OMIT_SHARED_CACHE
45538 /*
45539 ** A list of BtShared objects that are eligible for participation
45540 ** in shared cache.  This variable has file scope during normal builds,
45541 ** but the test harness needs to access it so we make it global for 
45542 ** test builds.
45543 **
45544 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
45545 */
45546 #ifdef SQLITE_TEST
45547 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
45548 #else
45549 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
45550 #endif
45551 #endif /* SQLITE_OMIT_SHARED_CACHE */
45552
45553 #ifndef SQLITE_OMIT_SHARED_CACHE
45554 /*
45555 ** Enable or disable the shared pager and schema features.
45556 **
45557 ** This routine has no effect on existing database connections.
45558 ** The shared cache setting effects only future calls to
45559 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
45560 */
45561 SQLITE_API int sqlite3_enable_shared_cache(int enable){
45562   sqlite3GlobalConfig.sharedCacheEnabled = enable;
45563   return SQLITE_OK;
45564 }
45565 #endif
45566
45567
45568
45569 #ifdef SQLITE_OMIT_SHARED_CACHE
45570   /*
45571   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
45572   ** and clearAllSharedCacheTableLocks()
45573   ** manipulate entries in the BtShared.pLock linked list used to store
45574   ** shared-cache table level locks. If the library is compiled with the
45575   ** shared-cache feature disabled, then there is only ever one user
45576   ** of each BtShared structure and so this locking is not necessary. 
45577   ** So define the lock related functions as no-ops.
45578   */
45579   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
45580   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
45581   #define clearAllSharedCacheTableLocks(a)
45582   #define downgradeAllSharedCacheTableLocks(a)
45583   #define hasSharedCacheTableLock(a,b,c,d) 1
45584   #define hasReadConflicts(a, b) 0
45585 #endif
45586
45587 #ifndef SQLITE_OMIT_SHARED_CACHE
45588
45589 #ifdef SQLITE_DEBUG
45590 /*
45591 **** This function is only used as part of an assert() statement. ***
45592 **
45593 ** Check to see if pBtree holds the required locks to read or write to the 
45594 ** table with root page iRoot.   Return 1 if it does and 0 if not.
45595 **
45596 ** For example, when writing to a table with root-page iRoot via 
45597 ** Btree connection pBtree:
45598 **
45599 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
45600 **
45601 ** When writing to an index that resides in a sharable database, the 
45602 ** caller should have first obtained a lock specifying the root page of
45603 ** the corresponding table. This makes things a bit more complicated,
45604 ** as this module treats each table as a separate structure. To determine
45605 ** the table corresponding to the index being written, this
45606 ** function has to search through the database schema.
45607 **
45608 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
45609 ** hold a write-lock on the schema table (root page 1). This is also
45610 ** acceptable.
45611 */
45612 static int hasSharedCacheTableLock(
45613   Btree *pBtree,         /* Handle that must hold lock */
45614   Pgno iRoot,            /* Root page of b-tree */
45615   int isIndex,           /* True if iRoot is the root of an index b-tree */
45616   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
45617 ){
45618   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
45619   Pgno iTab = 0;
45620   BtLock *pLock;
45621
45622   /* If this database is not shareable, or if the client is reading
45623   ** and has the read-uncommitted flag set, then no lock is required. 
45624   ** Return true immediately.
45625   */
45626   if( (pBtree->sharable==0)
45627    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
45628   ){
45629     return 1;
45630   }
45631
45632   /* If the client is reading  or writing an index and the schema is
45633   ** not loaded, then it is too difficult to actually check to see if
45634   ** the correct locks are held.  So do not bother - just return true.
45635   ** This case does not come up very often anyhow.
45636   */
45637   if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
45638     return 1;
45639   }
45640
45641   /* Figure out the root-page that the lock should be held on. For table
45642   ** b-trees, this is just the root page of the b-tree being read or
45643   ** written. For index b-trees, it is the root page of the associated
45644   ** table.  */
45645   if( isIndex ){
45646     HashElem *p;
45647     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
45648       Index *pIdx = (Index *)sqliteHashData(p);
45649       if( pIdx->tnum==(int)iRoot ){
45650         iTab = pIdx->pTable->tnum;
45651       }
45652     }
45653   }else{
45654     iTab = iRoot;
45655   }
45656
45657   /* Search for the required lock. Either a write-lock on root-page iTab, a 
45658   ** write-lock on the schema table, or (if the client is reading) a
45659   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
45660   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
45661     if( pLock->pBtree==pBtree 
45662      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
45663      && pLock->eLock>=eLockType 
45664     ){
45665       return 1;
45666     }
45667   }
45668
45669   /* Failed to find the required lock. */
45670   return 0;
45671 }
45672 #endif /* SQLITE_DEBUG */
45673
45674 #ifdef SQLITE_DEBUG
45675 /*
45676 **** This function may be used as part of assert() statements only. ****
45677 **
45678 ** Return true if it would be illegal for pBtree to write into the
45679 ** table or index rooted at iRoot because other shared connections are
45680 ** simultaneously reading that same table or index.
45681 **
45682 ** It is illegal for pBtree to write if some other Btree object that
45683 ** shares the same BtShared object is currently reading or writing
45684 ** the iRoot table.  Except, if the other Btree object has the
45685 ** read-uncommitted flag set, then it is OK for the other object to
45686 ** have a read cursor.
45687 **
45688 ** For example, before writing to any part of the table or index
45689 ** rooted at page iRoot, one should call:
45690 **
45691 **    assert( !hasReadConflicts(pBtree, iRoot) );
45692 */
45693 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
45694   BtCursor *p;
45695   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
45696     if( p->pgnoRoot==iRoot 
45697      && p->pBtree!=pBtree
45698      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
45699     ){
45700       return 1;
45701     }
45702   }
45703   return 0;
45704 }
45705 #endif    /* #ifdef SQLITE_DEBUG */
45706
45707 /*
45708 ** Query to see if Btree handle p may obtain a lock of type eLock 
45709 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
45710 ** SQLITE_OK if the lock may be obtained (by calling
45711 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
45712 */
45713 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
45714   BtShared *pBt = p->pBt;
45715   BtLock *pIter;
45716
45717   assert( sqlite3BtreeHoldsMutex(p) );
45718   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
45719   assert( p->db!=0 );
45720   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
45721   
45722   /* If requesting a write-lock, then the Btree must have an open write
45723   ** transaction on this file. And, obviously, for this to be so there 
45724   ** must be an open write transaction on the file itself.
45725   */
45726   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
45727   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
45728   
45729   /* This routine is a no-op if the shared-cache is not enabled */
45730   if( !p->sharable ){
45731     return SQLITE_OK;
45732   }
45733
45734   /* If some other connection is holding an exclusive lock, the
45735   ** requested lock may not be obtained.
45736   */
45737   if( pBt->pWriter!=p && pBt->isExclusive ){
45738     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
45739     return SQLITE_LOCKED_SHAREDCACHE;
45740   }
45741
45742   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
45743     /* The condition (pIter->eLock!=eLock) in the following if(...) 
45744     ** statement is a simplification of:
45745     **
45746     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
45747     **
45748     ** since we know that if eLock==WRITE_LOCK, then no other connection
45749     ** may hold a WRITE_LOCK on any table in this file (since there can
45750     ** only be a single writer).
45751     */
45752     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
45753     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
45754     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
45755       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
45756       if( eLock==WRITE_LOCK ){
45757         assert( p==pBt->pWriter );
45758         pBt->isPending = 1;
45759       }
45760       return SQLITE_LOCKED_SHAREDCACHE;
45761     }
45762   }
45763   return SQLITE_OK;
45764 }
45765 #endif /* !SQLITE_OMIT_SHARED_CACHE */
45766
45767 #ifndef SQLITE_OMIT_SHARED_CACHE
45768 /*
45769 ** Add a lock on the table with root-page iTable to the shared-btree used
45770 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
45771 ** WRITE_LOCK.
45772 **
45773 ** This function assumes the following:
45774 **
45775 **   (a) The specified Btree object p is connected to a sharable
45776 **       database (one with the BtShared.sharable flag set), and
45777 **
45778 **   (b) No other Btree objects hold a lock that conflicts
45779 **       with the requested lock (i.e. querySharedCacheTableLock() has
45780 **       already been called and returned SQLITE_OK).
45781 **
45782 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM 
45783 ** is returned if a malloc attempt fails.
45784 */
45785 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
45786   BtShared *pBt = p->pBt;
45787   BtLock *pLock = 0;
45788   BtLock *pIter;
45789
45790   assert( sqlite3BtreeHoldsMutex(p) );
45791   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
45792   assert( p->db!=0 );
45793
45794   /* A connection with the read-uncommitted flag set will never try to
45795   ** obtain a read-lock using this function. The only read-lock obtained
45796   ** by a connection in read-uncommitted mode is on the sqlite_master 
45797   ** table, and that lock is obtained in BtreeBeginTrans().  */
45798   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
45799
45800   /* This function should only be called on a sharable b-tree after it 
45801   ** has been determined that no other b-tree holds a conflicting lock.  */
45802   assert( p->sharable );
45803   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
45804
45805   /* First search the list for an existing lock on this table. */
45806   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
45807     if( pIter->iTable==iTable && pIter->pBtree==p ){
45808       pLock = pIter;
45809       break;
45810     }
45811   }
45812
45813   /* If the above search did not find a BtLock struct associating Btree p
45814   ** with table iTable, allocate one and link it into the list.
45815   */
45816   if( !pLock ){
45817     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
45818     if( !pLock ){
45819       return SQLITE_NOMEM;
45820     }
45821     pLock->iTable = iTable;
45822     pLock->pBtree = p;
45823     pLock->pNext = pBt->pLock;
45824     pBt->pLock = pLock;
45825   }
45826
45827   /* Set the BtLock.eLock variable to the maximum of the current lock
45828   ** and the requested lock. This means if a write-lock was already held
45829   ** and a read-lock requested, we don't incorrectly downgrade the lock.
45830   */
45831   assert( WRITE_LOCK>READ_LOCK );
45832   if( eLock>pLock->eLock ){
45833     pLock->eLock = eLock;
45834   }
45835
45836   return SQLITE_OK;
45837 }
45838 #endif /* !SQLITE_OMIT_SHARED_CACHE */
45839
45840 #ifndef SQLITE_OMIT_SHARED_CACHE
45841 /*
45842 ** Release all the table locks (locks obtained via calls to
45843 ** the setSharedCacheTableLock() procedure) held by Btree object p.
45844 **
45845 ** This function assumes that Btree p has an open read or write 
45846 ** transaction. If it does not, then the BtShared.isPending variable
45847 ** may be incorrectly cleared.
45848 */
45849 static void clearAllSharedCacheTableLocks(Btree *p){
45850   BtShared *pBt = p->pBt;
45851   BtLock **ppIter = &pBt->pLock;
45852
45853   assert( sqlite3BtreeHoldsMutex(p) );
45854   assert( p->sharable || 0==*ppIter );
45855   assert( p->inTrans>0 );
45856
45857   while( *ppIter ){
45858     BtLock *pLock = *ppIter;
45859     assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
45860     assert( pLock->pBtree->inTrans>=pLock->eLock );
45861     if( pLock->pBtree==p ){
45862       *ppIter = pLock->pNext;
45863       assert( pLock->iTable!=1 || pLock==&p->lock );
45864       if( pLock->iTable!=1 ){
45865         sqlite3_free(pLock);
45866       }
45867     }else{
45868       ppIter = &pLock->pNext;
45869     }
45870   }
45871
45872   assert( pBt->isPending==0 || pBt->pWriter );
45873   if( pBt->pWriter==p ){
45874     pBt->pWriter = 0;
45875     pBt->isExclusive = 0;
45876     pBt->isPending = 0;
45877   }else if( pBt->nTransaction==2 ){
45878     /* This function is called when Btree p is concluding its 
45879     ** transaction. If there currently exists a writer, and p is not
45880     ** that writer, then the number of locks held by connections other
45881     ** than the writer must be about to drop to zero. In this case
45882     ** set the isPending flag to 0.
45883     **
45884     ** If there is not currently a writer, then BtShared.isPending must
45885     ** be zero already. So this next line is harmless in that case.
45886     */
45887     pBt->isPending = 0;
45888   }
45889 }
45890
45891 /*
45892 ** This function changes all write-locks held by Btree p into read-locks.
45893 */
45894 static void downgradeAllSharedCacheTableLocks(Btree *p){
45895   BtShared *pBt = p->pBt;
45896   if( pBt->pWriter==p ){
45897     BtLock *pLock;
45898     pBt->pWriter = 0;
45899     pBt->isExclusive = 0;
45900     pBt->isPending = 0;
45901     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
45902       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
45903       pLock->eLock = READ_LOCK;
45904     }
45905   }
45906 }
45907
45908 #endif /* SQLITE_OMIT_SHARED_CACHE */
45909
45910 static void releasePage(MemPage *pPage);  /* Forward reference */
45911
45912 /*
45913 ***** This routine is used inside of assert() only ****
45914 **
45915 ** Verify that the cursor holds the mutex on its BtShared
45916 */
45917 #ifdef SQLITE_DEBUG
45918 static int cursorHoldsMutex(BtCursor *p){
45919   return sqlite3_mutex_held(p->pBt->mutex);
45920 }
45921 #endif
45922
45923
45924 #ifndef SQLITE_OMIT_INCRBLOB
45925 /*
45926 ** Invalidate the overflow page-list cache for cursor pCur, if any.
45927 */
45928 static void invalidateOverflowCache(BtCursor *pCur){
45929   assert( cursorHoldsMutex(pCur) );
45930   sqlite3_free(pCur->aOverflow);
45931   pCur->aOverflow = 0;
45932 }
45933
45934 /*
45935 ** Invalidate the overflow page-list cache for all cursors opened
45936 ** on the shared btree structure pBt.
45937 */
45938 static void invalidateAllOverflowCache(BtShared *pBt){
45939   BtCursor *p;
45940   assert( sqlite3_mutex_held(pBt->mutex) );
45941   for(p=pBt->pCursor; p; p=p->pNext){
45942     invalidateOverflowCache(p);
45943   }
45944 }
45945
45946 /*
45947 ** This function is called before modifying the contents of a table
45948 ** to invalidate any incrblob cursors that are open on the
45949 ** row or one of the rows being modified.
45950 **
45951 ** If argument isClearTable is true, then the entire contents of the
45952 ** table is about to be deleted. In this case invalidate all incrblob
45953 ** cursors open on any row within the table with root-page pgnoRoot.
45954 **
45955 ** Otherwise, if argument isClearTable is false, then the row with
45956 ** rowid iRow is being replaced or deleted. In this case invalidate
45957 ** only those incrblob cursors open on that specific row.
45958 */
45959 static void invalidateIncrblobCursors(
45960   Btree *pBtree,          /* The database file to check */
45961   i64 iRow,               /* The rowid that might be changing */
45962   int isClearTable        /* True if all rows are being deleted */
45963 ){
45964   BtCursor *p;
45965   BtShared *pBt = pBtree->pBt;
45966   assert( sqlite3BtreeHoldsMutex(pBtree) );
45967   for(p=pBt->pCursor; p; p=p->pNext){
45968     if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
45969       p->eState = CURSOR_INVALID;
45970     }
45971   }
45972 }
45973
45974 #else
45975   /* Stub functions when INCRBLOB is omitted */
45976   #define invalidateOverflowCache(x)
45977   #define invalidateAllOverflowCache(x)
45978   #define invalidateIncrblobCursors(x,y,z)
45979 #endif /* SQLITE_OMIT_INCRBLOB */
45980
45981 /*
45982 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called 
45983 ** when a page that previously contained data becomes a free-list leaf 
45984 ** page.
45985 **
45986 ** The BtShared.pHasContent bitvec exists to work around an obscure
45987 ** bug caused by the interaction of two useful IO optimizations surrounding
45988 ** free-list leaf pages:
45989 **
45990 **   1) When all data is deleted from a page and the page becomes
45991 **      a free-list leaf page, the page is not written to the database
45992 **      (as free-list leaf pages contain no meaningful data). Sometimes
45993 **      such a page is not even journalled (as it will not be modified,
45994 **      why bother journalling it?).
45995 **
45996 **   2) When a free-list leaf page is reused, its content is not read
45997 **      from the database or written to the journal file (why should it
45998 **      be, if it is not at all meaningful?).
45999 **
46000 ** By themselves, these optimizations work fine and provide a handy
46001 ** performance boost to bulk delete or insert operations. However, if
46002 ** a page is moved to the free-list and then reused within the same
46003 ** transaction, a problem comes up. If the page is not journalled when
46004 ** it is moved to the free-list and it is also not journalled when it
46005 ** is extracted from the free-list and reused, then the original data
46006 ** may be lost. In the event of a rollback, it may not be possible
46007 ** to restore the database to its original configuration.
46008 **
46009 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is 
46010 ** moved to become a free-list leaf page, the corresponding bit is
46011 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
46012 ** optimization 2 above is omitted if the corresponding bit is already
46013 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
46014 ** at the end of every transaction.
46015 */
46016 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
46017   int rc = SQLITE_OK;
46018   if( !pBt->pHasContent ){
46019     assert( pgno<=pBt->nPage );
46020     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
46021     if( !pBt->pHasContent ){
46022       rc = SQLITE_NOMEM;
46023     }
46024   }
46025   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
46026     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
46027   }
46028   return rc;
46029 }
46030
46031 /*
46032 ** Query the BtShared.pHasContent vector.
46033 **
46034 ** This function is called when a free-list leaf page is removed from the
46035 ** free-list for reuse. It returns false if it is safe to retrieve the
46036 ** page from the pager layer with the 'no-content' flag set. True otherwise.
46037 */
46038 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
46039   Bitvec *p = pBt->pHasContent;
46040   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
46041 }
46042
46043 /*
46044 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
46045 ** invoked at the conclusion of each write-transaction.
46046 */
46047 static void btreeClearHasContent(BtShared *pBt){
46048   sqlite3BitvecDestroy(pBt->pHasContent);
46049   pBt->pHasContent = 0;
46050 }
46051
46052 /*
46053 ** Save the current cursor position in the variables BtCursor.nKey 
46054 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
46055 **
46056 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
46057 ** prior to calling this routine.  
46058 */
46059 static int saveCursorPosition(BtCursor *pCur){
46060   int rc;
46061
46062   assert( CURSOR_VALID==pCur->eState );
46063   assert( 0==pCur->pKey );
46064   assert( cursorHoldsMutex(pCur) );
46065
46066   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
46067   assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
46068
46069   /* If this is an intKey table, then the above call to BtreeKeySize()
46070   ** stores the integer key in pCur->nKey. In this case this value is
46071   ** all that is required. Otherwise, if pCur is not open on an intKey
46072   ** table, then malloc space for and store the pCur->nKey bytes of key 
46073   ** data.
46074   */
46075   if( 0==pCur->apPage[0]->intKey ){
46076     void *pKey = sqlite3Malloc( (int)pCur->nKey );
46077     if( pKey ){
46078       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
46079       if( rc==SQLITE_OK ){
46080         pCur->pKey = pKey;
46081       }else{
46082         sqlite3_free(pKey);
46083       }
46084     }else{
46085       rc = SQLITE_NOMEM;
46086     }
46087   }
46088   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
46089
46090   if( rc==SQLITE_OK ){
46091     int i;
46092     for(i=0; i<=pCur->iPage; i++){
46093       releasePage(pCur->apPage[i]);
46094       pCur->apPage[i] = 0;
46095     }
46096     pCur->iPage = -1;
46097     pCur->eState = CURSOR_REQUIRESEEK;
46098   }
46099
46100   invalidateOverflowCache(pCur);
46101   return rc;
46102 }
46103
46104 /*
46105 ** Save the positions of all cursors (except pExcept) that are open on
46106 ** the table  with root-page iRoot. Usually, this is called just before cursor
46107 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
46108 */
46109 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
46110   BtCursor *p;
46111   assert( sqlite3_mutex_held(pBt->mutex) );
46112   assert( pExcept==0 || pExcept->pBt==pBt );
46113   for(p=pBt->pCursor; p; p=p->pNext){
46114     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) && 
46115         p->eState==CURSOR_VALID ){
46116       int rc = saveCursorPosition(p);
46117       if( SQLITE_OK!=rc ){
46118         return rc;
46119       }
46120     }
46121   }
46122   return SQLITE_OK;
46123 }
46124
46125 /*
46126 ** Clear the current cursor position.
46127 */
46128 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
46129   assert( cursorHoldsMutex(pCur) );
46130   sqlite3_free(pCur->pKey);
46131   pCur->pKey = 0;
46132   pCur->eState = CURSOR_INVALID;
46133 }
46134
46135 /*
46136 ** In this version of BtreeMoveto, pKey is a packed index record
46137 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
46138 ** record and then call BtreeMovetoUnpacked() to do the work.
46139 */
46140 static int btreeMoveto(
46141   BtCursor *pCur,     /* Cursor open on the btree to be searched */
46142   const void *pKey,   /* Packed key if the btree is an index */
46143   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
46144   int bias,           /* Bias search to the high end */
46145   int *pRes           /* Write search results here */
46146 ){
46147   int rc;                    /* Status code */
46148   UnpackedRecord *pIdxKey;   /* Unpacked index key */
46149   char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
46150
46151   if( pKey ){
46152     assert( nKey==(i64)(int)nKey );
46153     pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
46154                                       aSpace, sizeof(aSpace));
46155     if( pIdxKey==0 ) return SQLITE_NOMEM;
46156   }else{
46157     pIdxKey = 0;
46158   }
46159   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
46160   if( pKey ){
46161     sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
46162   }
46163   return rc;
46164 }
46165
46166 /*
46167 ** Restore the cursor to the position it was in (or as close to as possible)
46168 ** when saveCursorPosition() was called. Note that this call deletes the 
46169 ** saved position info stored by saveCursorPosition(), so there can be
46170 ** at most one effective restoreCursorPosition() call after each 
46171 ** saveCursorPosition().
46172 */
46173 static int btreeRestoreCursorPosition(BtCursor *pCur){
46174   int rc;
46175   assert( cursorHoldsMutex(pCur) );
46176   assert( pCur->eState>=CURSOR_REQUIRESEEK );
46177   if( pCur->eState==CURSOR_FAULT ){
46178     return pCur->skipNext;
46179   }
46180   pCur->eState = CURSOR_INVALID;
46181   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
46182   if( rc==SQLITE_OK ){
46183     sqlite3_free(pCur->pKey);
46184     pCur->pKey = 0;
46185     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
46186   }
46187   return rc;
46188 }
46189
46190 #define restoreCursorPosition(p) \
46191   (p->eState>=CURSOR_REQUIRESEEK ? \
46192          btreeRestoreCursorPosition(p) : \
46193          SQLITE_OK)
46194
46195 /*
46196 ** Determine whether or not a cursor has moved from the position it
46197 ** was last placed at.  Cursors can move when the row they are pointing
46198 ** at is deleted out from under them.
46199 **
46200 ** This routine returns an error code if something goes wrong.  The
46201 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
46202 */
46203 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
46204   int rc;
46205
46206   rc = restoreCursorPosition(pCur);
46207   if( rc ){
46208     *pHasMoved = 1;
46209     return rc;
46210   }
46211   if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
46212     *pHasMoved = 1;
46213   }else{
46214     *pHasMoved = 0;
46215   }
46216   return SQLITE_OK;
46217 }
46218
46219 #ifndef SQLITE_OMIT_AUTOVACUUM
46220 /*
46221 ** Given a page number of a regular database page, return the page
46222 ** number for the pointer-map page that contains the entry for the
46223 ** input page number.
46224 **
46225 ** Return 0 (not a valid page) for pgno==1 since there is
46226 ** no pointer map associated with page 1.  The integrity_check logic
46227 ** requires that ptrmapPageno(*,1)!=1.
46228 */
46229 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
46230   int nPagesPerMapPage;
46231   Pgno iPtrMap, ret;
46232   assert( sqlite3_mutex_held(pBt->mutex) );
46233   if( pgno<2 ) return 0;
46234   nPagesPerMapPage = (pBt->usableSize/5)+1;
46235   iPtrMap = (pgno-2)/nPagesPerMapPage;
46236   ret = (iPtrMap*nPagesPerMapPage) + 2; 
46237   if( ret==PENDING_BYTE_PAGE(pBt) ){
46238     ret++;
46239   }
46240   return ret;
46241 }
46242
46243 /*
46244 ** Write an entry into the pointer map.
46245 **
46246 ** This routine updates the pointer map entry for page number 'key'
46247 ** so that it maps to type 'eType' and parent page number 'pgno'.
46248 **
46249 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
46250 ** a no-op.  If an error occurs, the appropriate error code is written
46251 ** into *pRC.
46252 */
46253 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
46254   DbPage *pDbPage;  /* The pointer map page */
46255   u8 *pPtrmap;      /* The pointer map data */
46256   Pgno iPtrmap;     /* The pointer map page number */
46257   int offset;       /* Offset in pointer map page */
46258   int rc;           /* Return code from subfunctions */
46259
46260   if( *pRC ) return;
46261
46262   assert( sqlite3_mutex_held(pBt->mutex) );
46263   /* The master-journal page number must never be used as a pointer map page */
46264   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
46265
46266   assert( pBt->autoVacuum );
46267   if( key==0 ){
46268     *pRC = SQLITE_CORRUPT_BKPT;
46269     return;
46270   }
46271   iPtrmap = PTRMAP_PAGENO(pBt, key);
46272   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
46273   if( rc!=SQLITE_OK ){
46274     *pRC = rc;
46275     return;
46276   }
46277   offset = PTRMAP_PTROFFSET(iPtrmap, key);
46278   if( offset<0 ){
46279     *pRC = SQLITE_CORRUPT_BKPT;
46280     goto ptrmap_exit;
46281   }
46282   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
46283
46284   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
46285     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
46286     *pRC= rc = sqlite3PagerWrite(pDbPage);
46287     if( rc==SQLITE_OK ){
46288       pPtrmap[offset] = eType;
46289       put4byte(&pPtrmap[offset+1], parent);
46290     }
46291   }
46292
46293 ptrmap_exit:
46294   sqlite3PagerUnref(pDbPage);
46295 }
46296
46297 /*
46298 ** Read an entry from the pointer map.
46299 **
46300 ** This routine retrieves the pointer map entry for page 'key', writing
46301 ** the type and parent page number to *pEType and *pPgno respectively.
46302 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
46303 */
46304 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
46305   DbPage *pDbPage;   /* The pointer map page */
46306   int iPtrmap;       /* Pointer map page index */
46307   u8 *pPtrmap;       /* Pointer map page data */
46308   int offset;        /* Offset of entry in pointer map */
46309   int rc;
46310
46311   assert( sqlite3_mutex_held(pBt->mutex) );
46312
46313   iPtrmap = PTRMAP_PAGENO(pBt, key);
46314   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
46315   if( rc!=0 ){
46316     return rc;
46317   }
46318   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
46319
46320   offset = PTRMAP_PTROFFSET(iPtrmap, key);
46321   assert( pEType!=0 );
46322   *pEType = pPtrmap[offset];
46323   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
46324
46325   sqlite3PagerUnref(pDbPage);
46326   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
46327   return SQLITE_OK;
46328 }
46329
46330 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
46331   #define ptrmapPut(w,x,y,z,rc)
46332   #define ptrmapGet(w,x,y,z) SQLITE_OK
46333   #define ptrmapPutOvflPtr(x, y, rc)
46334 #endif
46335
46336 /*
46337 ** Given a btree page and a cell index (0 means the first cell on
46338 ** the page, 1 means the second cell, and so forth) return a pointer
46339 ** to the cell content.
46340 **
46341 ** This routine works only for pages that do not contain overflow cells.
46342 */
46343 #define findCell(P,I) \
46344   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
46345
46346 /*
46347 ** This a more complex version of findCell() that works for
46348 ** pages that do contain overflow cells.
46349 */
46350 static u8 *findOverflowCell(MemPage *pPage, int iCell){
46351   int i;
46352   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46353   for(i=pPage->nOverflow-1; i>=0; i--){
46354     int k;
46355     struct _OvflCell *pOvfl;
46356     pOvfl = &pPage->aOvfl[i];
46357     k = pOvfl->idx;
46358     if( k<=iCell ){
46359       if( k==iCell ){
46360         return pOvfl->pCell;
46361       }
46362       iCell--;
46363     }
46364   }
46365   return findCell(pPage, iCell);
46366 }
46367
46368 /*
46369 ** Parse a cell content block and fill in the CellInfo structure.  There
46370 ** are two versions of this function.  btreeParseCell() takes a 
46371 ** cell index as the second argument and btreeParseCellPtr() 
46372 ** takes a pointer to the body of the cell as its second argument.
46373 **
46374 ** Within this file, the parseCell() macro can be called instead of
46375 ** btreeParseCellPtr(). Using some compilers, this will be faster.
46376 */
46377 static void btreeParseCellPtr(
46378   MemPage *pPage,         /* Page containing the cell */
46379   u8 *pCell,              /* Pointer to the cell text. */
46380   CellInfo *pInfo         /* Fill in this structure */
46381 ){
46382   u16 n;                  /* Number bytes in cell content header */
46383   u32 nPayload;           /* Number of bytes of cell payload */
46384
46385   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46386
46387   pInfo->pCell = pCell;
46388   assert( pPage->leaf==0 || pPage->leaf==1 );
46389   n = pPage->childPtrSize;
46390   assert( n==4-4*pPage->leaf );
46391   if( pPage->intKey ){
46392     if( pPage->hasData ){
46393       n += getVarint32(&pCell[n], nPayload);
46394     }else{
46395       nPayload = 0;
46396     }
46397     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
46398     pInfo->nData = nPayload;
46399   }else{
46400     pInfo->nData = 0;
46401     n += getVarint32(&pCell[n], nPayload);
46402     pInfo->nKey = nPayload;
46403   }
46404   pInfo->nPayload = nPayload;
46405   pInfo->nHeader = n;
46406   testcase( nPayload==pPage->maxLocal );
46407   testcase( nPayload==pPage->maxLocal+1 );
46408   if( likely(nPayload<=pPage->maxLocal) ){
46409     /* This is the (easy) common case where the entire payload fits
46410     ** on the local page.  No overflow is required.
46411     */
46412     if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
46413     pInfo->nLocal = (u16)nPayload;
46414     pInfo->iOverflow = 0;
46415   }else{
46416     /* If the payload will not fit completely on the local page, we have
46417     ** to decide how much to store locally and how much to spill onto
46418     ** overflow pages.  The strategy is to minimize the amount of unused
46419     ** space on overflow pages while keeping the amount of local storage
46420     ** in between minLocal and maxLocal.
46421     **
46422     ** Warning:  changing the way overflow payload is distributed in any
46423     ** way will result in an incompatible file format.
46424     */
46425     int minLocal;  /* Minimum amount of payload held locally */
46426     int maxLocal;  /* Maximum amount of payload held locally */
46427     int surplus;   /* Overflow payload available for local storage */
46428
46429     minLocal = pPage->minLocal;
46430     maxLocal = pPage->maxLocal;
46431     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
46432     testcase( surplus==maxLocal );
46433     testcase( surplus==maxLocal+1 );
46434     if( surplus <= maxLocal ){
46435       pInfo->nLocal = (u16)surplus;
46436     }else{
46437       pInfo->nLocal = (u16)minLocal;
46438     }
46439     pInfo->iOverflow = (u16)(pInfo->nLocal + n);
46440     pInfo->nSize = pInfo->iOverflow + 4;
46441   }
46442 }
46443 #define parseCell(pPage, iCell, pInfo) \
46444   btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
46445 static void btreeParseCell(
46446   MemPage *pPage,         /* Page containing the cell */
46447   int iCell,              /* The cell index.  First cell is 0 */
46448   CellInfo *pInfo         /* Fill in this structure */
46449 ){
46450   parseCell(pPage, iCell, pInfo);
46451 }
46452
46453 /*
46454 ** Compute the total number of bytes that a Cell needs in the cell
46455 ** data area of the btree-page.  The return number includes the cell
46456 ** data header and the local payload, but not any overflow page or
46457 ** the space used by the cell pointer.
46458 */
46459 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
46460   u8 *pIter = &pCell[pPage->childPtrSize];
46461   u32 nSize;
46462
46463 #ifdef SQLITE_DEBUG
46464   /* The value returned by this function should always be the same as
46465   ** the (CellInfo.nSize) value found by doing a full parse of the
46466   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
46467   ** this function verifies that this invariant is not violated. */
46468   CellInfo debuginfo;
46469   btreeParseCellPtr(pPage, pCell, &debuginfo);
46470 #endif
46471
46472   if( pPage->intKey ){
46473     u8 *pEnd;
46474     if( pPage->hasData ){
46475       pIter += getVarint32(pIter, nSize);
46476     }else{
46477       nSize = 0;
46478     }
46479
46480     /* pIter now points at the 64-bit integer key value, a variable length 
46481     ** integer. The following block moves pIter to point at the first byte
46482     ** past the end of the key value. */
46483     pEnd = &pIter[9];
46484     while( (*pIter++)&0x80 && pIter<pEnd );
46485   }else{
46486     pIter += getVarint32(pIter, nSize);
46487   }
46488
46489   testcase( nSize==pPage->maxLocal );
46490   testcase( nSize==pPage->maxLocal+1 );
46491   if( nSize>pPage->maxLocal ){
46492     int minLocal = pPage->minLocal;
46493     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
46494     testcase( nSize==pPage->maxLocal );
46495     testcase( nSize==pPage->maxLocal+1 );
46496     if( nSize>pPage->maxLocal ){
46497       nSize = minLocal;
46498     }
46499     nSize += 4;
46500   }
46501   nSize += (u32)(pIter - pCell);
46502
46503   /* The minimum size of any cell is 4 bytes. */
46504   if( nSize<4 ){
46505     nSize = 4;
46506   }
46507
46508   assert( nSize==debuginfo.nSize );
46509   return (u16)nSize;
46510 }
46511
46512 #ifdef SQLITE_DEBUG
46513 /* This variation on cellSizePtr() is used inside of assert() statements
46514 ** only. */
46515 static u16 cellSize(MemPage *pPage, int iCell){
46516   return cellSizePtr(pPage, findCell(pPage, iCell));
46517 }
46518 #endif
46519
46520 #ifndef SQLITE_OMIT_AUTOVACUUM
46521 /*
46522 ** If the cell pCell, part of page pPage contains a pointer
46523 ** to an overflow page, insert an entry into the pointer-map
46524 ** for the overflow page.
46525 */
46526 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
46527   CellInfo info;
46528   if( *pRC ) return;
46529   assert( pCell!=0 );
46530   btreeParseCellPtr(pPage, pCell, &info);
46531   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
46532   if( info.iOverflow ){
46533     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
46534     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
46535   }
46536 }
46537 #endif
46538
46539
46540 /*
46541 ** Defragment the page given.  All Cells are moved to the
46542 ** end of the page and all free space is collected into one
46543 ** big FreeBlk that occurs in between the header and cell
46544 ** pointer array and the cell content area.
46545 */
46546 static int defragmentPage(MemPage *pPage){
46547   int i;                     /* Loop counter */
46548   int pc;                    /* Address of a i-th cell */
46549   int hdr;                   /* Offset to the page header */
46550   int size;                  /* Size of a cell */
46551   int usableSize;            /* Number of usable bytes on a page */
46552   int cellOffset;            /* Offset to the cell pointer array */
46553   int cbrk;                  /* Offset to the cell content area */
46554   int nCell;                 /* Number of cells on the page */
46555   unsigned char *data;       /* The page data */
46556   unsigned char *temp;       /* Temp area for cell content */
46557   int iCellFirst;            /* First allowable cell index */
46558   int iCellLast;             /* Last possible cell index */
46559
46560
46561   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
46562   assert( pPage->pBt!=0 );
46563   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
46564   assert( pPage->nOverflow==0 );
46565   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46566   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
46567   data = pPage->aData;
46568   hdr = pPage->hdrOffset;
46569   cellOffset = pPage->cellOffset;
46570   nCell = pPage->nCell;
46571   assert( nCell==get2byte(&data[hdr+3]) );
46572   usableSize = pPage->pBt->usableSize;
46573   cbrk = get2byte(&data[hdr+5]);
46574   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
46575   cbrk = usableSize;
46576   iCellFirst = cellOffset + 2*nCell;
46577   iCellLast = usableSize - 4;
46578   for(i=0; i<nCell; i++){
46579     u8 *pAddr;     /* The i-th cell pointer */
46580     pAddr = &data[cellOffset + i*2];
46581     pc = get2byte(pAddr);
46582     testcase( pc==iCellFirst );
46583     testcase( pc==iCellLast );
46584 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
46585     /* These conditions have already been verified in btreeInitPage()
46586     ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined 
46587     */
46588     if( pc<iCellFirst || pc>iCellLast ){
46589       return SQLITE_CORRUPT_BKPT;
46590     }
46591 #endif
46592     assert( pc>=iCellFirst && pc<=iCellLast );
46593     size = cellSizePtr(pPage, &temp[pc]);
46594     cbrk -= size;
46595 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
46596     if( cbrk<iCellFirst ){
46597       return SQLITE_CORRUPT_BKPT;
46598     }
46599 #else
46600     if( cbrk<iCellFirst || pc+size>usableSize ){
46601       return SQLITE_CORRUPT_BKPT;
46602     }
46603 #endif
46604     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
46605     testcase( cbrk+size==usableSize );
46606     testcase( pc+size==usableSize );
46607     memcpy(&data[cbrk], &temp[pc], size);
46608     put2byte(pAddr, cbrk);
46609   }
46610   assert( cbrk>=iCellFirst );
46611   put2byte(&data[hdr+5], cbrk);
46612   data[hdr+1] = 0;
46613   data[hdr+2] = 0;
46614   data[hdr+7] = 0;
46615   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
46616   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
46617   if( cbrk-iCellFirst!=pPage->nFree ){
46618     return SQLITE_CORRUPT_BKPT;
46619   }
46620   return SQLITE_OK;
46621 }
46622
46623 /*
46624 ** Allocate nByte bytes of space from within the B-Tree page passed
46625 ** as the first argument. Write into *pIdx the index into pPage->aData[]
46626 ** of the first byte of allocated space. Return either SQLITE_OK or
46627 ** an error code (usually SQLITE_CORRUPT).
46628 **
46629 ** The caller guarantees that there is sufficient space to make the
46630 ** allocation.  This routine might need to defragment in order to bring
46631 ** all the space together, however.  This routine will avoid using
46632 ** the first two bytes past the cell pointer area since presumably this
46633 ** allocation is being made in order to insert a new cell, so we will
46634 ** also end up needing a new cell pointer.
46635 */
46636 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
46637   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
46638   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
46639   int nFrag;                           /* Number of fragmented bytes on pPage */
46640   int top;                             /* First byte of cell content area */
46641   int gap;        /* First byte of gap between cell pointers and cell content */
46642   int rc;         /* Integer return code */
46643   int usableSize; /* Usable size of the page */
46644   
46645   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
46646   assert( pPage->pBt );
46647   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46648   assert( nByte>=0 );  /* Minimum cell size is 4 */
46649   assert( pPage->nFree>=nByte );
46650   assert( pPage->nOverflow==0 );
46651   usableSize = pPage->pBt->usableSize;
46652   assert( nByte < usableSize-8 );
46653
46654   nFrag = data[hdr+7];
46655   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
46656   gap = pPage->cellOffset + 2*pPage->nCell;
46657   top = get2byteNotZero(&data[hdr+5]);
46658   if( gap>top ) return SQLITE_CORRUPT_BKPT;
46659   testcase( gap+2==top );
46660   testcase( gap+1==top );
46661   testcase( gap==top );
46662
46663   if( nFrag>=60 ){
46664     /* Always defragment highly fragmented pages */
46665     rc = defragmentPage(pPage);
46666     if( rc ) return rc;
46667     top = get2byteNotZero(&data[hdr+5]);
46668   }else if( gap+2<=top ){
46669     /* Search the freelist looking for a free slot big enough to satisfy 
46670     ** the request. The allocation is made from the first free slot in 
46671     ** the list that is large enough to accomadate it.
46672     */
46673     int pc, addr;
46674     for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
46675       int size;            /* Size of the free slot */
46676       if( pc>usableSize-4 || pc<addr+4 ){
46677         return SQLITE_CORRUPT_BKPT;
46678       }
46679       size = get2byte(&data[pc+2]);
46680       if( size>=nByte ){
46681         int x = size - nByte;
46682         testcase( x==4 );
46683         testcase( x==3 );
46684         if( x<4 ){
46685           /* Remove the slot from the free-list. Update the number of
46686           ** fragmented bytes within the page. */
46687           memcpy(&data[addr], &data[pc], 2);
46688           data[hdr+7] = (u8)(nFrag + x);
46689         }else if( size+pc > usableSize ){
46690           return SQLITE_CORRUPT_BKPT;
46691         }else{
46692           /* The slot remains on the free-list. Reduce its size to account
46693           ** for the portion used by the new allocation. */
46694           put2byte(&data[pc+2], x);
46695         }
46696         *pIdx = pc + x;
46697         return SQLITE_OK;
46698       }
46699     }
46700   }
46701
46702   /* Check to make sure there is enough space in the gap to satisfy
46703   ** the allocation.  If not, defragment.
46704   */
46705   testcase( gap+2+nByte==top );
46706   if( gap+2+nByte>top ){
46707     rc = defragmentPage(pPage);
46708     if( rc ) return rc;
46709     top = get2byteNotZero(&data[hdr+5]);
46710     assert( gap+nByte<=top );
46711   }
46712
46713
46714   /* Allocate memory from the gap in between the cell pointer array
46715   ** and the cell content area.  The btreeInitPage() call has already
46716   ** validated the freelist.  Given that the freelist is valid, there
46717   ** is no way that the allocation can extend off the end of the page.
46718   ** The assert() below verifies the previous sentence.
46719   */
46720   top -= nByte;
46721   put2byte(&data[hdr+5], top);
46722   assert( top+nByte <= pPage->pBt->usableSize );
46723   *pIdx = top;
46724   return SQLITE_OK;
46725 }
46726
46727 /*
46728 ** Return a section of the pPage->aData to the freelist.
46729 ** The first byte of the new free block is pPage->aDisk[start]
46730 ** and the size of the block is "size" bytes.
46731 **
46732 ** Most of the effort here is involved in coalesing adjacent
46733 ** free blocks into a single big free block.
46734 */
46735 static int freeSpace(MemPage *pPage, int start, int size){
46736   int addr, pbegin, hdr;
46737   int iLast;                        /* Largest possible freeblock offset */
46738   unsigned char *data = pPage->aData;
46739
46740   assert( pPage->pBt!=0 );
46741   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
46742   assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
46743   assert( (start + size)<=pPage->pBt->usableSize );
46744   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46745   assert( size>=0 );   /* Minimum cell size is 4 */
46746
46747   if( pPage->pBt->secureDelete ){
46748     /* Overwrite deleted information with zeros when the secure_delete
46749     ** option is enabled */
46750     memset(&data[start], 0, size);
46751   }
46752
46753   /* Add the space back into the linked list of freeblocks.  Note that
46754   ** even though the freeblock list was checked by btreeInitPage(),
46755   ** btreeInitPage() did not detect overlapping cells or
46756   ** freeblocks that overlapped cells.   Nor does it detect when the
46757   ** cell content area exceeds the value in the page header.  If these
46758   ** situations arise, then subsequent insert operations might corrupt
46759   ** the freelist.  So we do need to check for corruption while scanning
46760   ** the freelist.
46761   */
46762   hdr = pPage->hdrOffset;
46763   addr = hdr + 1;
46764   iLast = pPage->pBt->usableSize - 4;
46765   assert( start<=iLast );
46766   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
46767     if( pbegin<addr+4 ){
46768       return SQLITE_CORRUPT_BKPT;
46769     }
46770     addr = pbegin;
46771   }
46772   if( pbegin>iLast ){
46773     return SQLITE_CORRUPT_BKPT;
46774   }
46775   assert( pbegin>addr || pbegin==0 );
46776   put2byte(&data[addr], start);
46777   put2byte(&data[start], pbegin);
46778   put2byte(&data[start+2], size);
46779   pPage->nFree = pPage->nFree + (u16)size;
46780
46781   /* Coalesce adjacent free blocks */
46782   addr = hdr + 1;
46783   while( (pbegin = get2byte(&data[addr]))>0 ){
46784     int pnext, psize, x;
46785     assert( pbegin>addr );
46786     assert( pbegin<=pPage->pBt->usableSize-4 );
46787     pnext = get2byte(&data[pbegin]);
46788     psize = get2byte(&data[pbegin+2]);
46789     if( pbegin + psize + 3 >= pnext && pnext>0 ){
46790       int frag = pnext - (pbegin+psize);
46791       if( (frag<0) || (frag>(int)data[hdr+7]) ){
46792         return SQLITE_CORRUPT_BKPT;
46793       }
46794       data[hdr+7] -= (u8)frag;
46795       x = get2byte(&data[pnext]);
46796       put2byte(&data[pbegin], x);
46797       x = pnext + get2byte(&data[pnext+2]) - pbegin;
46798       put2byte(&data[pbegin+2], x);
46799     }else{
46800       addr = pbegin;
46801     }
46802   }
46803
46804   /* If the cell content area begins with a freeblock, remove it. */
46805   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
46806     int top;
46807     pbegin = get2byte(&data[hdr+1]);
46808     memcpy(&data[hdr+1], &data[pbegin], 2);
46809     top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
46810     put2byte(&data[hdr+5], top);
46811   }
46812   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
46813   return SQLITE_OK;
46814 }
46815
46816 /*
46817 ** Decode the flags byte (the first byte of the header) for a page
46818 ** and initialize fields of the MemPage structure accordingly.
46819 **
46820 ** Only the following combinations are supported.  Anything different
46821 ** indicates a corrupt database files:
46822 **
46823 **         PTF_ZERODATA
46824 **         PTF_ZERODATA | PTF_LEAF
46825 **         PTF_LEAFDATA | PTF_INTKEY
46826 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
46827 */
46828 static int decodeFlags(MemPage *pPage, int flagByte){
46829   BtShared *pBt;     /* A copy of pPage->pBt */
46830
46831   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
46832   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46833   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
46834   flagByte &= ~PTF_LEAF;
46835   pPage->childPtrSize = 4-4*pPage->leaf;
46836   pBt = pPage->pBt;
46837   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
46838     pPage->intKey = 1;
46839     pPage->hasData = pPage->leaf;
46840     pPage->maxLocal = pBt->maxLeaf;
46841     pPage->minLocal = pBt->minLeaf;
46842   }else if( flagByte==PTF_ZERODATA ){
46843     pPage->intKey = 0;
46844     pPage->hasData = 0;
46845     pPage->maxLocal = pBt->maxLocal;
46846     pPage->minLocal = pBt->minLocal;
46847   }else{
46848     return SQLITE_CORRUPT_BKPT;
46849   }
46850   return SQLITE_OK;
46851 }
46852
46853 /*
46854 ** Initialize the auxiliary information for a disk block.
46855 **
46856 ** Return SQLITE_OK on success.  If we see that the page does
46857 ** not contain a well-formed database page, then return 
46858 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
46859 ** guarantee that the page is well-formed.  It only shows that
46860 ** we failed to detect any corruption.
46861 */
46862 static int btreeInitPage(MemPage *pPage){
46863
46864   assert( pPage->pBt!=0 );
46865   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46866   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
46867   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
46868   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
46869
46870   if( !pPage->isInit ){
46871     u16 pc;            /* Address of a freeblock within pPage->aData[] */
46872     u8 hdr;            /* Offset to beginning of page header */
46873     u8 *data;          /* Equal to pPage->aData */
46874     BtShared *pBt;        /* The main btree structure */
46875     int usableSize;    /* Amount of usable space on each page */
46876     u16 cellOffset;    /* Offset from start of page to first cell pointer */
46877     int nFree;         /* Number of unused bytes on the page */
46878     int top;           /* First byte of the cell content area */
46879     int iCellFirst;    /* First allowable cell or freeblock offset */
46880     int iCellLast;     /* Last possible cell or freeblock offset */
46881
46882     pBt = pPage->pBt;
46883
46884     hdr = pPage->hdrOffset;
46885     data = pPage->aData;
46886     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
46887     assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
46888     pPage->maskPage = (u16)(pBt->pageSize - 1);
46889     pPage->nOverflow = 0;
46890     usableSize = pBt->usableSize;
46891     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
46892     top = get2byteNotZero(&data[hdr+5]);
46893     pPage->nCell = get2byte(&data[hdr+3]);
46894     if( pPage->nCell>MX_CELL(pBt) ){
46895       /* To many cells for a single page.  The page must be corrupt */
46896       return SQLITE_CORRUPT_BKPT;
46897     }
46898     testcase( pPage->nCell==MX_CELL(pBt) );
46899
46900     /* A malformed database page might cause us to read past the end
46901     ** of page when parsing a cell.  
46902     **
46903     ** The following block of code checks early to see if a cell extends
46904     ** past the end of a page boundary and causes SQLITE_CORRUPT to be 
46905     ** returned if it does.
46906     */
46907     iCellFirst = cellOffset + 2*pPage->nCell;
46908     iCellLast = usableSize - 4;
46909 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
46910     {
46911       int i;            /* Index into the cell pointer array */
46912       int sz;           /* Size of a cell */
46913
46914       if( !pPage->leaf ) iCellLast--;
46915       for(i=0; i<pPage->nCell; i++){
46916         pc = get2byte(&data[cellOffset+i*2]);
46917         testcase( pc==iCellFirst );
46918         testcase( pc==iCellLast );
46919         if( pc<iCellFirst || pc>iCellLast ){
46920           return SQLITE_CORRUPT_BKPT;
46921         }
46922         sz = cellSizePtr(pPage, &data[pc]);
46923         testcase( pc+sz==usableSize );
46924         if( pc+sz>usableSize ){
46925           return SQLITE_CORRUPT_BKPT;
46926         }
46927       }
46928       if( !pPage->leaf ) iCellLast++;
46929     }  
46930 #endif
46931
46932     /* Compute the total free space on the page */
46933     pc = get2byte(&data[hdr+1]);
46934     nFree = data[hdr+7] + top;
46935     while( pc>0 ){
46936       u16 next, size;
46937       if( pc<iCellFirst || pc>iCellLast ){
46938         /* Start of free block is off the page */
46939         return SQLITE_CORRUPT_BKPT; 
46940       }
46941       next = get2byte(&data[pc]);
46942       size = get2byte(&data[pc+2]);
46943       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
46944         /* Free blocks must be in ascending order. And the last byte of
46945         ** the free-block must lie on the database page.  */
46946         return SQLITE_CORRUPT_BKPT; 
46947       }
46948       nFree = nFree + size;
46949       pc = next;
46950     }
46951
46952     /* At this point, nFree contains the sum of the offset to the start
46953     ** of the cell-content area plus the number of free bytes within
46954     ** the cell-content area. If this is greater than the usable-size
46955     ** of the page, then the page must be corrupted. This check also
46956     ** serves to verify that the offset to the start of the cell-content
46957     ** area, according to the page header, lies within the page.
46958     */
46959     if( nFree>usableSize ){
46960       return SQLITE_CORRUPT_BKPT; 
46961     }
46962     pPage->nFree = (u16)(nFree - iCellFirst);
46963     pPage->isInit = 1;
46964   }
46965   return SQLITE_OK;
46966 }
46967
46968 /*
46969 ** Set up a raw page so that it looks like a database page holding
46970 ** no entries.
46971 */
46972 static void zeroPage(MemPage *pPage, int flags){
46973   unsigned char *data = pPage->aData;
46974   BtShared *pBt = pPage->pBt;
46975   u8 hdr = pPage->hdrOffset;
46976   u16 first;
46977
46978   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
46979   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
46980   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
46981   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
46982   assert( sqlite3_mutex_held(pBt->mutex) );
46983   if( pBt->secureDelete ){
46984     memset(&data[hdr], 0, pBt->usableSize - hdr);
46985   }
46986   data[hdr] = (char)flags;
46987   first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
46988   memset(&data[hdr+1], 0, 4);
46989   data[hdr+7] = 0;
46990   put2byte(&data[hdr+5], pBt->usableSize);
46991   pPage->nFree = (u16)(pBt->usableSize - first);
46992   decodeFlags(pPage, flags);
46993   pPage->hdrOffset = hdr;
46994   pPage->cellOffset = first;
46995   pPage->nOverflow = 0;
46996   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
46997   pPage->maskPage = (u16)(pBt->pageSize - 1);
46998   pPage->nCell = 0;
46999   pPage->isInit = 1;
47000 }
47001
47002
47003 /*
47004 ** Convert a DbPage obtained from the pager into a MemPage used by
47005 ** the btree layer.
47006 */
47007 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
47008   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
47009   pPage->aData = sqlite3PagerGetData(pDbPage);
47010   pPage->pDbPage = pDbPage;
47011   pPage->pBt = pBt;
47012   pPage->pgno = pgno;
47013   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
47014   return pPage; 
47015 }
47016
47017 /*
47018 ** Get a page from the pager.  Initialize the MemPage.pBt and
47019 ** MemPage.aData elements if needed.
47020 **
47021 ** If the noContent flag is set, it means that we do not care about
47022 ** the content of the page at this time.  So do not go to the disk
47023 ** to fetch the content.  Just fill in the content with zeros for now.
47024 ** If in the future we call sqlite3PagerWrite() on this page, that
47025 ** means we have started to be concerned about content and the disk
47026 ** read should occur at that point.
47027 */
47028 static int btreeGetPage(
47029   BtShared *pBt,       /* The btree */
47030   Pgno pgno,           /* Number of the page to fetch */
47031   MemPage **ppPage,    /* Return the page in this parameter */
47032   int noContent        /* Do not load page content if true */
47033 ){
47034   int rc;
47035   DbPage *pDbPage;
47036
47037   assert( sqlite3_mutex_held(pBt->mutex) );
47038   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
47039   if( rc ) return rc;
47040   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
47041   return SQLITE_OK;
47042 }
47043
47044 /*
47045 ** Retrieve a page from the pager cache. If the requested page is not
47046 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
47047 ** MemPage.aData elements if needed.
47048 */
47049 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
47050   DbPage *pDbPage;
47051   assert( sqlite3_mutex_held(pBt->mutex) );
47052   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
47053   if( pDbPage ){
47054     return btreePageFromDbPage(pDbPage, pgno, pBt);
47055   }
47056   return 0;
47057 }
47058
47059 /*
47060 ** Return the size of the database file in pages. If there is any kind of
47061 ** error, return ((unsigned int)-1).
47062 */
47063 static Pgno btreePagecount(BtShared *pBt){
47064   return pBt->nPage;
47065 }
47066 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
47067   assert( sqlite3BtreeHoldsMutex(p) );
47068   assert( ((p->pBt->nPage)&0x8000000)==0 );
47069   return (int)btreePagecount(p->pBt);
47070 }
47071
47072 /*
47073 ** Get a page from the pager and initialize it.  This routine is just a
47074 ** convenience wrapper around separate calls to btreeGetPage() and 
47075 ** btreeInitPage().
47076 **
47077 ** If an error occurs, then the value *ppPage is set to is undefined. It
47078 ** may remain unchanged, or it may be set to an invalid value.
47079 */
47080 static int getAndInitPage(
47081   BtShared *pBt,          /* The database file */
47082   Pgno pgno,           /* Number of the page to get */
47083   MemPage **ppPage     /* Write the page pointer here */
47084 ){
47085   int rc;
47086   assert( sqlite3_mutex_held(pBt->mutex) );
47087
47088   if( pgno>btreePagecount(pBt) ){
47089     rc = SQLITE_CORRUPT_BKPT;
47090   }else{
47091     rc = btreeGetPage(pBt, pgno, ppPage, 0);
47092     if( rc==SQLITE_OK ){
47093       rc = btreeInitPage(*ppPage);
47094       if( rc!=SQLITE_OK ){
47095         releasePage(*ppPage);
47096       }
47097     }
47098   }
47099
47100   testcase( pgno==0 );
47101   assert( pgno!=0 || rc==SQLITE_CORRUPT );
47102   return rc;
47103 }
47104
47105 /*
47106 ** Release a MemPage.  This should be called once for each prior
47107 ** call to btreeGetPage.
47108 */
47109 static void releasePage(MemPage *pPage){
47110   if( pPage ){
47111     assert( pPage->aData );
47112     assert( pPage->pBt );
47113     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
47114     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
47115     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
47116     sqlite3PagerUnref(pPage->pDbPage);
47117   }
47118 }
47119
47120 /*
47121 ** During a rollback, when the pager reloads information into the cache
47122 ** so that the cache is restored to its original state at the start of
47123 ** the transaction, for each page restored this routine is called.
47124 **
47125 ** This routine needs to reset the extra data section at the end of the
47126 ** page to agree with the restored data.
47127 */
47128 static void pageReinit(DbPage *pData){
47129   MemPage *pPage;
47130   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
47131   assert( sqlite3PagerPageRefcount(pData)>0 );
47132   if( pPage->isInit ){
47133     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
47134     pPage->isInit = 0;
47135     if( sqlite3PagerPageRefcount(pData)>1 ){
47136       /* pPage might not be a btree page;  it might be an overflow page
47137       ** or ptrmap page or a free page.  In those cases, the following
47138       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
47139       ** But no harm is done by this.  And it is very important that
47140       ** btreeInitPage() be called on every btree page so we make
47141       ** the call for every page that comes in for re-initing. */
47142       btreeInitPage(pPage);
47143     }
47144   }
47145 }
47146
47147 /*
47148 ** Invoke the busy handler for a btree.
47149 */
47150 static int btreeInvokeBusyHandler(void *pArg){
47151   BtShared *pBt = (BtShared*)pArg;
47152   assert( pBt->db );
47153   assert( sqlite3_mutex_held(pBt->db->mutex) );
47154   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
47155 }
47156
47157 /*
47158 ** Open a database file.
47159 ** 
47160 ** zFilename is the name of the database file.  If zFilename is NULL
47161 ** then an ephemeral database is created.  The ephemeral database might
47162 ** be exclusively in memory, or it might use a disk-based memory cache.
47163 ** Either way, the ephemeral database will be automatically deleted 
47164 ** when sqlite3BtreeClose() is called.
47165 **
47166 ** If zFilename is ":memory:" then an in-memory database is created
47167 ** that is automatically destroyed when it is closed.
47168 **
47169 ** The "flags" parameter is a bitmask that might contain bits
47170 ** BTREE_OMIT_JOURNAL and/or BTREE_NO_READLOCK.  The BTREE_NO_READLOCK
47171 ** bit is also set if the SQLITE_NoReadlock flags is set in db->flags.
47172 ** These flags are passed through into sqlite3PagerOpen() and must
47173 ** be the same values as PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK.
47174 **
47175 ** If the database is already opened in the same database connection
47176 ** and we are in shared cache mode, then the open will fail with an
47177 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
47178 ** objects in the same database connection since doing so will lead
47179 ** to problems with locking.
47180 */
47181 SQLITE_PRIVATE int sqlite3BtreeOpen(
47182   const char *zFilename,  /* Name of the file containing the BTree database */
47183   sqlite3 *db,            /* Associated database handle */
47184   Btree **ppBtree,        /* Pointer to new Btree object written here */
47185   int flags,              /* Options */
47186   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
47187 ){
47188   sqlite3_vfs *pVfs;             /* The VFS to use for this btree */
47189   BtShared *pBt = 0;             /* Shared part of btree structure */
47190   Btree *p;                      /* Handle to return */
47191   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
47192   int rc = SQLITE_OK;            /* Result code from this function */
47193   u8 nReserve;                   /* Byte of unused space on each page */
47194   unsigned char zDbHeader[100];  /* Database header content */
47195
47196   /* True if opening an ephemeral, temporary database */
47197   const int isTempDb = zFilename==0 || zFilename[0]==0;
47198
47199   /* Set the variable isMemdb to true for an in-memory database, or 
47200   ** false for a file-based database.
47201   */
47202 #ifdef SQLITE_OMIT_MEMORYDB
47203   const int isMemdb = 0;
47204 #else
47205   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
47206                        || (isTempDb && sqlite3TempInMemory(db));
47207 #endif
47208
47209   assert( db!=0 );
47210   assert( sqlite3_mutex_held(db->mutex) );
47211   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
47212
47213   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
47214   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
47215
47216   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
47217   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
47218
47219   if( db->flags & SQLITE_NoReadlock ){
47220     flags |= BTREE_NO_READLOCK;
47221   }
47222   if( isMemdb ){
47223     flags |= BTREE_MEMORY;
47224   }
47225   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
47226     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
47227   }
47228   pVfs = db->pVfs;
47229   p = sqlite3MallocZero(sizeof(Btree));
47230   if( !p ){
47231     return SQLITE_NOMEM;
47232   }
47233   p->inTrans = TRANS_NONE;
47234   p->db = db;
47235 #ifndef SQLITE_OMIT_SHARED_CACHE
47236   p->lock.pBtree = p;
47237   p->lock.iTable = 1;
47238 #endif
47239
47240 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
47241   /*
47242   ** If this Btree is a candidate for shared cache, try to find an
47243   ** existing BtShared object that we can share with
47244   */
47245   if( isMemdb==0 && isTempDb==0 ){
47246     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
47247       int nFullPathname = pVfs->mxPathname+1;
47248       char *zFullPathname = sqlite3Malloc(nFullPathname);
47249       sqlite3_mutex *mutexShared;
47250       p->sharable = 1;
47251       if( !zFullPathname ){
47252         sqlite3_free(p);
47253         return SQLITE_NOMEM;
47254       }
47255       sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
47256       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
47257       sqlite3_mutex_enter(mutexOpen);
47258       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
47259       sqlite3_mutex_enter(mutexShared);
47260       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
47261         assert( pBt->nRef>0 );
47262         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
47263                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
47264           int iDb;
47265           for(iDb=db->nDb-1; iDb>=0; iDb--){
47266             Btree *pExisting = db->aDb[iDb].pBt;
47267             if( pExisting && pExisting->pBt==pBt ){
47268               sqlite3_mutex_leave(mutexShared);
47269               sqlite3_mutex_leave(mutexOpen);
47270               sqlite3_free(zFullPathname);
47271               sqlite3_free(p);
47272               return SQLITE_CONSTRAINT;
47273             }
47274           }
47275           p->pBt = pBt;
47276           pBt->nRef++;
47277           break;
47278         }
47279       }
47280       sqlite3_mutex_leave(mutexShared);
47281       sqlite3_free(zFullPathname);
47282     }
47283 #ifdef SQLITE_DEBUG
47284     else{
47285       /* In debug mode, we mark all persistent databases as sharable
47286       ** even when they are not.  This exercises the locking code and
47287       ** gives more opportunity for asserts(sqlite3_mutex_held())
47288       ** statements to find locking problems.
47289       */
47290       p->sharable = 1;
47291     }
47292 #endif
47293   }
47294 #endif
47295   if( pBt==0 ){
47296     /*
47297     ** The following asserts make sure that structures used by the btree are
47298     ** the right size.  This is to guard against size changes that result
47299     ** when compiling on a different architecture.
47300     */
47301     assert( sizeof(i64)==8 || sizeof(i64)==4 );
47302     assert( sizeof(u64)==8 || sizeof(u64)==4 );
47303     assert( sizeof(u32)==4 );
47304     assert( sizeof(u16)==2 );
47305     assert( sizeof(Pgno)==4 );
47306   
47307     pBt = sqlite3MallocZero( sizeof(*pBt) );
47308     if( pBt==0 ){
47309       rc = SQLITE_NOMEM;
47310       goto btree_open_out;
47311     }
47312     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
47313                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
47314     if( rc==SQLITE_OK ){
47315       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
47316     }
47317     if( rc!=SQLITE_OK ){
47318       goto btree_open_out;
47319     }
47320     pBt->openFlags = (u8)flags;
47321     pBt->db = db;
47322     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
47323     p->pBt = pBt;
47324   
47325     pBt->pCursor = 0;
47326     pBt->pPage1 = 0;
47327     pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
47328 #ifdef SQLITE_SECURE_DELETE
47329     pBt->secureDelete = 1;
47330 #endif
47331     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
47332     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
47333          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
47334       pBt->pageSize = 0;
47335 #ifndef SQLITE_OMIT_AUTOVACUUM
47336       /* If the magic name ":memory:" will create an in-memory database, then
47337       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
47338       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
47339       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
47340       ** regular file-name. In this case the auto-vacuum applies as per normal.
47341       */
47342       if( zFilename && !isMemdb ){
47343         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
47344         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
47345       }
47346 #endif
47347       nReserve = 0;
47348     }else{
47349       nReserve = zDbHeader[20];
47350       pBt->pageSizeFixed = 1;
47351 #ifndef SQLITE_OMIT_AUTOVACUUM
47352       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
47353       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
47354 #endif
47355     }
47356     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
47357     if( rc ) goto btree_open_out;
47358     pBt->usableSize = pBt->pageSize - nReserve;
47359     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
47360    
47361 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
47362     /* Add the new BtShared object to the linked list sharable BtShareds.
47363     */
47364     if( p->sharable ){
47365       sqlite3_mutex *mutexShared;
47366       pBt->nRef = 1;
47367       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
47368       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
47369         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
47370         if( pBt->mutex==0 ){
47371           rc = SQLITE_NOMEM;
47372           db->mallocFailed = 0;
47373           goto btree_open_out;
47374         }
47375       }
47376       sqlite3_mutex_enter(mutexShared);
47377       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
47378       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
47379       sqlite3_mutex_leave(mutexShared);
47380     }
47381 #endif
47382   }
47383
47384 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
47385   /* If the new Btree uses a sharable pBtShared, then link the new
47386   ** Btree into the list of all sharable Btrees for the same connection.
47387   ** The list is kept in ascending order by pBt address.
47388   */
47389   if( p->sharable ){
47390     int i;
47391     Btree *pSib;
47392     for(i=0; i<db->nDb; i++){
47393       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
47394         while( pSib->pPrev ){ pSib = pSib->pPrev; }
47395         if( p->pBt<pSib->pBt ){
47396           p->pNext = pSib;
47397           p->pPrev = 0;
47398           pSib->pPrev = p;
47399         }else{
47400           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
47401             pSib = pSib->pNext;
47402           }
47403           p->pNext = pSib->pNext;
47404           p->pPrev = pSib;
47405           if( p->pNext ){
47406             p->pNext->pPrev = p;
47407           }
47408           pSib->pNext = p;
47409         }
47410         break;
47411       }
47412     }
47413   }
47414 #endif
47415   *ppBtree = p;
47416
47417 btree_open_out:
47418   if( rc!=SQLITE_OK ){
47419     if( pBt && pBt->pPager ){
47420       sqlite3PagerClose(pBt->pPager);
47421     }
47422     sqlite3_free(pBt);
47423     sqlite3_free(p);
47424     *ppBtree = 0;
47425   }else{
47426     /* If the B-Tree was successfully opened, set the pager-cache size to the
47427     ** default value. Except, when opening on an existing shared pager-cache,
47428     ** do not change the pager-cache size.
47429     */
47430     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
47431       sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
47432     }
47433   }
47434   if( mutexOpen ){
47435     assert( sqlite3_mutex_held(mutexOpen) );
47436     sqlite3_mutex_leave(mutexOpen);
47437   }
47438   return rc;
47439 }
47440
47441 /*
47442 ** Decrement the BtShared.nRef counter.  When it reaches zero,
47443 ** remove the BtShared structure from the sharing list.  Return
47444 ** true if the BtShared.nRef counter reaches zero and return
47445 ** false if it is still positive.
47446 */
47447 static int removeFromSharingList(BtShared *pBt){
47448 #ifndef SQLITE_OMIT_SHARED_CACHE
47449   sqlite3_mutex *pMaster;
47450   BtShared *pList;
47451   int removed = 0;
47452
47453   assert( sqlite3_mutex_notheld(pBt->mutex) );
47454   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
47455   sqlite3_mutex_enter(pMaster);
47456   pBt->nRef--;
47457   if( pBt->nRef<=0 ){
47458     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
47459       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
47460     }else{
47461       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
47462       while( ALWAYS(pList) && pList->pNext!=pBt ){
47463         pList=pList->pNext;
47464       }
47465       if( ALWAYS(pList) ){
47466         pList->pNext = pBt->pNext;
47467       }
47468     }
47469     if( SQLITE_THREADSAFE ){
47470       sqlite3_mutex_free(pBt->mutex);
47471     }
47472     removed = 1;
47473   }
47474   sqlite3_mutex_leave(pMaster);
47475   return removed;
47476 #else
47477   return 1;
47478 #endif
47479 }
47480
47481 /*
47482 ** Make sure pBt->pTmpSpace points to an allocation of 
47483 ** MX_CELL_SIZE(pBt) bytes.
47484 */
47485 static void allocateTempSpace(BtShared *pBt){
47486   if( !pBt->pTmpSpace ){
47487     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
47488   }
47489 }
47490
47491 /*
47492 ** Free the pBt->pTmpSpace allocation
47493 */
47494 static void freeTempSpace(BtShared *pBt){
47495   sqlite3PageFree( pBt->pTmpSpace);
47496   pBt->pTmpSpace = 0;
47497 }
47498
47499 /*
47500 ** Close an open database and invalidate all cursors.
47501 */
47502 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
47503   BtShared *pBt = p->pBt;
47504   BtCursor *pCur;
47505
47506   /* Close all cursors opened via this handle.  */
47507   assert( sqlite3_mutex_held(p->db->mutex) );
47508   sqlite3BtreeEnter(p);
47509   pCur = pBt->pCursor;
47510   while( pCur ){
47511     BtCursor *pTmp = pCur;
47512     pCur = pCur->pNext;
47513     if( pTmp->pBtree==p ){
47514       sqlite3BtreeCloseCursor(pTmp);
47515     }
47516   }
47517
47518   /* Rollback any active transaction and free the handle structure.
47519   ** The call to sqlite3BtreeRollback() drops any table-locks held by
47520   ** this handle.
47521   */
47522   sqlite3BtreeRollback(p);
47523   sqlite3BtreeLeave(p);
47524
47525   /* If there are still other outstanding references to the shared-btree
47526   ** structure, return now. The remainder of this procedure cleans 
47527   ** up the shared-btree.
47528   */
47529   assert( p->wantToLock==0 && p->locked==0 );
47530   if( !p->sharable || removeFromSharingList(pBt) ){
47531     /* The pBt is no longer on the sharing list, so we can access
47532     ** it without having to hold the mutex.
47533     **
47534     ** Clean out and delete the BtShared object.
47535     */
47536     assert( !pBt->pCursor );
47537     sqlite3PagerClose(pBt->pPager);
47538     if( pBt->xFreeSchema && pBt->pSchema ){
47539       pBt->xFreeSchema(pBt->pSchema);
47540     }
47541     sqlite3DbFree(0, pBt->pSchema);
47542     freeTempSpace(pBt);
47543     sqlite3_free(pBt);
47544   }
47545
47546 #ifndef SQLITE_OMIT_SHARED_CACHE
47547   assert( p->wantToLock==0 );
47548   assert( p->locked==0 );
47549   if( p->pPrev ) p->pPrev->pNext = p->pNext;
47550   if( p->pNext ) p->pNext->pPrev = p->pPrev;
47551 #endif
47552
47553   sqlite3_free(p);
47554   return SQLITE_OK;
47555 }
47556
47557 /*
47558 ** Change the limit on the number of pages allowed in the cache.
47559 **
47560 ** The maximum number of cache pages is set to the absolute
47561 ** value of mxPage.  If mxPage is negative, the pager will
47562 ** operate asynchronously - it will not stop to do fsync()s
47563 ** to insure data is written to the disk surface before
47564 ** continuing.  Transactions still work if synchronous is off,
47565 ** and the database cannot be corrupted if this program
47566 ** crashes.  But if the operating system crashes or there is
47567 ** an abrupt power failure when synchronous is off, the database
47568 ** could be left in an inconsistent and unrecoverable state.
47569 ** Synchronous is on by default so database corruption is not
47570 ** normally a worry.
47571 */
47572 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
47573   BtShared *pBt = p->pBt;
47574   assert( sqlite3_mutex_held(p->db->mutex) );
47575   sqlite3BtreeEnter(p);
47576   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
47577   sqlite3BtreeLeave(p);
47578   return SQLITE_OK;
47579 }
47580
47581 /*
47582 ** Change the way data is synced to disk in order to increase or decrease
47583 ** how well the database resists damage due to OS crashes and power
47584 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
47585 ** there is a high probability of damage)  Level 2 is the default.  There
47586 ** is a very low but non-zero probability of damage.  Level 3 reduces the
47587 ** probability of damage to near zero but with a write performance reduction.
47588 */
47589 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
47590 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(
47591   Btree *p,              /* The btree to set the safety level on */
47592   int level,             /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
47593   int fullSync,          /* PRAGMA fullfsync. */
47594   int ckptFullSync       /* PRAGMA checkpoint_fullfync */
47595 ){
47596   BtShared *pBt = p->pBt;
47597   assert( sqlite3_mutex_held(p->db->mutex) );
47598   assert( level>=1 && level<=3 );
47599   sqlite3BtreeEnter(p);
47600   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
47601   sqlite3BtreeLeave(p);
47602   return SQLITE_OK;
47603 }
47604 #endif
47605
47606 /*
47607 ** Return TRUE if the given btree is set to safety level 1.  In other
47608 ** words, return TRUE if no sync() occurs on the disk files.
47609 */
47610 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
47611   BtShared *pBt = p->pBt;
47612   int rc;
47613   assert( sqlite3_mutex_held(p->db->mutex) );  
47614   sqlite3BtreeEnter(p);
47615   assert( pBt && pBt->pPager );
47616   rc = sqlite3PagerNosync(pBt->pPager);
47617   sqlite3BtreeLeave(p);
47618   return rc;
47619 }
47620
47621 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
47622 /*
47623 ** Change the default pages size and the number of reserved bytes per page.
47624 ** Or, if the page size has already been fixed, return SQLITE_READONLY 
47625 ** without changing anything.
47626 **
47627 ** The page size must be a power of 2 between 512 and 65536.  If the page
47628 ** size supplied does not meet this constraint then the page size is not
47629 ** changed.
47630 **
47631 ** Page sizes are constrained to be a power of two so that the region
47632 ** of the database file used for locking (beginning at PENDING_BYTE,
47633 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
47634 ** at the beginning of a page.
47635 **
47636 ** If parameter nReserve is less than zero, then the number of reserved
47637 ** bytes per page is left unchanged.
47638 **
47639 ** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
47640 ** and autovacuum mode can no longer be changed.
47641 */
47642 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
47643   int rc = SQLITE_OK;
47644   BtShared *pBt = p->pBt;
47645   assert( nReserve>=-1 && nReserve<=255 );
47646   sqlite3BtreeEnter(p);
47647   if( pBt->pageSizeFixed ){
47648     sqlite3BtreeLeave(p);
47649     return SQLITE_READONLY;
47650   }
47651   if( nReserve<0 ){
47652     nReserve = pBt->pageSize - pBt->usableSize;
47653   }
47654   assert( nReserve>=0 && nReserve<=255 );
47655   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
47656         ((pageSize-1)&pageSize)==0 ){
47657     assert( (pageSize & 7)==0 );
47658     assert( !pBt->pPage1 && !pBt->pCursor );
47659     pBt->pageSize = (u32)pageSize;
47660     freeTempSpace(pBt);
47661   }
47662   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
47663   pBt->usableSize = pBt->pageSize - (u16)nReserve;
47664   if( iFix ) pBt->pageSizeFixed = 1;
47665   sqlite3BtreeLeave(p);
47666   return rc;
47667 }
47668
47669 /*
47670 ** Return the currently defined page size
47671 */
47672 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
47673   return p->pBt->pageSize;
47674 }
47675
47676 /*
47677 ** Return the number of bytes of space at the end of every page that
47678 ** are intentually left unused.  This is the "reserved" space that is
47679 ** sometimes used by extensions.
47680 */
47681 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
47682   int n;
47683   sqlite3BtreeEnter(p);
47684   n = p->pBt->pageSize - p->pBt->usableSize;
47685   sqlite3BtreeLeave(p);
47686   return n;
47687 }
47688
47689 /*
47690 ** Set the maximum page count for a database if mxPage is positive.
47691 ** No changes are made if mxPage is 0 or negative.
47692 ** Regardless of the value of mxPage, return the maximum page count.
47693 */
47694 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
47695   int n;
47696   sqlite3BtreeEnter(p);
47697   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
47698   sqlite3BtreeLeave(p);
47699   return n;
47700 }
47701
47702 /*
47703 ** Set the secureDelete flag if newFlag is 0 or 1.  If newFlag is -1,
47704 ** then make no changes.  Always return the value of the secureDelete
47705 ** setting after the change.
47706 */
47707 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
47708   int b;
47709   if( p==0 ) return 0;
47710   sqlite3BtreeEnter(p);
47711   if( newFlag>=0 ){
47712     p->pBt->secureDelete = (newFlag!=0) ? 1 : 0;
47713   } 
47714   b = p->pBt->secureDelete;
47715   sqlite3BtreeLeave(p);
47716   return b;
47717 }
47718 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
47719
47720 /*
47721 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
47722 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
47723 ** is disabled. The default value for the auto-vacuum property is 
47724 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
47725 */
47726 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
47727 #ifdef SQLITE_OMIT_AUTOVACUUM
47728   return SQLITE_READONLY;
47729 #else
47730   BtShared *pBt = p->pBt;
47731   int rc = SQLITE_OK;
47732   u8 av = (u8)autoVacuum;
47733
47734   sqlite3BtreeEnter(p);
47735   if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
47736     rc = SQLITE_READONLY;
47737   }else{
47738     pBt->autoVacuum = av ?1:0;
47739     pBt->incrVacuum = av==2 ?1:0;
47740   }
47741   sqlite3BtreeLeave(p);
47742   return rc;
47743 #endif
47744 }
47745
47746 /*
47747 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
47748 ** enabled 1 is returned. Otherwise 0.
47749 */
47750 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
47751 #ifdef SQLITE_OMIT_AUTOVACUUM
47752   return BTREE_AUTOVACUUM_NONE;
47753 #else
47754   int rc;
47755   sqlite3BtreeEnter(p);
47756   rc = (
47757     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
47758     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
47759     BTREE_AUTOVACUUM_INCR
47760   );
47761   sqlite3BtreeLeave(p);
47762   return rc;
47763 #endif
47764 }
47765
47766
47767 /*
47768 ** Get a reference to pPage1 of the database file.  This will
47769 ** also acquire a readlock on that file.
47770 **
47771 ** SQLITE_OK is returned on success.  If the file is not a
47772 ** well-formed database file, then SQLITE_CORRUPT is returned.
47773 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
47774 ** is returned if we run out of memory. 
47775 */
47776 static int lockBtree(BtShared *pBt){
47777   int rc;              /* Result code from subfunctions */
47778   MemPage *pPage1;     /* Page 1 of the database file */
47779   int nPage;           /* Number of pages in the database */
47780   int nPageFile = 0;   /* Number of pages in the database file */
47781   int nPageHeader;     /* Number of pages in the database according to hdr */
47782
47783   assert( sqlite3_mutex_held(pBt->mutex) );
47784   assert( pBt->pPage1==0 );
47785   rc = sqlite3PagerSharedLock(pBt->pPager);
47786   if( rc!=SQLITE_OK ) return rc;
47787   rc = btreeGetPage(pBt, 1, &pPage1, 0);
47788   if( rc!=SQLITE_OK ) return rc;
47789
47790   /* Do some checking to help insure the file we opened really is
47791   ** a valid database file. 
47792   */
47793   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
47794   sqlite3PagerPagecount(pBt->pPager, &nPageFile);
47795   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
47796     nPage = nPageFile;
47797   }
47798   if( nPage>0 ){
47799     u32 pageSize;
47800     u32 usableSize;
47801     u8 *page1 = pPage1->aData;
47802     rc = SQLITE_NOTADB;
47803     if( memcmp(page1, zMagicHeader, 16)!=0 ){
47804       goto page1_init_failed;
47805     }
47806
47807 #ifdef SQLITE_OMIT_WAL
47808     if( page1[18]>1 ){
47809       pBt->readOnly = 1;
47810     }
47811     if( page1[19]>1 ){
47812       goto page1_init_failed;
47813     }
47814 #else
47815     if( page1[18]>2 ){
47816       pBt->readOnly = 1;
47817     }
47818     if( page1[19]>2 ){
47819       goto page1_init_failed;
47820     }
47821
47822     /* If the write version is set to 2, this database should be accessed
47823     ** in WAL mode. If the log is not already open, open it now. Then 
47824     ** return SQLITE_OK and return without populating BtShared.pPage1.
47825     ** The caller detects this and calls this function again. This is
47826     ** required as the version of page 1 currently in the page1 buffer
47827     ** may not be the latest version - there may be a newer one in the log
47828     ** file.
47829     */
47830     if( page1[19]==2 && pBt->doNotUseWAL==0 ){
47831       int isOpen = 0;
47832       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
47833       if( rc!=SQLITE_OK ){
47834         goto page1_init_failed;
47835       }else if( isOpen==0 ){
47836         releasePage(pPage1);
47837         return SQLITE_OK;
47838       }
47839       rc = SQLITE_NOTADB;
47840     }
47841 #endif
47842
47843     /* The maximum embedded fraction must be exactly 25%.  And the minimum
47844     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
47845     ** The original design allowed these amounts to vary, but as of
47846     ** version 3.6.0, we require them to be fixed.
47847     */
47848     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
47849       goto page1_init_failed;
47850     }
47851     pageSize = (page1[16]<<8) | (page1[17]<<16);
47852     if( ((pageSize-1)&pageSize)!=0
47853      || pageSize>SQLITE_MAX_PAGE_SIZE 
47854      || pageSize<=256 
47855     ){
47856       goto page1_init_failed;
47857     }
47858     assert( (pageSize & 7)==0 );
47859     usableSize = pageSize - page1[20];
47860     if( (u32)pageSize!=pBt->pageSize ){
47861       /* After reading the first page of the database assuming a page size
47862       ** of BtShared.pageSize, we have discovered that the page-size is
47863       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
47864       ** zero and return SQLITE_OK. The caller will call this function
47865       ** again with the correct page-size.
47866       */
47867       releasePage(pPage1);
47868       pBt->usableSize = usableSize;
47869       pBt->pageSize = pageSize;
47870       freeTempSpace(pBt);
47871       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
47872                                    pageSize-usableSize);
47873       return rc;
47874     }
47875     if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPageHeader>nPageFile ){
47876       rc = SQLITE_CORRUPT_BKPT;
47877       goto page1_init_failed;
47878     }
47879     if( usableSize<480 ){
47880       goto page1_init_failed;
47881     }
47882     pBt->pageSize = pageSize;
47883     pBt->usableSize = usableSize;
47884 #ifndef SQLITE_OMIT_AUTOVACUUM
47885     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
47886     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
47887 #endif
47888   }
47889
47890   /* maxLocal is the maximum amount of payload to store locally for
47891   ** a cell.  Make sure it is small enough so that at least minFanout
47892   ** cells can will fit on one page.  We assume a 10-byte page header.
47893   ** Besides the payload, the cell must store:
47894   **     2-byte pointer to the cell
47895   **     4-byte child pointer
47896   **     9-byte nKey value
47897   **     4-byte nData value
47898   **     4-byte overflow page pointer
47899   ** So a cell consists of a 2-byte pointer, a header which is as much as
47900   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
47901   ** page pointer.
47902   */
47903   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
47904   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
47905   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
47906   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
47907   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
47908   pBt->pPage1 = pPage1;
47909   pBt->nPage = nPage;
47910   return SQLITE_OK;
47911
47912 page1_init_failed:
47913   releasePage(pPage1);
47914   pBt->pPage1 = 0;
47915   return rc;
47916 }
47917
47918 /*
47919 ** If there are no outstanding cursors and we are not in the middle
47920 ** of a transaction but there is a read lock on the database, then
47921 ** this routine unrefs the first page of the database file which 
47922 ** has the effect of releasing the read lock.
47923 **
47924 ** If there is a transaction in progress, this routine is a no-op.
47925 */
47926 static void unlockBtreeIfUnused(BtShared *pBt){
47927   assert( sqlite3_mutex_held(pBt->mutex) );
47928   assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
47929   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
47930     assert( pBt->pPage1->aData );
47931     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
47932     assert( pBt->pPage1->aData );
47933     releasePage(pBt->pPage1);
47934     pBt->pPage1 = 0;
47935   }
47936 }
47937
47938 /*
47939 ** If pBt points to an empty file then convert that empty file
47940 ** into a new empty database by initializing the first page of
47941 ** the database.
47942 */
47943 static int newDatabase(BtShared *pBt){
47944   MemPage *pP1;
47945   unsigned char *data;
47946   int rc;
47947
47948   assert( sqlite3_mutex_held(pBt->mutex) );
47949   if( pBt->nPage>0 ){
47950     return SQLITE_OK;
47951   }
47952   pP1 = pBt->pPage1;
47953   assert( pP1!=0 );
47954   data = pP1->aData;
47955   rc = sqlite3PagerWrite(pP1->pDbPage);
47956   if( rc ) return rc;
47957   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
47958   assert( sizeof(zMagicHeader)==16 );
47959   data[16] = (u8)((pBt->pageSize>>8)&0xff);
47960   data[17] = (u8)((pBt->pageSize>>16)&0xff);
47961   data[18] = 1;
47962   data[19] = 1;
47963   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
47964   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
47965   data[21] = 64;
47966   data[22] = 32;
47967   data[23] = 32;
47968   memset(&data[24], 0, 100-24);
47969   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
47970   pBt->pageSizeFixed = 1;
47971 #ifndef SQLITE_OMIT_AUTOVACUUM
47972   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
47973   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
47974   put4byte(&data[36 + 4*4], pBt->autoVacuum);
47975   put4byte(&data[36 + 7*4], pBt->incrVacuum);
47976 #endif
47977   pBt->nPage = 1;
47978   data[31] = 1;
47979   return SQLITE_OK;
47980 }
47981
47982 /*
47983 ** Attempt to start a new transaction. A write-transaction
47984 ** is started if the second argument is nonzero, otherwise a read-
47985 ** transaction.  If the second argument is 2 or more and exclusive
47986 ** transaction is started, meaning that no other process is allowed
47987 ** to access the database.  A preexisting transaction may not be
47988 ** upgraded to exclusive by calling this routine a second time - the
47989 ** exclusivity flag only works for a new transaction.
47990 **
47991 ** A write-transaction must be started before attempting any 
47992 ** changes to the database.  None of the following routines 
47993 ** will work unless a transaction is started first:
47994 **
47995 **      sqlite3BtreeCreateTable()
47996 **      sqlite3BtreeCreateIndex()
47997 **      sqlite3BtreeClearTable()
47998 **      sqlite3BtreeDropTable()
47999 **      sqlite3BtreeInsert()
48000 **      sqlite3BtreeDelete()
48001 **      sqlite3BtreeUpdateMeta()
48002 **
48003 ** If an initial attempt to acquire the lock fails because of lock contention
48004 ** and the database was previously unlocked, then invoke the busy handler
48005 ** if there is one.  But if there was previously a read-lock, do not
48006 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
48007 ** returned when there is already a read-lock in order to avoid a deadlock.
48008 **
48009 ** Suppose there are two processes A and B.  A has a read lock and B has
48010 ** a reserved lock.  B tries to promote to exclusive but is blocked because
48011 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
48012 ** One or the other of the two processes must give way or there can be
48013 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
48014 ** when A already has a read lock, we encourage A to give up and let B
48015 ** proceed.
48016 */
48017 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
48018   sqlite3 *pBlock = 0;
48019   BtShared *pBt = p->pBt;
48020   int rc = SQLITE_OK;
48021
48022   sqlite3BtreeEnter(p);
48023   btreeIntegrity(p);
48024
48025   /* If the btree is already in a write-transaction, or it
48026   ** is already in a read-transaction and a read-transaction
48027   ** is requested, this is a no-op.
48028   */
48029   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
48030     goto trans_begun;
48031   }
48032
48033   /* Write transactions are not possible on a read-only database */
48034   if( pBt->readOnly && wrflag ){
48035     rc = SQLITE_READONLY;
48036     goto trans_begun;
48037   }
48038
48039 #ifndef SQLITE_OMIT_SHARED_CACHE
48040   /* If another database handle has already opened a write transaction 
48041   ** on this shared-btree structure and a second write transaction is
48042   ** requested, return SQLITE_LOCKED.
48043   */
48044   if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
48045     pBlock = pBt->pWriter->db;
48046   }else if( wrflag>1 ){
48047     BtLock *pIter;
48048     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
48049       if( pIter->pBtree!=p ){
48050         pBlock = pIter->pBtree->db;
48051         break;
48052       }
48053     }
48054   }
48055   if( pBlock ){
48056     sqlite3ConnectionBlocked(p->db, pBlock);
48057     rc = SQLITE_LOCKED_SHAREDCACHE;
48058     goto trans_begun;
48059   }
48060 #endif
48061
48062   /* Any read-only or read-write transaction implies a read-lock on 
48063   ** page 1. So if some other shared-cache client already has a write-lock 
48064   ** on page 1, the transaction cannot be opened. */
48065   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
48066   if( SQLITE_OK!=rc ) goto trans_begun;
48067
48068   pBt->initiallyEmpty = (u8)(pBt->nPage==0);
48069   do {
48070     /* Call lockBtree() until either pBt->pPage1 is populated or
48071     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
48072     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
48073     ** reading page 1 it discovers that the page-size of the database 
48074     ** file is not pBt->pageSize. In this case lockBtree() will update
48075     ** pBt->pageSize to the page-size of the file on disk.
48076     */
48077     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
48078
48079     if( rc==SQLITE_OK && wrflag ){
48080       if( pBt->readOnly ){
48081         rc = SQLITE_READONLY;
48082       }else{
48083         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
48084         if( rc==SQLITE_OK ){
48085           rc = newDatabase(pBt);
48086         }
48087       }
48088     }
48089   
48090     if( rc!=SQLITE_OK ){
48091       unlockBtreeIfUnused(pBt);
48092     }
48093   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
48094           btreeInvokeBusyHandler(pBt) );
48095
48096   if( rc==SQLITE_OK ){
48097     if( p->inTrans==TRANS_NONE ){
48098       pBt->nTransaction++;
48099 #ifndef SQLITE_OMIT_SHARED_CACHE
48100       if( p->sharable ){
48101         assert( p->lock.pBtree==p && p->lock.iTable==1 );
48102         p->lock.eLock = READ_LOCK;
48103         p->lock.pNext = pBt->pLock;
48104         pBt->pLock = &p->lock;
48105       }
48106 #endif
48107     }
48108     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
48109     if( p->inTrans>pBt->inTransaction ){
48110       pBt->inTransaction = p->inTrans;
48111     }
48112     if( wrflag ){
48113       MemPage *pPage1 = pBt->pPage1;
48114 #ifndef SQLITE_OMIT_SHARED_CACHE
48115       assert( !pBt->pWriter );
48116       pBt->pWriter = p;
48117       pBt->isExclusive = (u8)(wrflag>1);
48118 #endif
48119
48120       /* If the db-size header field is incorrect (as it may be if an old
48121       ** client has been writing the database file), update it now. Doing
48122       ** this sooner rather than later means the database size can safely 
48123       ** re-read the database size from page 1 if a savepoint or transaction
48124       ** rollback occurs within the transaction.
48125       */
48126       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
48127         rc = sqlite3PagerWrite(pPage1->pDbPage);
48128         if( rc==SQLITE_OK ){
48129           put4byte(&pPage1->aData[28], pBt->nPage);
48130         }
48131       }
48132     }
48133   }
48134
48135
48136 trans_begun:
48137   if( rc==SQLITE_OK && wrflag ){
48138     /* This call makes sure that the pager has the correct number of
48139     ** open savepoints. If the second parameter is greater than 0 and
48140     ** the sub-journal is not already open, then it will be opened here.
48141     */
48142     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
48143   }
48144
48145   btreeIntegrity(p);
48146   sqlite3BtreeLeave(p);
48147   return rc;
48148 }
48149
48150 #ifndef SQLITE_OMIT_AUTOVACUUM
48151
48152 /*
48153 ** Set the pointer-map entries for all children of page pPage. Also, if
48154 ** pPage contains cells that point to overflow pages, set the pointer
48155 ** map entries for the overflow pages as well.
48156 */
48157 static int setChildPtrmaps(MemPage *pPage){
48158   int i;                             /* Counter variable */
48159   int nCell;                         /* Number of cells in page pPage */
48160   int rc;                            /* Return code */
48161   BtShared *pBt = pPage->pBt;
48162   u8 isInitOrig = pPage->isInit;
48163   Pgno pgno = pPage->pgno;
48164
48165   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48166   rc = btreeInitPage(pPage);
48167   if( rc!=SQLITE_OK ){
48168     goto set_child_ptrmaps_out;
48169   }
48170   nCell = pPage->nCell;
48171
48172   for(i=0; i<nCell; i++){
48173     u8 *pCell = findCell(pPage, i);
48174
48175     ptrmapPutOvflPtr(pPage, pCell, &rc);
48176
48177     if( !pPage->leaf ){
48178       Pgno childPgno = get4byte(pCell);
48179       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
48180     }
48181   }
48182
48183   if( !pPage->leaf ){
48184     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
48185     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
48186   }
48187
48188 set_child_ptrmaps_out:
48189   pPage->isInit = isInitOrig;
48190   return rc;
48191 }
48192
48193 /*
48194 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
48195 ** that it points to iTo. Parameter eType describes the type of pointer to
48196 ** be modified, as  follows:
48197 **
48198 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
48199 **                   page of pPage.
48200 **
48201 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
48202 **                   page pointed to by one of the cells on pPage.
48203 **
48204 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
48205 **                   overflow page in the list.
48206 */
48207 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
48208   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48209   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48210   if( eType==PTRMAP_OVERFLOW2 ){
48211     /* The pointer is always the first 4 bytes of the page in this case.  */
48212     if( get4byte(pPage->aData)!=iFrom ){
48213       return SQLITE_CORRUPT_BKPT;
48214     }
48215     put4byte(pPage->aData, iTo);
48216   }else{
48217     u8 isInitOrig = pPage->isInit;
48218     int i;
48219     int nCell;
48220
48221     btreeInitPage(pPage);
48222     nCell = pPage->nCell;
48223
48224     for(i=0; i<nCell; i++){
48225       u8 *pCell = findCell(pPage, i);
48226       if( eType==PTRMAP_OVERFLOW1 ){
48227         CellInfo info;
48228         btreeParseCellPtr(pPage, pCell, &info);
48229         if( info.iOverflow ){
48230           if( iFrom==get4byte(&pCell[info.iOverflow]) ){
48231             put4byte(&pCell[info.iOverflow], iTo);
48232             break;
48233           }
48234         }
48235       }else{
48236         if( get4byte(pCell)==iFrom ){
48237           put4byte(pCell, iTo);
48238           break;
48239         }
48240       }
48241     }
48242   
48243     if( i==nCell ){
48244       if( eType!=PTRMAP_BTREE || 
48245           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
48246         return SQLITE_CORRUPT_BKPT;
48247       }
48248       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
48249     }
48250
48251     pPage->isInit = isInitOrig;
48252   }
48253   return SQLITE_OK;
48254 }
48255
48256
48257 /*
48258 ** Move the open database page pDbPage to location iFreePage in the 
48259 ** database. The pDbPage reference remains valid.
48260 **
48261 ** The isCommit flag indicates that there is no need to remember that
48262 ** the journal needs to be sync()ed before database page pDbPage->pgno 
48263 ** can be written to. The caller has already promised not to write to that
48264 ** page.
48265 */
48266 static int relocatePage(
48267   BtShared *pBt,           /* Btree */
48268   MemPage *pDbPage,        /* Open page to move */
48269   u8 eType,                /* Pointer map 'type' entry for pDbPage */
48270   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
48271   Pgno iFreePage,          /* The location to move pDbPage to */
48272   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
48273 ){
48274   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
48275   Pgno iDbPage = pDbPage->pgno;
48276   Pager *pPager = pBt->pPager;
48277   int rc;
48278
48279   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
48280       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
48281   assert( sqlite3_mutex_held(pBt->mutex) );
48282   assert( pDbPage->pBt==pBt );
48283
48284   /* Move page iDbPage from its current location to page number iFreePage */
48285   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
48286       iDbPage, iFreePage, iPtrPage, eType));
48287   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
48288   if( rc!=SQLITE_OK ){
48289     return rc;
48290   }
48291   pDbPage->pgno = iFreePage;
48292
48293   /* If pDbPage was a btree-page, then it may have child pages and/or cells
48294   ** that point to overflow pages. The pointer map entries for all these
48295   ** pages need to be changed.
48296   **
48297   ** If pDbPage is an overflow page, then the first 4 bytes may store a
48298   ** pointer to a subsequent overflow page. If this is the case, then
48299   ** the pointer map needs to be updated for the subsequent overflow page.
48300   */
48301   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
48302     rc = setChildPtrmaps(pDbPage);
48303     if( rc!=SQLITE_OK ){
48304       return rc;
48305     }
48306   }else{
48307     Pgno nextOvfl = get4byte(pDbPage->aData);
48308     if( nextOvfl!=0 ){
48309       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
48310       if( rc!=SQLITE_OK ){
48311         return rc;
48312       }
48313     }
48314   }
48315
48316   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
48317   ** that it points at iFreePage. Also fix the pointer map entry for
48318   ** iPtrPage.
48319   */
48320   if( eType!=PTRMAP_ROOTPAGE ){
48321     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
48322     if( rc!=SQLITE_OK ){
48323       return rc;
48324     }
48325     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
48326     if( rc!=SQLITE_OK ){
48327       releasePage(pPtrPage);
48328       return rc;
48329     }
48330     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
48331     releasePage(pPtrPage);
48332     if( rc==SQLITE_OK ){
48333       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
48334     }
48335   }
48336   return rc;
48337 }
48338
48339 /* Forward declaration required by incrVacuumStep(). */
48340 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
48341
48342 /*
48343 ** Perform a single step of an incremental-vacuum. If successful,
48344 ** return SQLITE_OK. If there is no work to do (and therefore no
48345 ** point in calling this function again), return SQLITE_DONE.
48346 **
48347 ** More specificly, this function attempts to re-organize the 
48348 ** database so that the last page of the file currently in use
48349 ** is no longer in use.
48350 **
48351 ** If the nFin parameter is non-zero, this function assumes
48352 ** that the caller will keep calling incrVacuumStep() until
48353 ** it returns SQLITE_DONE or an error, and that nFin is the
48354 ** number of pages the database file will contain after this 
48355 ** process is complete.  If nFin is zero, it is assumed that
48356 ** incrVacuumStep() will be called a finite amount of times
48357 ** which may or may not empty the freelist.  A full autovacuum
48358 ** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
48359 */
48360 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
48361   Pgno nFreeList;           /* Number of pages still on the free-list */
48362   int rc;
48363
48364   assert( sqlite3_mutex_held(pBt->mutex) );
48365   assert( iLastPg>nFin );
48366
48367   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
48368     u8 eType;
48369     Pgno iPtrPage;
48370
48371     nFreeList = get4byte(&pBt->pPage1->aData[36]);
48372     if( nFreeList==0 ){
48373       return SQLITE_DONE;
48374     }
48375
48376     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
48377     if( rc!=SQLITE_OK ){
48378       return rc;
48379     }
48380     if( eType==PTRMAP_ROOTPAGE ){
48381       return SQLITE_CORRUPT_BKPT;
48382     }
48383
48384     if( eType==PTRMAP_FREEPAGE ){
48385       if( nFin==0 ){
48386         /* Remove the page from the files free-list. This is not required
48387         ** if nFin is non-zero. In that case, the free-list will be
48388         ** truncated to zero after this function returns, so it doesn't 
48389         ** matter if it still contains some garbage entries.
48390         */
48391         Pgno iFreePg;
48392         MemPage *pFreePg;
48393         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
48394         if( rc!=SQLITE_OK ){
48395           return rc;
48396         }
48397         assert( iFreePg==iLastPg );
48398         releasePage(pFreePg);
48399       }
48400     } else {
48401       Pgno iFreePg;             /* Index of free page to move pLastPg to */
48402       MemPage *pLastPg;
48403
48404       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
48405       if( rc!=SQLITE_OK ){
48406         return rc;
48407       }
48408
48409       /* If nFin is zero, this loop runs exactly once and page pLastPg
48410       ** is swapped with the first free page pulled off the free list.
48411       **
48412       ** On the other hand, if nFin is greater than zero, then keep
48413       ** looping until a free-page located within the first nFin pages
48414       ** of the file is found.
48415       */
48416       do {
48417         MemPage *pFreePg;
48418         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
48419         if( rc!=SQLITE_OK ){
48420           releasePage(pLastPg);
48421           return rc;
48422         }
48423         releasePage(pFreePg);
48424       }while( nFin!=0 && iFreePg>nFin );
48425       assert( iFreePg<iLastPg );
48426       
48427       rc = sqlite3PagerWrite(pLastPg->pDbPage);
48428       if( rc==SQLITE_OK ){
48429         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
48430       }
48431       releasePage(pLastPg);
48432       if( rc!=SQLITE_OK ){
48433         return rc;
48434       }
48435     }
48436   }
48437
48438   if( nFin==0 ){
48439     iLastPg--;
48440     while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
48441       if( PTRMAP_ISPAGE(pBt, iLastPg) ){
48442         MemPage *pPg;
48443         rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
48444         if( rc!=SQLITE_OK ){
48445           return rc;
48446         }
48447         rc = sqlite3PagerWrite(pPg->pDbPage);
48448         releasePage(pPg);
48449         if( rc!=SQLITE_OK ){
48450           return rc;
48451         }
48452       }
48453       iLastPg--;
48454     }
48455     sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
48456     pBt->nPage = iLastPg;
48457   }
48458   return SQLITE_OK;
48459 }
48460
48461 /*
48462 ** A write-transaction must be opened before calling this function.
48463 ** It performs a single unit of work towards an incremental vacuum.
48464 **
48465 ** If the incremental vacuum is finished after this function has run,
48466 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
48467 ** SQLITE_OK is returned. Otherwise an SQLite error code. 
48468 */
48469 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
48470   int rc;
48471   BtShared *pBt = p->pBt;
48472
48473   sqlite3BtreeEnter(p);
48474   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
48475   if( !pBt->autoVacuum ){
48476     rc = SQLITE_DONE;
48477   }else{
48478     invalidateAllOverflowCache(pBt);
48479     rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
48480     if( rc==SQLITE_OK ){
48481       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
48482       put4byte(&pBt->pPage1->aData[28], pBt->nPage);
48483     }
48484   }
48485   sqlite3BtreeLeave(p);
48486   return rc;
48487 }
48488
48489 /*
48490 ** This routine is called prior to sqlite3PagerCommit when a transaction
48491 ** is commited for an auto-vacuum database.
48492 **
48493 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
48494 ** the database file should be truncated to during the commit process. 
48495 ** i.e. the database has been reorganized so that only the first *pnTrunc
48496 ** pages are in use.
48497 */
48498 static int autoVacuumCommit(BtShared *pBt){
48499   int rc = SQLITE_OK;
48500   Pager *pPager = pBt->pPager;
48501   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
48502
48503   assert( sqlite3_mutex_held(pBt->mutex) );
48504   invalidateAllOverflowCache(pBt);
48505   assert(pBt->autoVacuum);
48506   if( !pBt->incrVacuum ){
48507     Pgno nFin;         /* Number of pages in database after autovacuuming */
48508     Pgno nFree;        /* Number of pages on the freelist initially */
48509     Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
48510     Pgno iFree;        /* The next page to be freed */
48511     int nEntry;        /* Number of entries on one ptrmap page */
48512     Pgno nOrig;        /* Database size before freeing */
48513
48514     nOrig = btreePagecount(pBt);
48515     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
48516       /* It is not possible to create a database for which the final page
48517       ** is either a pointer-map page or the pending-byte page. If one
48518       ** is encountered, this indicates corruption.
48519       */
48520       return SQLITE_CORRUPT_BKPT;
48521     }
48522
48523     nFree = get4byte(&pBt->pPage1->aData[36]);
48524     nEntry = pBt->usableSize/5;
48525     nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
48526     nFin = nOrig - nFree - nPtrmap;
48527     if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
48528       nFin--;
48529     }
48530     while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
48531       nFin--;
48532     }
48533     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
48534
48535     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
48536       rc = incrVacuumStep(pBt, nFin, iFree);
48537     }
48538     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
48539       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
48540       put4byte(&pBt->pPage1->aData[32], 0);
48541       put4byte(&pBt->pPage1->aData[36], 0);
48542       put4byte(&pBt->pPage1->aData[28], nFin);
48543       sqlite3PagerTruncateImage(pBt->pPager, nFin);
48544       pBt->nPage = nFin;
48545     }
48546     if( rc!=SQLITE_OK ){
48547       sqlite3PagerRollback(pPager);
48548     }
48549   }
48550
48551   assert( nRef==sqlite3PagerRefcount(pPager) );
48552   return rc;
48553 }
48554
48555 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
48556 # define setChildPtrmaps(x) SQLITE_OK
48557 #endif
48558
48559 /*
48560 ** This routine does the first phase of a two-phase commit.  This routine
48561 ** causes a rollback journal to be created (if it does not already exist)
48562 ** and populated with enough information so that if a power loss occurs
48563 ** the database can be restored to its original state by playing back
48564 ** the journal.  Then the contents of the journal are flushed out to
48565 ** the disk.  After the journal is safely on oxide, the changes to the
48566 ** database are written into the database file and flushed to oxide.
48567 ** At the end of this call, the rollback journal still exists on the
48568 ** disk and we are still holding all locks, so the transaction has not
48569 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
48570 ** commit process.
48571 **
48572 ** This call is a no-op if no write-transaction is currently active on pBt.
48573 **
48574 ** Otherwise, sync the database file for the btree pBt. zMaster points to
48575 ** the name of a master journal file that should be written into the
48576 ** individual journal file, or is NULL, indicating no master journal file 
48577 ** (single database transaction).
48578 **
48579 ** When this is called, the master journal should already have been
48580 ** created, populated with this journal pointer and synced to disk.
48581 **
48582 ** Once this is routine has returned, the only thing required to commit
48583 ** the write-transaction for this database file is to delete the journal.
48584 */
48585 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
48586   int rc = SQLITE_OK;
48587   if( p->inTrans==TRANS_WRITE ){
48588     BtShared *pBt = p->pBt;
48589     sqlite3BtreeEnter(p);
48590 #ifndef SQLITE_OMIT_AUTOVACUUM
48591     if( pBt->autoVacuum ){
48592       rc = autoVacuumCommit(pBt);
48593       if( rc!=SQLITE_OK ){
48594         sqlite3BtreeLeave(p);
48595         return rc;
48596       }
48597     }
48598 #endif
48599     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
48600     sqlite3BtreeLeave(p);
48601   }
48602   return rc;
48603 }
48604
48605 /*
48606 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
48607 ** at the conclusion of a transaction.
48608 */
48609 static void btreeEndTransaction(Btree *p){
48610   BtShared *pBt = p->pBt;
48611   assert( sqlite3BtreeHoldsMutex(p) );
48612
48613   btreeClearHasContent(pBt);
48614   if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
48615     /* If there are other active statements that belong to this database
48616     ** handle, downgrade to a read-only transaction. The other statements
48617     ** may still be reading from the database.  */
48618     downgradeAllSharedCacheTableLocks(p);
48619     p->inTrans = TRANS_READ;
48620   }else{
48621     /* If the handle had any kind of transaction open, decrement the 
48622     ** transaction count of the shared btree. If the transaction count 
48623     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
48624     ** call below will unlock the pager.  */
48625     if( p->inTrans!=TRANS_NONE ){
48626       clearAllSharedCacheTableLocks(p);
48627       pBt->nTransaction--;
48628       if( 0==pBt->nTransaction ){
48629         pBt->inTransaction = TRANS_NONE;
48630       }
48631     }
48632
48633     /* Set the current transaction state to TRANS_NONE and unlock the 
48634     ** pager if this call closed the only read or write transaction.  */
48635     p->inTrans = TRANS_NONE;
48636     unlockBtreeIfUnused(pBt);
48637   }
48638
48639   btreeIntegrity(p);
48640 }
48641
48642 /*
48643 ** Commit the transaction currently in progress.
48644 **
48645 ** This routine implements the second phase of a 2-phase commit.  The
48646 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
48647 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
48648 ** routine did all the work of writing information out to disk and flushing the
48649 ** contents so that they are written onto the disk platter.  All this
48650 ** routine has to do is delete or truncate or zero the header in the
48651 ** the rollback journal (which causes the transaction to commit) and
48652 ** drop locks.
48653 **
48654 ** This will release the write lock on the database file.  If there
48655 ** are no active cursors, it also releases the read lock.
48656 */
48657 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
48658
48659   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
48660   sqlite3BtreeEnter(p);
48661   btreeIntegrity(p);
48662
48663   /* If the handle has a write-transaction open, commit the shared-btrees 
48664   ** transaction and set the shared state to TRANS_READ.
48665   */
48666   if( p->inTrans==TRANS_WRITE ){
48667     int rc;
48668     BtShared *pBt = p->pBt;
48669     assert( pBt->inTransaction==TRANS_WRITE );
48670     assert( pBt->nTransaction>0 );
48671     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
48672     if( rc!=SQLITE_OK ){
48673       sqlite3BtreeLeave(p);
48674       return rc;
48675     }
48676     pBt->inTransaction = TRANS_READ;
48677   }
48678
48679   btreeEndTransaction(p);
48680   sqlite3BtreeLeave(p);
48681   return SQLITE_OK;
48682 }
48683
48684 /*
48685 ** Do both phases of a commit.
48686 */
48687 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
48688   int rc;
48689   sqlite3BtreeEnter(p);
48690   rc = sqlite3BtreeCommitPhaseOne(p, 0);
48691   if( rc==SQLITE_OK ){
48692     rc = sqlite3BtreeCommitPhaseTwo(p);
48693   }
48694   sqlite3BtreeLeave(p);
48695   return rc;
48696 }
48697
48698 #ifndef NDEBUG
48699 /*
48700 ** Return the number of write-cursors open on this handle. This is for use
48701 ** in assert() expressions, so it is only compiled if NDEBUG is not
48702 ** defined.
48703 **
48704 ** For the purposes of this routine, a write-cursor is any cursor that
48705 ** is capable of writing to the databse.  That means the cursor was
48706 ** originally opened for writing and the cursor has not be disabled
48707 ** by having its state changed to CURSOR_FAULT.
48708 */
48709 static int countWriteCursors(BtShared *pBt){
48710   BtCursor *pCur;
48711   int r = 0;
48712   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
48713     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; 
48714   }
48715   return r;
48716 }
48717 #endif
48718
48719 /*
48720 ** This routine sets the state to CURSOR_FAULT and the error
48721 ** code to errCode for every cursor on BtShared that pBtree
48722 ** references.
48723 **
48724 ** Every cursor is tripped, including cursors that belong
48725 ** to other database connections that happen to be sharing
48726 ** the cache with pBtree.
48727 **
48728 ** This routine gets called when a rollback occurs.
48729 ** All cursors using the same cache must be tripped
48730 ** to prevent them from trying to use the btree after
48731 ** the rollback.  The rollback may have deleted tables
48732 ** or moved root pages, so it is not sufficient to
48733 ** save the state of the cursor.  The cursor must be
48734 ** invalidated.
48735 */
48736 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
48737   BtCursor *p;
48738   sqlite3BtreeEnter(pBtree);
48739   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
48740     int i;
48741     sqlite3BtreeClearCursor(p);
48742     p->eState = CURSOR_FAULT;
48743     p->skipNext = errCode;
48744     for(i=0; i<=p->iPage; i++){
48745       releasePage(p->apPage[i]);
48746       p->apPage[i] = 0;
48747     }
48748   }
48749   sqlite3BtreeLeave(pBtree);
48750 }
48751
48752 /*
48753 ** Rollback the transaction in progress.  All cursors will be
48754 ** invalided by this operation.  Any attempt to use a cursor
48755 ** that was open at the beginning of this operation will result
48756 ** in an error.
48757 **
48758 ** This will release the write lock on the database file.  If there
48759 ** are no active cursors, it also releases the read lock.
48760 */
48761 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
48762   int rc;
48763   BtShared *pBt = p->pBt;
48764   MemPage *pPage1;
48765
48766   sqlite3BtreeEnter(p);
48767   rc = saveAllCursors(pBt, 0, 0);
48768 #ifndef SQLITE_OMIT_SHARED_CACHE
48769   if( rc!=SQLITE_OK ){
48770     /* This is a horrible situation. An IO or malloc() error occurred whilst
48771     ** trying to save cursor positions. If this is an automatic rollback (as
48772     ** the result of a constraint, malloc() failure or IO error) then 
48773     ** the cache may be internally inconsistent (not contain valid trees) so
48774     ** we cannot simply return the error to the caller. Instead, abort 
48775     ** all queries that may be using any of the cursors that failed to save.
48776     */
48777     sqlite3BtreeTripAllCursors(p, rc);
48778   }
48779 #endif
48780   btreeIntegrity(p);
48781
48782   if( p->inTrans==TRANS_WRITE ){
48783     int rc2;
48784
48785     assert( TRANS_WRITE==pBt->inTransaction );
48786     rc2 = sqlite3PagerRollback(pBt->pPager);
48787     if( rc2!=SQLITE_OK ){
48788       rc = rc2;
48789     }
48790
48791     /* The rollback may have destroyed the pPage1->aData value.  So
48792     ** call btreeGetPage() on page 1 again to make
48793     ** sure pPage1->aData is set correctly. */
48794     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
48795       int nPage = get4byte(28+(u8*)pPage1->aData);
48796       testcase( nPage==0 );
48797       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
48798       testcase( pBt->nPage!=nPage );
48799       pBt->nPage = nPage;
48800       releasePage(pPage1);
48801     }
48802     assert( countWriteCursors(pBt)==0 );
48803     pBt->inTransaction = TRANS_READ;
48804   }
48805
48806   btreeEndTransaction(p);
48807   sqlite3BtreeLeave(p);
48808   return rc;
48809 }
48810
48811 /*
48812 ** Start a statement subtransaction. The subtransaction can can be rolled
48813 ** back independently of the main transaction. You must start a transaction 
48814 ** before starting a subtransaction. The subtransaction is ended automatically 
48815 ** if the main transaction commits or rolls back.
48816 **
48817 ** Statement subtransactions are used around individual SQL statements
48818 ** that are contained within a BEGIN...COMMIT block.  If a constraint
48819 ** error occurs within the statement, the effect of that one statement
48820 ** can be rolled back without having to rollback the entire transaction.
48821 **
48822 ** A statement sub-transaction is implemented as an anonymous savepoint. The
48823 ** value passed as the second parameter is the total number of savepoints,
48824 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
48825 ** are no active savepoints and no other statement-transactions open,
48826 ** iStatement is 1. This anonymous savepoint can be released or rolled back
48827 ** using the sqlite3BtreeSavepoint() function.
48828 */
48829 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
48830   int rc;
48831   BtShared *pBt = p->pBt;
48832   sqlite3BtreeEnter(p);
48833   assert( p->inTrans==TRANS_WRITE );
48834   assert( pBt->readOnly==0 );
48835   assert( iStatement>0 );
48836   assert( iStatement>p->db->nSavepoint );
48837   assert( pBt->inTransaction==TRANS_WRITE );
48838   /* At the pager level, a statement transaction is a savepoint with
48839   ** an index greater than all savepoints created explicitly using
48840   ** SQL statements. It is illegal to open, release or rollback any
48841   ** such savepoints while the statement transaction savepoint is active.
48842   */
48843   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
48844   sqlite3BtreeLeave(p);
48845   return rc;
48846 }
48847
48848 /*
48849 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
48850 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
48851 ** savepoint identified by parameter iSavepoint, depending on the value 
48852 ** of op.
48853 **
48854 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
48855 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 
48856 ** contents of the entire transaction are rolled back. This is different
48857 ** from a normal transaction rollback, as no locks are released and the
48858 ** transaction remains open.
48859 */
48860 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
48861   int rc = SQLITE_OK;
48862   if( p && p->inTrans==TRANS_WRITE ){
48863     BtShared *pBt = p->pBt;
48864     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
48865     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
48866     sqlite3BtreeEnter(p);
48867     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
48868     if( rc==SQLITE_OK ){
48869       if( iSavepoint<0 && pBt->initiallyEmpty ) pBt->nPage = 0;
48870       rc = newDatabase(pBt);
48871       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
48872
48873       /* The database size was written into the offset 28 of the header
48874       ** when the transaction started, so we know that the value at offset
48875       ** 28 is nonzero. */
48876       assert( pBt->nPage>0 );
48877     }
48878     sqlite3BtreeLeave(p);
48879   }
48880   return rc;
48881 }
48882
48883 /*
48884 ** Create a new cursor for the BTree whose root is on the page
48885 ** iTable. If a read-only cursor is requested, it is assumed that
48886 ** the caller already has at least a read-only transaction open
48887 ** on the database already. If a write-cursor is requested, then
48888 ** the caller is assumed to have an open write transaction.
48889 **
48890 ** If wrFlag==0, then the cursor can only be used for reading.
48891 ** If wrFlag==1, then the cursor can be used for reading or for
48892 ** writing if other conditions for writing are also met.  These
48893 ** are the conditions that must be met in order for writing to
48894 ** be allowed:
48895 **
48896 ** 1:  The cursor must have been opened with wrFlag==1
48897 **
48898 ** 2:  Other database connections that share the same pager cache
48899 **     but which are not in the READ_UNCOMMITTED state may not have
48900 **     cursors open with wrFlag==0 on the same table.  Otherwise
48901 **     the changes made by this write cursor would be visible to
48902 **     the read cursors in the other database connection.
48903 **
48904 ** 3:  The database must be writable (not on read-only media)
48905 **
48906 ** 4:  There must be an active transaction.
48907 **
48908 ** No checking is done to make sure that page iTable really is the
48909 ** root page of a b-tree.  If it is not, then the cursor acquired
48910 ** will not work correctly.
48911 **
48912 ** It is assumed that the sqlite3BtreeCursorZero() has been called
48913 ** on pCur to initialize the memory space prior to invoking this routine.
48914 */
48915 static int btreeCursor(
48916   Btree *p,                              /* The btree */
48917   int iTable,                            /* Root page of table to open */
48918   int wrFlag,                            /* 1 to write. 0 read-only */
48919   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
48920   BtCursor *pCur                         /* Space for new cursor */
48921 ){
48922   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
48923
48924   assert( sqlite3BtreeHoldsMutex(p) );
48925   assert( wrFlag==0 || wrFlag==1 );
48926
48927   /* The following assert statements verify that if this is a sharable 
48928   ** b-tree database, the connection is holding the required table locks, 
48929   ** and that no other connection has any open cursor that conflicts with 
48930   ** this lock.  */
48931   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
48932   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
48933
48934   /* Assert that the caller has opened the required transaction. */
48935   assert( p->inTrans>TRANS_NONE );
48936   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
48937   assert( pBt->pPage1 && pBt->pPage1->aData );
48938
48939   if( NEVER(wrFlag && pBt->readOnly) ){
48940     return SQLITE_READONLY;
48941   }
48942   if( iTable==1 && btreePagecount(pBt)==0 ){
48943     return SQLITE_EMPTY;
48944   }
48945
48946   /* Now that no other errors can occur, finish filling in the BtCursor
48947   ** variables and link the cursor into the BtShared list.  */
48948   pCur->pgnoRoot = (Pgno)iTable;
48949   pCur->iPage = -1;
48950   pCur->pKeyInfo = pKeyInfo;
48951   pCur->pBtree = p;
48952   pCur->pBt = pBt;
48953   pCur->wrFlag = (u8)wrFlag;
48954   pCur->pNext = pBt->pCursor;
48955   if( pCur->pNext ){
48956     pCur->pNext->pPrev = pCur;
48957   }
48958   pBt->pCursor = pCur;
48959   pCur->eState = CURSOR_INVALID;
48960   pCur->cachedRowid = 0;
48961   return SQLITE_OK;
48962 }
48963 SQLITE_PRIVATE int sqlite3BtreeCursor(
48964   Btree *p,                                   /* The btree */
48965   int iTable,                                 /* Root page of table to open */
48966   int wrFlag,                                 /* 1 to write. 0 read-only */
48967   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
48968   BtCursor *pCur                              /* Write new cursor here */
48969 ){
48970   int rc;
48971   sqlite3BtreeEnter(p);
48972   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
48973   sqlite3BtreeLeave(p);
48974   return rc;
48975 }
48976
48977 /*
48978 ** Return the size of a BtCursor object in bytes.
48979 **
48980 ** This interfaces is needed so that users of cursors can preallocate
48981 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
48982 ** to users so they cannot do the sizeof() themselves - they must call
48983 ** this routine.
48984 */
48985 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
48986   return ROUND8(sizeof(BtCursor));
48987 }
48988
48989 /*
48990 ** Initialize memory that will be converted into a BtCursor object.
48991 **
48992 ** The simple approach here would be to memset() the entire object
48993 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
48994 ** do not need to be zeroed and they are large, so we can save a lot
48995 ** of run-time by skipping the initialization of those elements.
48996 */
48997 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
48998   memset(p, 0, offsetof(BtCursor, iPage));
48999 }
49000
49001 /*
49002 ** Set the cached rowid value of every cursor in the same database file
49003 ** as pCur and having the same root page number as pCur.  The value is
49004 ** set to iRowid.
49005 **
49006 ** Only positive rowid values are considered valid for this cache.
49007 ** The cache is initialized to zero, indicating an invalid cache.
49008 ** A btree will work fine with zero or negative rowids.  We just cannot
49009 ** cache zero or negative rowids, which means tables that use zero or
49010 ** negative rowids might run a little slower.  But in practice, zero
49011 ** or negative rowids are very uncommon so this should not be a problem.
49012 */
49013 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
49014   BtCursor *p;
49015   for(p=pCur->pBt->pCursor; p; p=p->pNext){
49016     if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
49017   }
49018   assert( pCur->cachedRowid==iRowid );
49019 }
49020
49021 /*
49022 ** Return the cached rowid for the given cursor.  A negative or zero
49023 ** return value indicates that the rowid cache is invalid and should be
49024 ** ignored.  If the rowid cache has never before been set, then a
49025 ** zero is returned.
49026 */
49027 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
49028   return pCur->cachedRowid;
49029 }
49030
49031 /*
49032 ** Close a cursor.  The read lock on the database file is released
49033 ** when the last cursor is closed.
49034 */
49035 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
49036   Btree *pBtree = pCur->pBtree;
49037   if( pBtree ){
49038     int i;
49039     BtShared *pBt = pCur->pBt;
49040     sqlite3BtreeEnter(pBtree);
49041     sqlite3BtreeClearCursor(pCur);
49042     if( pCur->pPrev ){
49043       pCur->pPrev->pNext = pCur->pNext;
49044     }else{
49045       pBt->pCursor = pCur->pNext;
49046     }
49047     if( pCur->pNext ){
49048       pCur->pNext->pPrev = pCur->pPrev;
49049     }
49050     for(i=0; i<=pCur->iPage; i++){
49051       releasePage(pCur->apPage[i]);
49052     }
49053     unlockBtreeIfUnused(pBt);
49054     invalidateOverflowCache(pCur);
49055     /* sqlite3_free(pCur); */
49056     sqlite3BtreeLeave(pBtree);
49057   }
49058   return SQLITE_OK;
49059 }
49060
49061 /*
49062 ** Make sure the BtCursor* given in the argument has a valid
49063 ** BtCursor.info structure.  If it is not already valid, call
49064 ** btreeParseCell() to fill it in.
49065 **
49066 ** BtCursor.info is a cache of the information in the current cell.
49067 ** Using this cache reduces the number of calls to btreeParseCell().
49068 **
49069 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
49070 ** compiler to crash when getCellInfo() is implemented as a macro.
49071 ** But there is a measureable speed advantage to using the macro on gcc
49072 ** (when less compiler optimizations like -Os or -O0 are used and the
49073 ** compiler is not doing agressive inlining.)  So we use a real function
49074 ** for MSVC and a macro for everything else.  Ticket #2457.
49075 */
49076 #ifndef NDEBUG
49077   static void assertCellInfo(BtCursor *pCur){
49078     CellInfo info;
49079     int iPage = pCur->iPage;
49080     memset(&info, 0, sizeof(info));
49081     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
49082     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
49083   }
49084 #else
49085   #define assertCellInfo(x)
49086 #endif
49087 #ifdef _MSC_VER
49088   /* Use a real function in MSVC to work around bugs in that compiler. */
49089   static void getCellInfo(BtCursor *pCur){
49090     if( pCur->info.nSize==0 ){
49091       int iPage = pCur->iPage;
49092       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
49093       pCur->validNKey = 1;
49094     }else{
49095       assertCellInfo(pCur);
49096     }
49097   }
49098 #else /* if not _MSC_VER */
49099   /* Use a macro in all other compilers so that the function is inlined */
49100 #define getCellInfo(pCur)                                                      \
49101   if( pCur->info.nSize==0 ){                                                   \
49102     int iPage = pCur->iPage;                                                   \
49103     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
49104     pCur->validNKey = 1;                                                       \
49105   }else{                                                                       \
49106     assertCellInfo(pCur);                                                      \
49107   }
49108 #endif /* _MSC_VER */
49109
49110 #ifndef NDEBUG  /* The next routine used only within assert() statements */
49111 /*
49112 ** Return true if the given BtCursor is valid.  A valid cursor is one
49113 ** that is currently pointing to a row in a (non-empty) table.
49114 ** This is a verification routine is used only within assert() statements.
49115 */
49116 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
49117   return pCur && pCur->eState==CURSOR_VALID;
49118 }
49119 #endif /* NDEBUG */
49120
49121 /*
49122 ** Set *pSize to the size of the buffer needed to hold the value of
49123 ** the key for the current entry.  If the cursor is not pointing
49124 ** to a valid entry, *pSize is set to 0. 
49125 **
49126 ** For a table with the INTKEY flag set, this routine returns the key
49127 ** itself, not the number of bytes in the key.
49128 **
49129 ** The caller must position the cursor prior to invoking this routine.
49130 ** 
49131 ** This routine cannot fail.  It always returns SQLITE_OK.  
49132 */
49133 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
49134   assert( cursorHoldsMutex(pCur) );
49135   assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
49136   if( pCur->eState!=CURSOR_VALID ){
49137     *pSize = 0;
49138   }else{
49139     getCellInfo(pCur);
49140     *pSize = pCur->info.nKey;
49141   }
49142   return SQLITE_OK;
49143 }
49144
49145 /*
49146 ** Set *pSize to the number of bytes of data in the entry the
49147 ** cursor currently points to.
49148 **
49149 ** The caller must guarantee that the cursor is pointing to a non-NULL
49150 ** valid entry.  In other words, the calling procedure must guarantee
49151 ** that the cursor has Cursor.eState==CURSOR_VALID.
49152 **
49153 ** Failure is not possible.  This function always returns SQLITE_OK.
49154 ** It might just as well be a procedure (returning void) but we continue
49155 ** to return an integer result code for historical reasons.
49156 */
49157 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
49158   assert( cursorHoldsMutex(pCur) );
49159   assert( pCur->eState==CURSOR_VALID );
49160   getCellInfo(pCur);
49161   *pSize = pCur->info.nData;
49162   return SQLITE_OK;
49163 }
49164
49165 /*
49166 ** Given the page number of an overflow page in the database (parameter
49167 ** ovfl), this function finds the page number of the next page in the 
49168 ** linked list of overflow pages. If possible, it uses the auto-vacuum
49169 ** pointer-map data instead of reading the content of page ovfl to do so. 
49170 **
49171 ** If an error occurs an SQLite error code is returned. Otherwise:
49172 **
49173 ** The page number of the next overflow page in the linked list is 
49174 ** written to *pPgnoNext. If page ovfl is the last page in its linked 
49175 ** list, *pPgnoNext is set to zero. 
49176 **
49177 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
49178 ** to page number pOvfl was obtained, then *ppPage is set to point to that
49179 ** reference. It is the responsibility of the caller to call releasePage()
49180 ** on *ppPage to free the reference. In no reference was obtained (because
49181 ** the pointer-map was used to obtain the value for *pPgnoNext), then
49182 ** *ppPage is set to zero.
49183 */
49184 static int getOverflowPage(
49185   BtShared *pBt,               /* The database file */
49186   Pgno ovfl,                   /* Current overflow page number */
49187   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
49188   Pgno *pPgnoNext              /* OUT: Next overflow page number */
49189 ){
49190   Pgno next = 0;
49191   MemPage *pPage = 0;
49192   int rc = SQLITE_OK;
49193
49194   assert( sqlite3_mutex_held(pBt->mutex) );
49195   assert(pPgnoNext);
49196
49197 #ifndef SQLITE_OMIT_AUTOVACUUM
49198   /* Try to find the next page in the overflow list using the
49199   ** autovacuum pointer-map pages. Guess that the next page in 
49200   ** the overflow list is page number (ovfl+1). If that guess turns 
49201   ** out to be wrong, fall back to loading the data of page 
49202   ** number ovfl to determine the next page number.
49203   */
49204   if( pBt->autoVacuum ){
49205     Pgno pgno;
49206     Pgno iGuess = ovfl+1;
49207     u8 eType;
49208
49209     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
49210       iGuess++;
49211     }
49212
49213     if( iGuess<=btreePagecount(pBt) ){
49214       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
49215       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
49216         next = iGuess;
49217         rc = SQLITE_DONE;
49218       }
49219     }
49220   }
49221 #endif
49222
49223   assert( next==0 || rc==SQLITE_DONE );
49224   if( rc==SQLITE_OK ){
49225     rc = btreeGetPage(pBt, ovfl, &pPage, 0);
49226     assert( rc==SQLITE_OK || pPage==0 );
49227     if( rc==SQLITE_OK ){
49228       next = get4byte(pPage->aData);
49229     }
49230   }
49231
49232   *pPgnoNext = next;
49233   if( ppPage ){
49234     *ppPage = pPage;
49235   }else{
49236     releasePage(pPage);
49237   }
49238   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
49239 }
49240
49241 /*
49242 ** Copy data from a buffer to a page, or from a page to a buffer.
49243 **
49244 ** pPayload is a pointer to data stored on database page pDbPage.
49245 ** If argument eOp is false, then nByte bytes of data are copied
49246 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
49247 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
49248 ** of data are copied from the buffer pBuf to pPayload.
49249 **
49250 ** SQLITE_OK is returned on success, otherwise an error code.
49251 */
49252 static int copyPayload(
49253   void *pPayload,           /* Pointer to page data */
49254   void *pBuf,               /* Pointer to buffer */
49255   int nByte,                /* Number of bytes to copy */
49256   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
49257   DbPage *pDbPage           /* Page containing pPayload */
49258 ){
49259   if( eOp ){
49260     /* Copy data from buffer to page (a write operation) */
49261     int rc = sqlite3PagerWrite(pDbPage);
49262     if( rc!=SQLITE_OK ){
49263       return rc;
49264     }
49265     memcpy(pPayload, pBuf, nByte);
49266   }else{
49267     /* Copy data from page to buffer (a read operation) */
49268     memcpy(pBuf, pPayload, nByte);
49269   }
49270   return SQLITE_OK;
49271 }
49272
49273 /*
49274 ** This function is used to read or overwrite payload information
49275 ** for the entry that the pCur cursor is pointing to. If the eOp
49276 ** parameter is 0, this is a read operation (data copied into
49277 ** buffer pBuf). If it is non-zero, a write (data copied from
49278 ** buffer pBuf).
49279 **
49280 ** A total of "amt" bytes are read or written beginning at "offset".
49281 ** Data is read to or from the buffer pBuf.
49282 **
49283 ** The content being read or written might appear on the main page
49284 ** or be scattered out on multiple overflow pages.
49285 **
49286 ** If the BtCursor.isIncrblobHandle flag is set, and the current
49287 ** cursor entry uses one or more overflow pages, this function
49288 ** allocates space for and lazily popluates the overflow page-list 
49289 ** cache array (BtCursor.aOverflow). Subsequent calls use this
49290 ** cache to make seeking to the supplied offset more efficient.
49291 **
49292 ** Once an overflow page-list cache has been allocated, it may be
49293 ** invalidated if some other cursor writes to the same table, or if
49294 ** the cursor is moved to a different row. Additionally, in auto-vacuum
49295 ** mode, the following events may invalidate an overflow page-list cache.
49296 **
49297 **   * An incremental vacuum,
49298 **   * A commit in auto_vacuum="full" mode,
49299 **   * Creating a table (may require moving an overflow page).
49300 */
49301 static int accessPayload(
49302   BtCursor *pCur,      /* Cursor pointing to entry to read from */
49303   u32 offset,          /* Begin reading this far into payload */
49304   u32 amt,             /* Read this many bytes */
49305   unsigned char *pBuf, /* Write the bytes into this buffer */ 
49306   int eOp              /* zero to read. non-zero to write. */
49307 ){
49308   unsigned char *aPayload;
49309   int rc = SQLITE_OK;
49310   u32 nKey;
49311   int iIdx = 0;
49312   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
49313   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
49314
49315   assert( pPage );
49316   assert( pCur->eState==CURSOR_VALID );
49317   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
49318   assert( cursorHoldsMutex(pCur) );
49319
49320   getCellInfo(pCur);
49321   aPayload = pCur->info.pCell + pCur->info.nHeader;
49322   nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
49323
49324   if( NEVER(offset+amt > nKey+pCur->info.nData) 
49325    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
49326   ){
49327     /* Trying to read or write past the end of the data is an error */
49328     return SQLITE_CORRUPT_BKPT;
49329   }
49330
49331   /* Check if data must be read/written to/from the btree page itself. */
49332   if( offset<pCur->info.nLocal ){
49333     int a = amt;
49334     if( a+offset>pCur->info.nLocal ){
49335       a = pCur->info.nLocal - offset;
49336     }
49337     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
49338     offset = 0;
49339     pBuf += a;
49340     amt -= a;
49341   }else{
49342     offset -= pCur->info.nLocal;
49343   }
49344
49345   if( rc==SQLITE_OK && amt>0 ){
49346     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
49347     Pgno nextPage;
49348
49349     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
49350
49351 #ifndef SQLITE_OMIT_INCRBLOB
49352     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
49353     ** has not been allocated, allocate it now. The array is sized at
49354     ** one entry for each overflow page in the overflow chain. The
49355     ** page number of the first overflow page is stored in aOverflow[0],
49356     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
49357     ** (the cache is lazily populated).
49358     */
49359     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
49360       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
49361       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
49362       /* nOvfl is always positive.  If it were zero, fetchPayload would have
49363       ** been used instead of this routine. */
49364       if( ALWAYS(nOvfl) && !pCur->aOverflow ){
49365         rc = SQLITE_NOMEM;
49366       }
49367     }
49368
49369     /* If the overflow page-list cache has been allocated and the
49370     ** entry for the first required overflow page is valid, skip
49371     ** directly to it.
49372     */
49373     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
49374       iIdx = (offset/ovflSize);
49375       nextPage = pCur->aOverflow[iIdx];
49376       offset = (offset%ovflSize);
49377     }
49378 #endif
49379
49380     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
49381
49382 #ifndef SQLITE_OMIT_INCRBLOB
49383       /* If required, populate the overflow page-list cache. */
49384       if( pCur->aOverflow ){
49385         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
49386         pCur->aOverflow[iIdx] = nextPage;
49387       }
49388 #endif
49389
49390       if( offset>=ovflSize ){
49391         /* The only reason to read this page is to obtain the page
49392         ** number for the next page in the overflow chain. The page
49393         ** data is not required. So first try to lookup the overflow
49394         ** page-list cache, if any, then fall back to the getOverflowPage()
49395         ** function.
49396         */
49397 #ifndef SQLITE_OMIT_INCRBLOB
49398         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
49399           nextPage = pCur->aOverflow[iIdx+1];
49400         } else 
49401 #endif
49402           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
49403         offset -= ovflSize;
49404       }else{
49405         /* Need to read this page properly. It contains some of the
49406         ** range of data that is being read (eOp==0) or written (eOp!=0).
49407         */
49408         DbPage *pDbPage;
49409         int a = amt;
49410         rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
49411         if( rc==SQLITE_OK ){
49412           aPayload = sqlite3PagerGetData(pDbPage);
49413           nextPage = get4byte(aPayload);
49414           if( a + offset > ovflSize ){
49415             a = ovflSize - offset;
49416           }
49417           rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
49418           sqlite3PagerUnref(pDbPage);
49419           offset = 0;
49420           amt -= a;
49421           pBuf += a;
49422         }
49423       }
49424     }
49425   }
49426
49427   if( rc==SQLITE_OK && amt>0 ){
49428     return SQLITE_CORRUPT_BKPT;
49429   }
49430   return rc;
49431 }
49432
49433 /*
49434 ** Read part of the key associated with cursor pCur.  Exactly
49435 ** "amt" bytes will be transfered into pBuf[].  The transfer
49436 ** begins at "offset".
49437 **
49438 ** The caller must ensure that pCur is pointing to a valid row
49439 ** in the table.
49440 **
49441 ** Return SQLITE_OK on success or an error code if anything goes
49442 ** wrong.  An error is returned if "offset+amt" is larger than
49443 ** the available payload.
49444 */
49445 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
49446   assert( cursorHoldsMutex(pCur) );
49447   assert( pCur->eState==CURSOR_VALID );
49448   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
49449   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
49450   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
49451 }
49452
49453 /*
49454 ** Read part of the data associated with cursor pCur.  Exactly
49455 ** "amt" bytes will be transfered into pBuf[].  The transfer
49456 ** begins at "offset".
49457 **
49458 ** Return SQLITE_OK on success or an error code if anything goes
49459 ** wrong.  An error is returned if "offset+amt" is larger than
49460 ** the available payload.
49461 */
49462 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
49463   int rc;
49464
49465 #ifndef SQLITE_OMIT_INCRBLOB
49466   if ( pCur->eState==CURSOR_INVALID ){
49467     return SQLITE_ABORT;
49468   }
49469 #endif
49470
49471   assert( cursorHoldsMutex(pCur) );
49472   rc = restoreCursorPosition(pCur);
49473   if( rc==SQLITE_OK ){
49474     assert( pCur->eState==CURSOR_VALID );
49475     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
49476     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
49477     rc = accessPayload(pCur, offset, amt, pBuf, 0);
49478   }
49479   return rc;
49480 }
49481
49482 /*
49483 ** Return a pointer to payload information from the entry that the 
49484 ** pCur cursor is pointing to.  The pointer is to the beginning of
49485 ** the key if skipKey==0 and it points to the beginning of data if
49486 ** skipKey==1.  The number of bytes of available key/data is written
49487 ** into *pAmt.  If *pAmt==0, then the value returned will not be
49488 ** a valid pointer.
49489 **
49490 ** This routine is an optimization.  It is common for the entire key
49491 ** and data to fit on the local page and for there to be no overflow
49492 ** pages.  When that is so, this routine can be used to access the
49493 ** key and data without making a copy.  If the key and/or data spills
49494 ** onto overflow pages, then accessPayload() must be used to reassemble
49495 ** the key/data and copy it into a preallocated buffer.
49496 **
49497 ** The pointer returned by this routine looks directly into the cached
49498 ** page of the database.  The data might change or move the next time
49499 ** any btree routine is called.
49500 */
49501 static const unsigned char *fetchPayload(
49502   BtCursor *pCur,      /* Cursor pointing to entry to read from */
49503   int *pAmt,           /* Write the number of available bytes here */
49504   int skipKey          /* read beginning at data if this is true */
49505 ){
49506   unsigned char *aPayload;
49507   MemPage *pPage;
49508   u32 nKey;
49509   u32 nLocal;
49510
49511   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
49512   assert( pCur->eState==CURSOR_VALID );
49513   assert( cursorHoldsMutex(pCur) );
49514   pPage = pCur->apPage[pCur->iPage];
49515   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
49516   if( NEVER(pCur->info.nSize==0) ){
49517     btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
49518                    &pCur->info);
49519   }
49520   aPayload = pCur->info.pCell;
49521   aPayload += pCur->info.nHeader;
49522   if( pPage->intKey ){
49523     nKey = 0;
49524   }else{
49525     nKey = (int)pCur->info.nKey;
49526   }
49527   if( skipKey ){
49528     aPayload += nKey;
49529     nLocal = pCur->info.nLocal - nKey;
49530   }else{
49531     nLocal = pCur->info.nLocal;
49532     assert( nLocal<=nKey );
49533   }
49534   *pAmt = nLocal;
49535   return aPayload;
49536 }
49537
49538
49539 /*
49540 ** For the entry that cursor pCur is point to, return as
49541 ** many bytes of the key or data as are available on the local
49542 ** b-tree page.  Write the number of available bytes into *pAmt.
49543 **
49544 ** The pointer returned is ephemeral.  The key/data may move
49545 ** or be destroyed on the next call to any Btree routine,
49546 ** including calls from other threads against the same cache.
49547 ** Hence, a mutex on the BtShared should be held prior to calling
49548 ** this routine.
49549 **
49550 ** These routines is used to get quick access to key and data
49551 ** in the common case where no overflow pages are used.
49552 */
49553 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
49554   const void *p = 0;
49555   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
49556   assert( cursorHoldsMutex(pCur) );
49557   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
49558     p = (const void*)fetchPayload(pCur, pAmt, 0);
49559   }
49560   return p;
49561 }
49562 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
49563   const void *p = 0;
49564   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
49565   assert( cursorHoldsMutex(pCur) );
49566   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
49567     p = (const void*)fetchPayload(pCur, pAmt, 1);
49568   }
49569   return p;
49570 }
49571
49572
49573 /*
49574 ** Move the cursor down to a new child page.  The newPgno argument is the
49575 ** page number of the child page to move to.
49576 **
49577 ** This function returns SQLITE_CORRUPT if the page-header flags field of
49578 ** the new child page does not match the flags field of the parent (i.e.
49579 ** if an intkey page appears to be the parent of a non-intkey page, or
49580 ** vice-versa).
49581 */
49582 static int moveToChild(BtCursor *pCur, u32 newPgno){
49583   int rc;
49584   int i = pCur->iPage;
49585   MemPage *pNewPage;
49586   BtShared *pBt = pCur->pBt;
49587
49588   assert( cursorHoldsMutex(pCur) );
49589   assert( pCur->eState==CURSOR_VALID );
49590   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
49591   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
49592     return SQLITE_CORRUPT_BKPT;
49593   }
49594   rc = getAndInitPage(pBt, newPgno, &pNewPage);
49595   if( rc ) return rc;
49596   pCur->apPage[i+1] = pNewPage;
49597   pCur->aiIdx[i+1] = 0;
49598   pCur->iPage++;
49599
49600   pCur->info.nSize = 0;
49601   pCur->validNKey = 0;
49602   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
49603     return SQLITE_CORRUPT_BKPT;
49604   }
49605   return SQLITE_OK;
49606 }
49607
49608 #ifndef NDEBUG
49609 /*
49610 ** Page pParent is an internal (non-leaf) tree page. This function 
49611 ** asserts that page number iChild is the left-child if the iIdx'th
49612 ** cell in page pParent. Or, if iIdx is equal to the total number of
49613 ** cells in pParent, that page number iChild is the right-child of
49614 ** the page.
49615 */
49616 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
49617   assert( iIdx<=pParent->nCell );
49618   if( iIdx==pParent->nCell ){
49619     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
49620   }else{
49621     assert( get4byte(findCell(pParent, iIdx))==iChild );
49622   }
49623 }
49624 #else
49625 #  define assertParentIndex(x,y,z) 
49626 #endif
49627
49628 /*
49629 ** Move the cursor up to the parent page.
49630 **
49631 ** pCur->idx is set to the cell index that contains the pointer
49632 ** to the page we are coming from.  If we are coming from the
49633 ** right-most child page then pCur->idx is set to one more than
49634 ** the largest cell index.
49635 */
49636 static void moveToParent(BtCursor *pCur){
49637   assert( cursorHoldsMutex(pCur) );
49638   assert( pCur->eState==CURSOR_VALID );
49639   assert( pCur->iPage>0 );
49640   assert( pCur->apPage[pCur->iPage] );
49641   assertParentIndex(
49642     pCur->apPage[pCur->iPage-1], 
49643     pCur->aiIdx[pCur->iPage-1], 
49644     pCur->apPage[pCur->iPage]->pgno
49645   );
49646   releasePage(pCur->apPage[pCur->iPage]);
49647   pCur->iPage--;
49648   pCur->info.nSize = 0;
49649   pCur->validNKey = 0;
49650 }
49651
49652 /*
49653 ** Move the cursor to point to the root page of its b-tree structure.
49654 **
49655 ** If the table has a virtual root page, then the cursor is moved to point
49656 ** to the virtual root page instead of the actual root page. A table has a
49657 ** virtual root page when the actual root page contains no cells and a 
49658 ** single child page. This can only happen with the table rooted at page 1.
49659 **
49660 ** If the b-tree structure is empty, the cursor state is set to 
49661 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
49662 ** cell located on the root (or virtual root) page and the cursor state
49663 ** is set to CURSOR_VALID.
49664 **
49665 ** If this function returns successfully, it may be assumed that the
49666 ** page-header flags indicate that the [virtual] root-page is the expected 
49667 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
49668 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
49669 ** indicating a table b-tree, or if the caller did specify a KeyInfo 
49670 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
49671 ** b-tree).
49672 */
49673 static int moveToRoot(BtCursor *pCur){
49674   MemPage *pRoot;
49675   int rc = SQLITE_OK;
49676   Btree *p = pCur->pBtree;
49677   BtShared *pBt = p->pBt;
49678
49679   assert( cursorHoldsMutex(pCur) );
49680   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
49681   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
49682   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
49683   if( pCur->eState>=CURSOR_REQUIRESEEK ){
49684     if( pCur->eState==CURSOR_FAULT ){
49685       assert( pCur->skipNext!=SQLITE_OK );
49686       return pCur->skipNext;
49687     }
49688     sqlite3BtreeClearCursor(pCur);
49689   }
49690
49691   if( pCur->iPage>=0 ){
49692     int i;
49693     for(i=1; i<=pCur->iPage; i++){
49694       releasePage(pCur->apPage[i]);
49695     }
49696     pCur->iPage = 0;
49697   }else{
49698     rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
49699     if( rc!=SQLITE_OK ){
49700       pCur->eState = CURSOR_INVALID;
49701       return rc;
49702     }
49703     pCur->iPage = 0;
49704
49705     /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
49706     ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
49707     ** NULL, the caller expects a table b-tree. If this is not the case,
49708     ** return an SQLITE_CORRUPT error.  */
49709     assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
49710     if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
49711       return SQLITE_CORRUPT_BKPT;
49712     }
49713   }
49714
49715   /* Assert that the root page is of the correct type. This must be the
49716   ** case as the call to this function that loaded the root-page (either
49717   ** this call or a previous invocation) would have detected corruption 
49718   ** if the assumption were not true, and it is not possible for the flags 
49719   ** byte to have been modified while this cursor is holding a reference
49720   ** to the page.  */
49721   pRoot = pCur->apPage[0];
49722   assert( pRoot->pgno==pCur->pgnoRoot );
49723   assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
49724
49725   pCur->aiIdx[0] = 0;
49726   pCur->info.nSize = 0;
49727   pCur->atLast = 0;
49728   pCur->validNKey = 0;
49729
49730   if( pRoot->nCell==0 && !pRoot->leaf ){
49731     Pgno subpage;
49732     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
49733     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
49734     pCur->eState = CURSOR_VALID;
49735     rc = moveToChild(pCur, subpage);
49736   }else{
49737     pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
49738   }
49739   return rc;
49740 }
49741
49742 /*
49743 ** Move the cursor down to the left-most leaf entry beneath the
49744 ** entry to which it is currently pointing.
49745 **
49746 ** The left-most leaf is the one with the smallest key - the first
49747 ** in ascending order.
49748 */
49749 static int moveToLeftmost(BtCursor *pCur){
49750   Pgno pgno;
49751   int rc = SQLITE_OK;
49752   MemPage *pPage;
49753
49754   assert( cursorHoldsMutex(pCur) );
49755   assert( pCur->eState==CURSOR_VALID );
49756   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
49757     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
49758     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
49759     rc = moveToChild(pCur, pgno);
49760   }
49761   return rc;
49762 }
49763
49764 /*
49765 ** Move the cursor down to the right-most leaf entry beneath the
49766 ** page to which it is currently pointing.  Notice the difference
49767 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
49768 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
49769 ** finds the right-most entry beneath the *page*.
49770 **
49771 ** The right-most entry is the one with the largest key - the last
49772 ** key in ascending order.
49773 */
49774 static int moveToRightmost(BtCursor *pCur){
49775   Pgno pgno;
49776   int rc = SQLITE_OK;
49777   MemPage *pPage = 0;
49778
49779   assert( cursorHoldsMutex(pCur) );
49780   assert( pCur->eState==CURSOR_VALID );
49781   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
49782     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
49783     pCur->aiIdx[pCur->iPage] = pPage->nCell;
49784     rc = moveToChild(pCur, pgno);
49785   }
49786   if( rc==SQLITE_OK ){
49787     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
49788     pCur->info.nSize = 0;
49789     pCur->validNKey = 0;
49790   }
49791   return rc;
49792 }
49793
49794 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
49795 ** on success.  Set *pRes to 0 if the cursor actually points to something
49796 ** or set *pRes to 1 if the table is empty.
49797 */
49798 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
49799   int rc;
49800
49801   assert( cursorHoldsMutex(pCur) );
49802   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
49803   rc = moveToRoot(pCur);
49804   if( rc==SQLITE_OK ){
49805     if( pCur->eState==CURSOR_INVALID ){
49806       assert( pCur->apPage[pCur->iPage]->nCell==0 );
49807       *pRes = 1;
49808     }else{
49809       assert( pCur->apPage[pCur->iPage]->nCell>0 );
49810       *pRes = 0;
49811       rc = moveToLeftmost(pCur);
49812     }
49813   }
49814   return rc;
49815 }
49816
49817 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
49818 ** on success.  Set *pRes to 0 if the cursor actually points to something
49819 ** or set *pRes to 1 if the table is empty.
49820 */
49821 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
49822   int rc;
49823  
49824   assert( cursorHoldsMutex(pCur) );
49825   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
49826
49827   /* If the cursor already points to the last entry, this is a no-op. */
49828   if( CURSOR_VALID==pCur->eState && pCur->atLast ){
49829 #ifdef SQLITE_DEBUG
49830     /* This block serves to assert() that the cursor really does point 
49831     ** to the last entry in the b-tree. */
49832     int ii;
49833     for(ii=0; ii<pCur->iPage; ii++){
49834       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
49835     }
49836     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
49837     assert( pCur->apPage[pCur->iPage]->leaf );
49838 #endif
49839     return SQLITE_OK;
49840   }
49841
49842   rc = moveToRoot(pCur);
49843   if( rc==SQLITE_OK ){
49844     if( CURSOR_INVALID==pCur->eState ){
49845       assert( pCur->apPage[pCur->iPage]->nCell==0 );
49846       *pRes = 1;
49847     }else{
49848       assert( pCur->eState==CURSOR_VALID );
49849       *pRes = 0;
49850       rc = moveToRightmost(pCur);
49851       pCur->atLast = rc==SQLITE_OK ?1:0;
49852     }
49853   }
49854   return rc;
49855 }
49856
49857 /* Move the cursor so that it points to an entry near the key 
49858 ** specified by pIdxKey or intKey.   Return a success code.
49859 **
49860 ** For INTKEY tables, the intKey parameter is used.  pIdxKey 
49861 ** must be NULL.  For index tables, pIdxKey is used and intKey
49862 ** is ignored.
49863 **
49864 ** If an exact match is not found, then the cursor is always
49865 ** left pointing at a leaf page which would hold the entry if it
49866 ** were present.  The cursor might point to an entry that comes
49867 ** before or after the key.
49868 **
49869 ** An integer is written into *pRes which is the result of
49870 ** comparing the key with the entry to which the cursor is 
49871 ** pointing.  The meaning of the integer written into
49872 ** *pRes is as follows:
49873 **
49874 **     *pRes<0      The cursor is left pointing at an entry that
49875 **                  is smaller than intKey/pIdxKey or if the table is empty
49876 **                  and the cursor is therefore left point to nothing.
49877 **
49878 **     *pRes==0     The cursor is left pointing at an entry that
49879 **                  exactly matches intKey/pIdxKey.
49880 **
49881 **     *pRes>0      The cursor is left pointing at an entry that
49882 **                  is larger than intKey/pIdxKey.
49883 **
49884 */
49885 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
49886   BtCursor *pCur,          /* The cursor to be moved */
49887   UnpackedRecord *pIdxKey, /* Unpacked index key */
49888   i64 intKey,              /* The table key */
49889   int biasRight,           /* If true, bias the search to the high end */
49890   int *pRes                /* Write search results here */
49891 ){
49892   int rc;
49893
49894   assert( cursorHoldsMutex(pCur) );
49895   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
49896   assert( pRes );
49897   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
49898
49899   /* If the cursor is already positioned at the point we are trying
49900   ** to move to, then just return without doing any work */
49901   if( pCur->eState==CURSOR_VALID && pCur->validNKey 
49902    && pCur->apPage[0]->intKey 
49903   ){
49904     if( pCur->info.nKey==intKey ){
49905       *pRes = 0;
49906       return SQLITE_OK;
49907     }
49908     if( pCur->atLast && pCur->info.nKey<intKey ){
49909       *pRes = -1;
49910       return SQLITE_OK;
49911     }
49912   }
49913
49914   rc = moveToRoot(pCur);
49915   if( rc ){
49916     return rc;
49917   }
49918   assert( pCur->apPage[pCur->iPage] );
49919   assert( pCur->apPage[pCur->iPage]->isInit );
49920   assert( pCur->apPage[pCur->iPage]->nCell>0 || pCur->eState==CURSOR_INVALID );
49921   if( pCur->eState==CURSOR_INVALID ){
49922     *pRes = -1;
49923     assert( pCur->apPage[pCur->iPage]->nCell==0 );
49924     return SQLITE_OK;
49925   }
49926   assert( pCur->apPage[0]->intKey || pIdxKey );
49927   for(;;){
49928     int lwr, upr;
49929     Pgno chldPg;
49930     MemPage *pPage = pCur->apPage[pCur->iPage];
49931     int c;
49932
49933     /* pPage->nCell must be greater than zero. If this is the root-page
49934     ** the cursor would have been INVALID above and this for(;;) loop
49935     ** not run. If this is not the root-page, then the moveToChild() routine
49936     ** would have already detected db corruption. Similarly, pPage must
49937     ** be the right kind (index or table) of b-tree page. Otherwise
49938     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
49939     assert( pPage->nCell>0 );
49940     assert( pPage->intKey==(pIdxKey==0) );
49941     lwr = 0;
49942     upr = pPage->nCell-1;
49943     if( biasRight ){
49944       pCur->aiIdx[pCur->iPage] = (u16)upr;
49945     }else{
49946       pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
49947     }
49948     for(;;){
49949       int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
49950       u8 *pCell;                          /* Pointer to current cell in pPage */
49951
49952       pCur->info.nSize = 0;
49953       pCell = findCell(pPage, idx) + pPage->childPtrSize;
49954       if( pPage->intKey ){
49955         i64 nCellKey;
49956         if( pPage->hasData ){
49957           u32 dummy;
49958           pCell += getVarint32(pCell, dummy);
49959         }
49960         getVarint(pCell, (u64*)&nCellKey);
49961         if( nCellKey==intKey ){
49962           c = 0;
49963         }else if( nCellKey<intKey ){
49964           c = -1;
49965         }else{
49966           assert( nCellKey>intKey );
49967           c = +1;
49968         }
49969         pCur->validNKey = 1;
49970         pCur->info.nKey = nCellKey;
49971       }else{
49972         /* The maximum supported page-size is 65536 bytes. This means that
49973         ** the maximum number of record bytes stored on an index B-Tree
49974         ** page is less than 16384 bytes and may be stored as a 2-byte
49975         ** varint. This information is used to attempt to avoid parsing 
49976         ** the entire cell by checking for the cases where the record is 
49977         ** stored entirely within the b-tree page by inspecting the first 
49978         ** 2 bytes of the cell.
49979         */
49980         int nCell = pCell[0];
49981         if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
49982           /* This branch runs if the record-size field of the cell is a
49983           ** single byte varint and the record fits entirely on the main
49984           ** b-tree page.  */
49985           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
49986         }else if( !(pCell[1] & 0x80) 
49987           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
49988         ){
49989           /* The record-size field is a 2 byte varint and the record 
49990           ** fits entirely on the main b-tree page.  */
49991           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
49992         }else{
49993           /* The record flows over onto one or more overflow pages. In
49994           ** this case the whole cell needs to be parsed, a buffer allocated
49995           ** and accessPayload() used to retrieve the record into the
49996           ** buffer before VdbeRecordCompare() can be called. */
49997           void *pCellKey;
49998           u8 * const pCellBody = pCell - pPage->childPtrSize;
49999           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
50000           nCell = (int)pCur->info.nKey;
50001           pCellKey = sqlite3Malloc( nCell );
50002           if( pCellKey==0 ){
50003             rc = SQLITE_NOMEM;
50004             goto moveto_finish;
50005           }
50006           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
50007           if( rc ){
50008             sqlite3_free(pCellKey);
50009             goto moveto_finish;
50010           }
50011           c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
50012           sqlite3_free(pCellKey);
50013         }
50014       }
50015       if( c==0 ){
50016         if( pPage->intKey && !pPage->leaf ){
50017           lwr = idx;
50018           upr = lwr - 1;
50019           break;
50020         }else{
50021           *pRes = 0;
50022           rc = SQLITE_OK;
50023           goto moveto_finish;
50024         }
50025       }
50026       if( c<0 ){
50027         lwr = idx+1;
50028       }else{
50029         upr = idx-1;
50030       }
50031       if( lwr>upr ){
50032         break;
50033       }
50034       pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
50035     }
50036     assert( lwr==upr+1 );
50037     assert( pPage->isInit );
50038     if( pPage->leaf ){
50039       chldPg = 0;
50040     }else if( lwr>=pPage->nCell ){
50041       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
50042     }else{
50043       chldPg = get4byte(findCell(pPage, lwr));
50044     }
50045     if( chldPg==0 ){
50046       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
50047       *pRes = c;
50048       rc = SQLITE_OK;
50049       goto moveto_finish;
50050     }
50051     pCur->aiIdx[pCur->iPage] = (u16)lwr;
50052     pCur->info.nSize = 0;
50053     pCur->validNKey = 0;
50054     rc = moveToChild(pCur, chldPg);
50055     if( rc ) goto moveto_finish;
50056   }
50057 moveto_finish:
50058   return rc;
50059 }
50060
50061
50062 /*
50063 ** Return TRUE if the cursor is not pointing at an entry of the table.
50064 **
50065 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
50066 ** past the last entry in the table or sqlite3BtreePrev() moves past
50067 ** the first entry.  TRUE is also returned if the table is empty.
50068 */
50069 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
50070   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
50071   ** have been deleted? This API will need to change to return an error code
50072   ** as well as the boolean result value.
50073   */
50074   return (CURSOR_VALID!=pCur->eState);
50075 }
50076
50077 /*
50078 ** Advance the cursor to the next entry in the database.  If
50079 ** successful then set *pRes=0.  If the cursor
50080 ** was already pointing to the last entry in the database before
50081 ** this routine was called, then set *pRes=1.
50082 */
50083 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
50084   int rc;
50085   int idx;
50086   MemPage *pPage;
50087
50088   assert( cursorHoldsMutex(pCur) );
50089   rc = restoreCursorPosition(pCur);
50090   if( rc!=SQLITE_OK ){
50091     return rc;
50092   }
50093   assert( pRes!=0 );
50094   if( CURSOR_INVALID==pCur->eState ){
50095     *pRes = 1;
50096     return SQLITE_OK;
50097   }
50098   if( pCur->skipNext>0 ){
50099     pCur->skipNext = 0;
50100     *pRes = 0;
50101     return SQLITE_OK;
50102   }
50103   pCur->skipNext = 0;
50104
50105   pPage = pCur->apPage[pCur->iPage];
50106   idx = ++pCur->aiIdx[pCur->iPage];
50107   assert( pPage->isInit );
50108   assert( idx<=pPage->nCell );
50109
50110   pCur->info.nSize = 0;
50111   pCur->validNKey = 0;
50112   if( idx>=pPage->nCell ){
50113     if( !pPage->leaf ){
50114       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
50115       if( rc ) return rc;
50116       rc = moveToLeftmost(pCur);
50117       *pRes = 0;
50118       return rc;
50119     }
50120     do{
50121       if( pCur->iPage==0 ){
50122         *pRes = 1;
50123         pCur->eState = CURSOR_INVALID;
50124         return SQLITE_OK;
50125       }
50126       moveToParent(pCur);
50127       pPage = pCur->apPage[pCur->iPage];
50128     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
50129     *pRes = 0;
50130     if( pPage->intKey ){
50131       rc = sqlite3BtreeNext(pCur, pRes);
50132     }else{
50133       rc = SQLITE_OK;
50134     }
50135     return rc;
50136   }
50137   *pRes = 0;
50138   if( pPage->leaf ){
50139     return SQLITE_OK;
50140   }
50141   rc = moveToLeftmost(pCur);
50142   return rc;
50143 }
50144
50145
50146 /*
50147 ** Step the cursor to the back to the previous entry in the database.  If
50148 ** successful then set *pRes=0.  If the cursor
50149 ** was already pointing to the first entry in the database before
50150 ** this routine was called, then set *pRes=1.
50151 */
50152 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
50153   int rc;
50154   MemPage *pPage;
50155
50156   assert( cursorHoldsMutex(pCur) );
50157   rc = restoreCursorPosition(pCur);
50158   if( rc!=SQLITE_OK ){
50159     return rc;
50160   }
50161   pCur->atLast = 0;
50162   if( CURSOR_INVALID==pCur->eState ){
50163     *pRes = 1;
50164     return SQLITE_OK;
50165   }
50166   if( pCur->skipNext<0 ){
50167     pCur->skipNext = 0;
50168     *pRes = 0;
50169     return SQLITE_OK;
50170   }
50171   pCur->skipNext = 0;
50172
50173   pPage = pCur->apPage[pCur->iPage];
50174   assert( pPage->isInit );
50175   if( !pPage->leaf ){
50176     int idx = pCur->aiIdx[pCur->iPage];
50177     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
50178     if( rc ){
50179       return rc;
50180     }
50181     rc = moveToRightmost(pCur);
50182   }else{
50183     while( pCur->aiIdx[pCur->iPage]==0 ){
50184       if( pCur->iPage==0 ){
50185         pCur->eState = CURSOR_INVALID;
50186         *pRes = 1;
50187         return SQLITE_OK;
50188       }
50189       moveToParent(pCur);
50190     }
50191     pCur->info.nSize = 0;
50192     pCur->validNKey = 0;
50193
50194     pCur->aiIdx[pCur->iPage]--;
50195     pPage = pCur->apPage[pCur->iPage];
50196     if( pPage->intKey && !pPage->leaf ){
50197       rc = sqlite3BtreePrevious(pCur, pRes);
50198     }else{
50199       rc = SQLITE_OK;
50200     }
50201   }
50202   *pRes = 0;
50203   return rc;
50204 }
50205
50206 /*
50207 ** Allocate a new page from the database file.
50208 **
50209 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
50210 ** has already been called on the new page.)  The new page has also
50211 ** been referenced and the calling routine is responsible for calling
50212 ** sqlite3PagerUnref() on the new page when it is done.
50213 **
50214 ** SQLITE_OK is returned on success.  Any other return value indicates
50215 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
50216 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
50217 **
50218 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to 
50219 ** locate a page close to the page number "nearby".  This can be used in an
50220 ** attempt to keep related pages close to each other in the database file,
50221 ** which in turn can make database access faster.
50222 **
50223 ** If the "exact" parameter is not 0, and the page-number nearby exists 
50224 ** anywhere on the free-list, then it is guarenteed to be returned. This
50225 ** is only used by auto-vacuum databases when allocating a new table.
50226 */
50227 static int allocateBtreePage(
50228   BtShared *pBt, 
50229   MemPage **ppPage, 
50230   Pgno *pPgno, 
50231   Pgno nearby,
50232   u8 exact
50233 ){
50234   MemPage *pPage1;
50235   int rc;
50236   u32 n;     /* Number of pages on the freelist */
50237   u32 k;     /* Number of leaves on the trunk of the freelist */
50238   MemPage *pTrunk = 0;
50239   MemPage *pPrevTrunk = 0;
50240   Pgno mxPage;     /* Total size of the database file */
50241
50242   assert( sqlite3_mutex_held(pBt->mutex) );
50243   pPage1 = pBt->pPage1;
50244   mxPage = btreePagecount(pBt);
50245   n = get4byte(&pPage1->aData[36]);
50246   testcase( n==mxPage-1 );
50247   if( n>=mxPage ){
50248     return SQLITE_CORRUPT_BKPT;
50249   }
50250   if( n>0 ){
50251     /* There are pages on the freelist.  Reuse one of those pages. */
50252     Pgno iTrunk;
50253     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
50254     
50255     /* If the 'exact' parameter was true and a query of the pointer-map
50256     ** shows that the page 'nearby' is somewhere on the free-list, then
50257     ** the entire-list will be searched for that page.
50258     */
50259 #ifndef SQLITE_OMIT_AUTOVACUUM
50260     if( exact && nearby<=mxPage ){
50261       u8 eType;
50262       assert( nearby>0 );
50263       assert( pBt->autoVacuum );
50264       rc = ptrmapGet(pBt, nearby, &eType, 0);
50265       if( rc ) return rc;
50266       if( eType==PTRMAP_FREEPAGE ){
50267         searchList = 1;
50268       }
50269       *pPgno = nearby;
50270     }
50271 #endif
50272
50273     /* Decrement the free-list count by 1. Set iTrunk to the index of the
50274     ** first free-list trunk page. iPrevTrunk is initially 1.
50275     */
50276     rc = sqlite3PagerWrite(pPage1->pDbPage);
50277     if( rc ) return rc;
50278     put4byte(&pPage1->aData[36], n-1);
50279
50280     /* The code within this loop is run only once if the 'searchList' variable
50281     ** is not true. Otherwise, it runs once for each trunk-page on the
50282     ** free-list until the page 'nearby' is located.
50283     */
50284     do {
50285       pPrevTrunk = pTrunk;
50286       if( pPrevTrunk ){
50287         iTrunk = get4byte(&pPrevTrunk->aData[0]);
50288       }else{
50289         iTrunk = get4byte(&pPage1->aData[32]);
50290       }
50291       testcase( iTrunk==mxPage );
50292       if( iTrunk>mxPage ){
50293         rc = SQLITE_CORRUPT_BKPT;
50294       }else{
50295         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
50296       }
50297       if( rc ){
50298         pTrunk = 0;
50299         goto end_allocate_page;
50300       }
50301
50302       k = get4byte(&pTrunk->aData[4]);
50303       if( k==0 && !searchList ){
50304         /* The trunk has no leaves and the list is not being searched. 
50305         ** So extract the trunk page itself and use it as the newly 
50306         ** allocated page */
50307         assert( pPrevTrunk==0 );
50308         rc = sqlite3PagerWrite(pTrunk->pDbPage);
50309         if( rc ){
50310           goto end_allocate_page;
50311         }
50312         *pPgno = iTrunk;
50313         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
50314         *ppPage = pTrunk;
50315         pTrunk = 0;
50316         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
50317       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
50318         /* Value of k is out of range.  Database corruption */
50319         rc = SQLITE_CORRUPT_BKPT;
50320         goto end_allocate_page;
50321 #ifndef SQLITE_OMIT_AUTOVACUUM
50322       }else if( searchList && nearby==iTrunk ){
50323         /* The list is being searched and this trunk page is the page
50324         ** to allocate, regardless of whether it has leaves.
50325         */
50326         assert( *pPgno==iTrunk );
50327         *ppPage = pTrunk;
50328         searchList = 0;
50329         rc = sqlite3PagerWrite(pTrunk->pDbPage);
50330         if( rc ){
50331           goto end_allocate_page;
50332         }
50333         if( k==0 ){
50334           if( !pPrevTrunk ){
50335             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
50336           }else{
50337             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
50338             if( rc!=SQLITE_OK ){
50339               goto end_allocate_page;
50340             }
50341             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
50342           }
50343         }else{
50344           /* The trunk page is required by the caller but it contains 
50345           ** pointers to free-list leaves. The first leaf becomes a trunk
50346           ** page in this case.
50347           */
50348           MemPage *pNewTrunk;
50349           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
50350           if( iNewTrunk>mxPage ){ 
50351             rc = SQLITE_CORRUPT_BKPT;
50352             goto end_allocate_page;
50353           }
50354           testcase( iNewTrunk==mxPage );
50355           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
50356           if( rc!=SQLITE_OK ){
50357             goto end_allocate_page;
50358           }
50359           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
50360           if( rc!=SQLITE_OK ){
50361             releasePage(pNewTrunk);
50362             goto end_allocate_page;
50363           }
50364           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
50365           put4byte(&pNewTrunk->aData[4], k-1);
50366           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
50367           releasePage(pNewTrunk);
50368           if( !pPrevTrunk ){
50369             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
50370             put4byte(&pPage1->aData[32], iNewTrunk);
50371           }else{
50372             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
50373             if( rc ){
50374               goto end_allocate_page;
50375             }
50376             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
50377           }
50378         }
50379         pTrunk = 0;
50380         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
50381 #endif
50382       }else if( k>0 ){
50383         /* Extract a leaf from the trunk */
50384         u32 closest;
50385         Pgno iPage;
50386         unsigned char *aData = pTrunk->aData;
50387         rc = sqlite3PagerWrite(pTrunk->pDbPage);
50388         if( rc ){
50389           goto end_allocate_page;
50390         }
50391         if( nearby>0 ){
50392           u32 i;
50393           int dist;
50394           closest = 0;
50395           dist = get4byte(&aData[8]) - nearby;
50396           if( dist<0 ) dist = -dist;
50397           for(i=1; i<k; i++){
50398             int d2 = get4byte(&aData[8+i*4]) - nearby;
50399             if( d2<0 ) d2 = -d2;
50400             if( d2<dist ){
50401               closest = i;
50402               dist = d2;
50403             }
50404           }
50405         }else{
50406           closest = 0;
50407         }
50408
50409         iPage = get4byte(&aData[8+closest*4]);
50410         testcase( iPage==mxPage );
50411         if( iPage>mxPage ){
50412           rc = SQLITE_CORRUPT_BKPT;
50413           goto end_allocate_page;
50414         }
50415         testcase( iPage==mxPage );
50416         if( !searchList || iPage==nearby ){
50417           int noContent;
50418           *pPgno = iPage;
50419           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
50420                  ": %d more free pages\n",
50421                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
50422           if( closest<k-1 ){
50423             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
50424           }
50425           put4byte(&aData[4], k-1);
50426           assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
50427           noContent = !btreeGetHasContent(pBt, *pPgno);
50428           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
50429           if( rc==SQLITE_OK ){
50430             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
50431             if( rc!=SQLITE_OK ){
50432               releasePage(*ppPage);
50433             }
50434           }
50435           searchList = 0;
50436         }
50437       }
50438       releasePage(pPrevTrunk);
50439       pPrevTrunk = 0;
50440     }while( searchList );
50441   }else{
50442     /* There are no pages on the freelist, so create a new page at the
50443     ** end of the file */
50444     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
50445     if( rc ) return rc;
50446     pBt->nPage++;
50447     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
50448
50449 #ifndef SQLITE_OMIT_AUTOVACUUM
50450     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
50451       /* If *pPgno refers to a pointer-map page, allocate two new pages
50452       ** at the end of the file instead of one. The first allocated page
50453       ** becomes a new pointer-map page, the second is used by the caller.
50454       */
50455       MemPage *pPg = 0;
50456       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
50457       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
50458       rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
50459       if( rc==SQLITE_OK ){
50460         rc = sqlite3PagerWrite(pPg->pDbPage);
50461         releasePage(pPg);
50462       }
50463       if( rc ) return rc;
50464       pBt->nPage++;
50465       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
50466     }
50467 #endif
50468     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
50469     *pPgno = pBt->nPage;
50470
50471     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
50472     rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
50473     if( rc ) return rc;
50474     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
50475     if( rc!=SQLITE_OK ){
50476       releasePage(*ppPage);
50477     }
50478     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
50479   }
50480
50481   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
50482
50483 end_allocate_page:
50484   releasePage(pTrunk);
50485   releasePage(pPrevTrunk);
50486   if( rc==SQLITE_OK ){
50487     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
50488       releasePage(*ppPage);
50489       return SQLITE_CORRUPT_BKPT;
50490     }
50491     (*ppPage)->isInit = 0;
50492   }else{
50493     *ppPage = 0;
50494   }
50495   return rc;
50496 }
50497
50498 /*
50499 ** This function is used to add page iPage to the database file free-list. 
50500 ** It is assumed that the page is not already a part of the free-list.
50501 **
50502 ** The value passed as the second argument to this function is optional.
50503 ** If the caller happens to have a pointer to the MemPage object 
50504 ** corresponding to page iPage handy, it may pass it as the second value. 
50505 ** Otherwise, it may pass NULL.
50506 **
50507 ** If a pointer to a MemPage object is passed as the second argument,
50508 ** its reference count is not altered by this function.
50509 */
50510 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
50511   MemPage *pTrunk = 0;                /* Free-list trunk page */
50512   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ 
50513   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
50514   MemPage *pPage;                     /* Page being freed. May be NULL. */
50515   int rc;                             /* Return Code */
50516   int nFree;                          /* Initial number of pages on free-list */
50517
50518   assert( sqlite3_mutex_held(pBt->mutex) );
50519   assert( iPage>1 );
50520   assert( !pMemPage || pMemPage->pgno==iPage );
50521
50522   if( pMemPage ){
50523     pPage = pMemPage;
50524     sqlite3PagerRef(pPage->pDbPage);
50525   }else{
50526     pPage = btreePageLookup(pBt, iPage);
50527   }
50528
50529   /* Increment the free page count on pPage1 */
50530   rc = sqlite3PagerWrite(pPage1->pDbPage);
50531   if( rc ) goto freepage_out;
50532   nFree = get4byte(&pPage1->aData[36]);
50533   put4byte(&pPage1->aData[36], nFree+1);
50534
50535   if( pBt->secureDelete ){
50536     /* If the secure_delete option is enabled, then
50537     ** always fully overwrite deleted information with zeros.
50538     */
50539     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
50540      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
50541     ){
50542       goto freepage_out;
50543     }
50544     memset(pPage->aData, 0, pPage->pBt->pageSize);
50545   }
50546
50547   /* If the database supports auto-vacuum, write an entry in the pointer-map
50548   ** to indicate that the page is free.
50549   */
50550   if( ISAUTOVACUUM ){
50551     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
50552     if( rc ) goto freepage_out;
50553   }
50554
50555   /* Now manipulate the actual database free-list structure. There are two
50556   ** possibilities. If the free-list is currently empty, or if the first
50557   ** trunk page in the free-list is full, then this page will become a
50558   ** new free-list trunk page. Otherwise, it will become a leaf of the
50559   ** first trunk page in the current free-list. This block tests if it
50560   ** is possible to add the page as a new free-list leaf.
50561   */
50562   if( nFree!=0 ){
50563     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
50564
50565     iTrunk = get4byte(&pPage1->aData[32]);
50566     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
50567     if( rc!=SQLITE_OK ){
50568       goto freepage_out;
50569     }
50570
50571     nLeaf = get4byte(&pTrunk->aData[4]);
50572     assert( pBt->usableSize>32 );
50573     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
50574       rc = SQLITE_CORRUPT_BKPT;
50575       goto freepage_out;
50576     }
50577     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
50578       /* In this case there is room on the trunk page to insert the page
50579       ** being freed as a new leaf.
50580       **
50581       ** Note that the trunk page is not really full until it contains
50582       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
50583       ** coded.  But due to a coding error in versions of SQLite prior to
50584       ** 3.6.0, databases with freelist trunk pages holding more than
50585       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
50586       ** to maintain backwards compatibility with older versions of SQLite,
50587       ** we will continue to restrict the number of entries to usableSize/4 - 8
50588       ** for now.  At some point in the future (once everyone has upgraded
50589       ** to 3.6.0 or later) we should consider fixing the conditional above
50590       ** to read "usableSize/4-2" instead of "usableSize/4-8".
50591       */
50592       rc = sqlite3PagerWrite(pTrunk->pDbPage);
50593       if( rc==SQLITE_OK ){
50594         put4byte(&pTrunk->aData[4], nLeaf+1);
50595         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
50596         if( pPage && !pBt->secureDelete ){
50597           sqlite3PagerDontWrite(pPage->pDbPage);
50598         }
50599         rc = btreeSetHasContent(pBt, iPage);
50600       }
50601       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
50602       goto freepage_out;
50603     }
50604   }
50605
50606   /* If control flows to this point, then it was not possible to add the
50607   ** the page being freed as a leaf page of the first trunk in the free-list.
50608   ** Possibly because the free-list is empty, or possibly because the 
50609   ** first trunk in the free-list is full. Either way, the page being freed
50610   ** will become the new first trunk page in the free-list.
50611   */
50612   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
50613     goto freepage_out;
50614   }
50615   rc = sqlite3PagerWrite(pPage->pDbPage);
50616   if( rc!=SQLITE_OK ){
50617     goto freepage_out;
50618   }
50619   put4byte(pPage->aData, iTrunk);
50620   put4byte(&pPage->aData[4], 0);
50621   put4byte(&pPage1->aData[32], iPage);
50622   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
50623
50624 freepage_out:
50625   if( pPage ){
50626     pPage->isInit = 0;
50627   }
50628   releasePage(pPage);
50629   releasePage(pTrunk);
50630   return rc;
50631 }
50632 static void freePage(MemPage *pPage, int *pRC){
50633   if( (*pRC)==SQLITE_OK ){
50634     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
50635   }
50636 }
50637
50638 /*
50639 ** Free any overflow pages associated with the given Cell.
50640 */
50641 static int clearCell(MemPage *pPage, unsigned char *pCell){
50642   BtShared *pBt = pPage->pBt;
50643   CellInfo info;
50644   Pgno ovflPgno;
50645   int rc;
50646   int nOvfl;
50647   u32 ovflPageSize;
50648
50649   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50650   btreeParseCellPtr(pPage, pCell, &info);
50651   if( info.iOverflow==0 ){
50652     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
50653   }
50654   ovflPgno = get4byte(&pCell[info.iOverflow]);
50655   assert( pBt->usableSize > 4 );
50656   ovflPageSize = pBt->usableSize - 4;
50657   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
50658   assert( ovflPgno==0 || nOvfl>0 );
50659   while( nOvfl-- ){
50660     Pgno iNext = 0;
50661     MemPage *pOvfl = 0;
50662     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
50663       /* 0 is not a legal page number and page 1 cannot be an 
50664       ** overflow page. Therefore if ovflPgno<2 or past the end of the 
50665       ** file the database must be corrupt. */
50666       return SQLITE_CORRUPT_BKPT;
50667     }
50668     if( nOvfl ){
50669       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
50670       if( rc ) return rc;
50671     }
50672
50673     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
50674      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
50675     ){
50676       /* There is no reason any cursor should have an outstanding reference 
50677       ** to an overflow page belonging to a cell that is being deleted/updated.
50678       ** So if there exists more than one reference to this page, then it 
50679       ** must not really be an overflow page and the database must be corrupt. 
50680       ** It is helpful to detect this before calling freePage2(), as 
50681       ** freePage2() may zero the page contents if secure-delete mode is
50682       ** enabled. If this 'overflow' page happens to be a page that the
50683       ** caller is iterating through or using in some other way, this
50684       ** can be problematic.
50685       */
50686       rc = SQLITE_CORRUPT_BKPT;
50687     }else{
50688       rc = freePage2(pBt, pOvfl, ovflPgno);
50689     }
50690
50691     if( pOvfl ){
50692       sqlite3PagerUnref(pOvfl->pDbPage);
50693     }
50694     if( rc ) return rc;
50695     ovflPgno = iNext;
50696   }
50697   return SQLITE_OK;
50698 }
50699
50700 /*
50701 ** Create the byte sequence used to represent a cell on page pPage
50702 ** and write that byte sequence into pCell[].  Overflow pages are
50703 ** allocated and filled in as necessary.  The calling procedure
50704 ** is responsible for making sure sufficient space has been allocated
50705 ** for pCell[].
50706 **
50707 ** Note that pCell does not necessary need to point to the pPage->aData
50708 ** area.  pCell might point to some temporary storage.  The cell will
50709 ** be constructed in this temporary area then copied into pPage->aData
50710 ** later.
50711 */
50712 static int fillInCell(
50713   MemPage *pPage,                /* The page that contains the cell */
50714   unsigned char *pCell,          /* Complete text of the cell */
50715   const void *pKey, i64 nKey,    /* The key */
50716   const void *pData,int nData,   /* The data */
50717   int nZero,                     /* Extra zero bytes to append to pData */
50718   int *pnSize                    /* Write cell size here */
50719 ){
50720   int nPayload;
50721   const u8 *pSrc;
50722   int nSrc, n, rc;
50723   int spaceLeft;
50724   MemPage *pOvfl = 0;
50725   MemPage *pToRelease = 0;
50726   unsigned char *pPrior;
50727   unsigned char *pPayload;
50728   BtShared *pBt = pPage->pBt;
50729   Pgno pgnoOvfl = 0;
50730   int nHeader;
50731   CellInfo info;
50732
50733   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50734
50735   /* pPage is not necessarily writeable since pCell might be auxiliary
50736   ** buffer space that is separate from the pPage buffer area */
50737   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
50738             || sqlite3PagerIswriteable(pPage->pDbPage) );
50739
50740   /* Fill in the header. */
50741   nHeader = 0;
50742   if( !pPage->leaf ){
50743     nHeader += 4;
50744   }
50745   if( pPage->hasData ){
50746     nHeader += putVarint(&pCell[nHeader], nData+nZero);
50747   }else{
50748     nData = nZero = 0;
50749   }
50750   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
50751   btreeParseCellPtr(pPage, pCell, &info);
50752   assert( info.nHeader==nHeader );
50753   assert( info.nKey==nKey );
50754   assert( info.nData==(u32)(nData+nZero) );
50755   
50756   /* Fill in the payload */
50757   nPayload = nData + nZero;
50758   if( pPage->intKey ){
50759     pSrc = pData;
50760     nSrc = nData;
50761     nData = 0;
50762   }else{ 
50763     if( NEVER(nKey>0x7fffffff || pKey==0) ){
50764       return SQLITE_CORRUPT_BKPT;
50765     }
50766     nPayload += (int)nKey;
50767     pSrc = pKey;
50768     nSrc = (int)nKey;
50769   }
50770   *pnSize = info.nSize;
50771   spaceLeft = info.nLocal;
50772   pPayload = &pCell[nHeader];
50773   pPrior = &pCell[info.iOverflow];
50774
50775   while( nPayload>0 ){
50776     if( spaceLeft==0 ){
50777 #ifndef SQLITE_OMIT_AUTOVACUUM
50778       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
50779       if( pBt->autoVacuum ){
50780         do{
50781           pgnoOvfl++;
50782         } while( 
50783           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
50784         );
50785       }
50786 #endif
50787       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
50788 #ifndef SQLITE_OMIT_AUTOVACUUM
50789       /* If the database supports auto-vacuum, and the second or subsequent
50790       ** overflow page is being allocated, add an entry to the pointer-map
50791       ** for that page now. 
50792       **
50793       ** If this is the first overflow page, then write a partial entry 
50794       ** to the pointer-map. If we write nothing to this pointer-map slot,
50795       ** then the optimistic overflow chain processing in clearCell()
50796       ** may misinterpret the uninitialised values and delete the
50797       ** wrong pages from the database.
50798       */
50799       if( pBt->autoVacuum && rc==SQLITE_OK ){
50800         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
50801         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
50802         if( rc ){
50803           releasePage(pOvfl);
50804         }
50805       }
50806 #endif
50807       if( rc ){
50808         releasePage(pToRelease);
50809         return rc;
50810       }
50811
50812       /* If pToRelease is not zero than pPrior points into the data area
50813       ** of pToRelease.  Make sure pToRelease is still writeable. */
50814       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
50815
50816       /* If pPrior is part of the data area of pPage, then make sure pPage
50817       ** is still writeable */
50818       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
50819             || sqlite3PagerIswriteable(pPage->pDbPage) );
50820
50821       put4byte(pPrior, pgnoOvfl);
50822       releasePage(pToRelease);
50823       pToRelease = pOvfl;
50824       pPrior = pOvfl->aData;
50825       put4byte(pPrior, 0);
50826       pPayload = &pOvfl->aData[4];
50827       spaceLeft = pBt->usableSize - 4;
50828     }
50829     n = nPayload;
50830     if( n>spaceLeft ) n = spaceLeft;
50831
50832     /* If pToRelease is not zero than pPayload points into the data area
50833     ** of pToRelease.  Make sure pToRelease is still writeable. */
50834     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
50835
50836     /* If pPayload is part of the data area of pPage, then make sure pPage
50837     ** is still writeable */
50838     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
50839             || sqlite3PagerIswriteable(pPage->pDbPage) );
50840
50841     if( nSrc>0 ){
50842       if( n>nSrc ) n = nSrc;
50843       assert( pSrc );
50844       memcpy(pPayload, pSrc, n);
50845     }else{
50846       memset(pPayload, 0, n);
50847     }
50848     nPayload -= n;
50849     pPayload += n;
50850     pSrc += n;
50851     nSrc -= n;
50852     spaceLeft -= n;
50853     if( nSrc==0 ){
50854       nSrc = nData;
50855       pSrc = pData;
50856     }
50857   }
50858   releasePage(pToRelease);
50859   return SQLITE_OK;
50860 }
50861
50862 /*
50863 ** Remove the i-th cell from pPage.  This routine effects pPage only.
50864 ** The cell content is not freed or deallocated.  It is assumed that
50865 ** the cell content has been copied someplace else.  This routine just
50866 ** removes the reference to the cell from pPage.
50867 **
50868 ** "sz" must be the number of bytes in the cell.
50869 */
50870 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
50871   int i;          /* Loop counter */
50872   u32 pc;         /* Offset to cell content of cell being deleted */
50873   u8 *data;       /* pPage->aData */
50874   u8 *ptr;        /* Used to move bytes around within data[] */
50875   int rc;         /* The return code */
50876   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
50877
50878   if( *pRC ) return;
50879
50880   assert( idx>=0 && idx<pPage->nCell );
50881   assert( sz==cellSize(pPage, idx) );
50882   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50883   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50884   data = pPage->aData;
50885   ptr = &data[pPage->cellOffset + 2*idx];
50886   pc = get2byte(ptr);
50887   hdr = pPage->hdrOffset;
50888   testcase( pc==get2byte(&data[hdr+5]) );
50889   testcase( pc+sz==pPage->pBt->usableSize );
50890   if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
50891     *pRC = SQLITE_CORRUPT_BKPT;
50892     return;
50893   }
50894   rc = freeSpace(pPage, pc, sz);
50895   if( rc ){
50896     *pRC = rc;
50897     return;
50898   }
50899   for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
50900     ptr[0] = ptr[2];
50901     ptr[1] = ptr[3];
50902   }
50903   pPage->nCell--;
50904   put2byte(&data[hdr+3], pPage->nCell);
50905   pPage->nFree += 2;
50906 }
50907
50908 /*
50909 ** Insert a new cell on pPage at cell index "i".  pCell points to the
50910 ** content of the cell.
50911 **
50912 ** If the cell content will fit on the page, then put it there.  If it
50913 ** will not fit, then make a copy of the cell content into pTemp if
50914 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
50915 ** in pPage->aOvfl[] and make it point to the cell content (either
50916 ** in pTemp or the original pCell) and also record its index. 
50917 ** Allocating a new entry in pPage->aCell[] implies that 
50918 ** pPage->nOverflow is incremented.
50919 **
50920 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
50921 ** cell. The caller will overwrite them after this function returns. If
50922 ** nSkip is non-zero, then pCell may not point to an invalid memory location 
50923 ** (but pCell+nSkip is always valid).
50924 */
50925 static void insertCell(
50926   MemPage *pPage,   /* Page into which we are copying */
50927   int i,            /* New cell becomes the i-th cell of the page */
50928   u8 *pCell,        /* Content of the new cell */
50929   int sz,           /* Bytes of content in pCell */
50930   u8 *pTemp,        /* Temp storage space for pCell, if needed */
50931   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
50932   int *pRC          /* Read and write return code from here */
50933 ){
50934   int idx = 0;      /* Where to write new cell content in data[] */
50935   int j;            /* Loop counter */
50936   int end;          /* First byte past the last cell pointer in data[] */
50937   int ins;          /* Index in data[] where new cell pointer is inserted */
50938   int cellOffset;   /* Address of first cell pointer in data[] */
50939   u8 *data;         /* The content of the whole page */
50940   u8 *ptr;          /* Used for moving information around in data[] */
50941
50942   int nSkip = (iChild ? 4 : 0);
50943
50944   if( *pRC ) return;
50945
50946   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
50947   assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
50948   assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
50949   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50950   /* The cell should normally be sized correctly.  However, when moving a
50951   ** malformed cell from a leaf page to an interior page, if the cell size
50952   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
50953   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
50954   ** the term after the || in the following assert(). */
50955   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
50956   if( pPage->nOverflow || sz+2>pPage->nFree ){
50957     if( pTemp ){
50958       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
50959       pCell = pTemp;
50960     }
50961     if( iChild ){
50962       put4byte(pCell, iChild);
50963     }
50964     j = pPage->nOverflow++;
50965     assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
50966     pPage->aOvfl[j].pCell = pCell;
50967     pPage->aOvfl[j].idx = (u16)i;
50968   }else{
50969     int rc = sqlite3PagerWrite(pPage->pDbPage);
50970     if( rc!=SQLITE_OK ){
50971       *pRC = rc;
50972       return;
50973     }
50974     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50975     data = pPage->aData;
50976     cellOffset = pPage->cellOffset;
50977     end = cellOffset + 2*pPage->nCell;
50978     ins = cellOffset + 2*i;
50979     rc = allocateSpace(pPage, sz, &idx);
50980     if( rc ){ *pRC = rc; return; }
50981     /* The allocateSpace() routine guarantees the following two properties
50982     ** if it returns success */
50983     assert( idx >= end+2 );
50984     assert( idx+sz <= pPage->pBt->usableSize );
50985     pPage->nCell++;
50986     pPage->nFree -= (u16)(2 + sz);
50987     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
50988     if( iChild ){
50989       put4byte(&data[idx], iChild);
50990     }
50991     for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){
50992       ptr[0] = ptr[-2];
50993       ptr[1] = ptr[-1];
50994     }
50995     put2byte(&data[ins], idx);
50996     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
50997 #ifndef SQLITE_OMIT_AUTOVACUUM
50998     if( pPage->pBt->autoVacuum ){
50999       /* The cell may contain a pointer to an overflow page. If so, write
51000       ** the entry for the overflow page into the pointer map.
51001       */
51002       ptrmapPutOvflPtr(pPage, pCell, pRC);
51003     }
51004 #endif
51005   }
51006 }
51007
51008 /*
51009 ** Add a list of cells to a page.  The page should be initially empty.
51010 ** The cells are guaranteed to fit on the page.
51011 */
51012 static void assemblePage(
51013   MemPage *pPage,   /* The page to be assemblied */
51014   int nCell,        /* The number of cells to add to this page */
51015   u8 **apCell,      /* Pointers to cell bodies */
51016   u16 *aSize        /* Sizes of the cells */
51017 ){
51018   int i;            /* Loop counter */
51019   u8 *pCellptr;     /* Address of next cell pointer */
51020   int cellbody;     /* Address of next cell body */
51021   u8 * const data = pPage->aData;             /* Pointer to data for pPage */
51022   const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
51023   const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
51024
51025   assert( pPage->nOverflow==0 );
51026   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51027   assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921);
51028   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
51029
51030   /* Check that the page has just been zeroed by zeroPage() */
51031   assert( pPage->nCell==0 );
51032   assert( get2byteNotZero(&data[hdr+5])==nUsable );
51033
51034   pCellptr = &data[pPage->cellOffset + nCell*2];
51035   cellbody = nUsable;
51036   for(i=nCell-1; i>=0; i--){
51037     pCellptr -= 2;
51038     cellbody -= aSize[i];
51039     put2byte(pCellptr, cellbody);
51040     memcpy(&data[cellbody], apCell[i], aSize[i]);
51041   }
51042   put2byte(&data[hdr+3], nCell);
51043   put2byte(&data[hdr+5], cellbody);
51044   pPage->nFree -= (nCell*2 + nUsable - cellbody);
51045   pPage->nCell = (u16)nCell;
51046 }
51047
51048 /*
51049 ** The following parameters determine how many adjacent pages get involved
51050 ** in a balancing operation.  NN is the number of neighbors on either side
51051 ** of the page that participate in the balancing operation.  NB is the
51052 ** total number of pages that participate, including the target page and
51053 ** NN neighbors on either side.
51054 **
51055 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
51056 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
51057 ** in exchange for a larger degradation in INSERT and UPDATE performance.
51058 ** The value of NN appears to give the best results overall.
51059 */
51060 #define NN 1             /* Number of neighbors on either side of pPage */
51061 #define NB (NN*2+1)      /* Total pages involved in the balance */
51062
51063
51064 #ifndef SQLITE_OMIT_QUICKBALANCE
51065 /*
51066 ** This version of balance() handles the common special case where
51067 ** a new entry is being inserted on the extreme right-end of the
51068 ** tree, in other words, when the new entry will become the largest
51069 ** entry in the tree.
51070 **
51071 ** Instead of trying to balance the 3 right-most leaf pages, just add
51072 ** a new page to the right-hand side and put the one new entry in
51073 ** that page.  This leaves the right side of the tree somewhat
51074 ** unbalanced.  But odds are that we will be inserting new entries
51075 ** at the end soon afterwards so the nearly empty page will quickly
51076 ** fill up.  On average.
51077 **
51078 ** pPage is the leaf page which is the right-most page in the tree.
51079 ** pParent is its parent.  pPage must have a single overflow entry
51080 ** which is also the right-most entry on the page.
51081 **
51082 ** The pSpace buffer is used to store a temporary copy of the divider
51083 ** cell that will be inserted into pParent. Such a cell consists of a 4
51084 ** byte page number followed by a variable length integer. In other
51085 ** words, at most 13 bytes. Hence the pSpace buffer must be at
51086 ** least 13 bytes in size.
51087 */
51088 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
51089   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
51090   MemPage *pNew;                       /* Newly allocated page */
51091   int rc;                              /* Return Code */
51092   Pgno pgnoNew;                        /* Page number of pNew */
51093
51094   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51095   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
51096   assert( pPage->nOverflow==1 );
51097
51098   /* This error condition is now caught prior to reaching this function */
51099   if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
51100
51101   /* Allocate a new page. This page will become the right-sibling of 
51102   ** pPage. Make the parent page writable, so that the new divider cell
51103   ** may be inserted. If both these operations are successful, proceed.
51104   */
51105   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
51106
51107   if( rc==SQLITE_OK ){
51108
51109     u8 *pOut = &pSpace[4];
51110     u8 *pCell = pPage->aOvfl[0].pCell;
51111     u16 szCell = cellSizePtr(pPage, pCell);
51112     u8 *pStop;
51113
51114     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
51115     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
51116     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
51117     assemblePage(pNew, 1, &pCell, &szCell);
51118
51119     /* If this is an auto-vacuum database, update the pointer map
51120     ** with entries for the new page, and any pointer from the 
51121     ** cell on the page to an overflow page. If either of these
51122     ** operations fails, the return code is set, but the contents
51123     ** of the parent page are still manipulated by thh code below.
51124     ** That is Ok, at this point the parent page is guaranteed to
51125     ** be marked as dirty. Returning an error code will cause a
51126     ** rollback, undoing any changes made to the parent page.
51127     */
51128     if( ISAUTOVACUUM ){
51129       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
51130       if( szCell>pNew->minLocal ){
51131         ptrmapPutOvflPtr(pNew, pCell, &rc);
51132       }
51133     }
51134   
51135     /* Create a divider cell to insert into pParent. The divider cell
51136     ** consists of a 4-byte page number (the page number of pPage) and
51137     ** a variable length key value (which must be the same value as the
51138     ** largest key on pPage).
51139     **
51140     ** To find the largest key value on pPage, first find the right-most 
51141     ** cell on pPage. The first two fields of this cell are the 
51142     ** record-length (a variable length integer at most 32-bits in size)
51143     ** and the key value (a variable length integer, may have any value).
51144     ** The first of the while(...) loops below skips over the record-length
51145     ** field. The second while(...) loop copies the key value from the
51146     ** cell on pPage into the pSpace buffer.
51147     */
51148     pCell = findCell(pPage, pPage->nCell-1);
51149     pStop = &pCell[9];
51150     while( (*(pCell++)&0x80) && pCell<pStop );
51151     pStop = &pCell[9];
51152     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
51153
51154     /* Insert the new divider cell into pParent. */
51155     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
51156                0, pPage->pgno, &rc);
51157
51158     /* Set the right-child pointer of pParent to point to the new page. */
51159     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
51160   
51161     /* Release the reference to the new page. */
51162     releasePage(pNew);
51163   }
51164
51165   return rc;
51166 }
51167 #endif /* SQLITE_OMIT_QUICKBALANCE */
51168
51169 #if 0
51170 /*
51171 ** This function does not contribute anything to the operation of SQLite.
51172 ** it is sometimes activated temporarily while debugging code responsible 
51173 ** for setting pointer-map entries.
51174 */
51175 static int ptrmapCheckPages(MemPage **apPage, int nPage){
51176   int i, j;
51177   for(i=0; i<nPage; i++){
51178     Pgno n;
51179     u8 e;
51180     MemPage *pPage = apPage[i];
51181     BtShared *pBt = pPage->pBt;
51182     assert( pPage->isInit );
51183
51184     for(j=0; j<pPage->nCell; j++){
51185       CellInfo info;
51186       u8 *z;
51187      
51188       z = findCell(pPage, j);
51189       btreeParseCellPtr(pPage, z, &info);
51190       if( info.iOverflow ){
51191         Pgno ovfl = get4byte(&z[info.iOverflow]);
51192         ptrmapGet(pBt, ovfl, &e, &n);
51193         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
51194       }
51195       if( !pPage->leaf ){
51196         Pgno child = get4byte(z);
51197         ptrmapGet(pBt, child, &e, &n);
51198         assert( n==pPage->pgno && e==PTRMAP_BTREE );
51199       }
51200     }
51201     if( !pPage->leaf ){
51202       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
51203       ptrmapGet(pBt, child, &e, &n);
51204       assert( n==pPage->pgno && e==PTRMAP_BTREE );
51205     }
51206   }
51207   return 1;
51208 }
51209 #endif
51210
51211 /*
51212 ** This function is used to copy the contents of the b-tree node stored 
51213 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
51214 ** the pointer-map entries for each child page are updated so that the
51215 ** parent page stored in the pointer map is page pTo. If pFrom contained
51216 ** any cells with overflow page pointers, then the corresponding pointer
51217 ** map entries are also updated so that the parent page is page pTo.
51218 **
51219 ** If pFrom is currently carrying any overflow cells (entries in the
51220 ** MemPage.aOvfl[] array), they are not copied to pTo. 
51221 **
51222 ** Before returning, page pTo is reinitialized using btreeInitPage().
51223 **
51224 ** The performance of this function is not critical. It is only used by 
51225 ** the balance_shallower() and balance_deeper() procedures, neither of
51226 ** which are called often under normal circumstances.
51227 */
51228 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
51229   if( (*pRC)==SQLITE_OK ){
51230     BtShared * const pBt = pFrom->pBt;
51231     u8 * const aFrom = pFrom->aData;
51232     u8 * const aTo = pTo->aData;
51233     int const iFromHdr = pFrom->hdrOffset;
51234     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
51235     int rc;
51236     int iData;
51237   
51238   
51239     assert( pFrom->isInit );
51240     assert( pFrom->nFree>=iToHdr );
51241     assert( get2byte(&aFrom[iFromHdr+5])<=pBt->usableSize );
51242   
51243     /* Copy the b-tree node content from page pFrom to page pTo. */
51244     iData = get2byte(&aFrom[iFromHdr+5]);
51245     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
51246     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
51247   
51248     /* Reinitialize page pTo so that the contents of the MemPage structure
51249     ** match the new data. The initialization of pTo can actually fail under
51250     ** fairly obscure circumstances, even though it is a copy of initialized 
51251     ** page pFrom.
51252     */
51253     pTo->isInit = 0;
51254     rc = btreeInitPage(pTo);
51255     if( rc!=SQLITE_OK ){
51256       *pRC = rc;
51257       return;
51258     }
51259   
51260     /* If this is an auto-vacuum database, update the pointer-map entries
51261     ** for any b-tree or overflow pages that pTo now contains the pointers to.
51262     */
51263     if( ISAUTOVACUUM ){
51264       *pRC = setChildPtrmaps(pTo);
51265     }
51266   }
51267 }
51268
51269 /*
51270 ** This routine redistributes cells on the iParentIdx'th child of pParent
51271 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
51272 ** same amount of free space. Usually a single sibling on either side of the
51273 ** page are used in the balancing, though both siblings might come from one
51274 ** side if the page is the first or last child of its parent. If the page 
51275 ** has fewer than 2 siblings (something which can only happen if the page
51276 ** is a root page or a child of a root page) then all available siblings
51277 ** participate in the balancing.
51278 **
51279 ** The number of siblings of the page might be increased or decreased by 
51280 ** one or two in an effort to keep pages nearly full but not over full. 
51281 **
51282 ** Note that when this routine is called, some of the cells on the page
51283 ** might not actually be stored in MemPage.aData[]. This can happen
51284 ** if the page is overfull. This routine ensures that all cells allocated
51285 ** to the page and its siblings fit into MemPage.aData[] before returning.
51286 **
51287 ** In the course of balancing the page and its siblings, cells may be
51288 ** inserted into or removed from the parent page (pParent). Doing so
51289 ** may cause the parent page to become overfull or underfull. If this
51290 ** happens, it is the responsibility of the caller to invoke the correct
51291 ** balancing routine to fix this problem (see the balance() routine). 
51292 **
51293 ** If this routine fails for any reason, it might leave the database
51294 ** in a corrupted state. So if this routine fails, the database should
51295 ** be rolled back.
51296 **
51297 ** The third argument to this function, aOvflSpace, is a pointer to a
51298 ** buffer big enough to hold one page. If while inserting cells into the parent
51299 ** page (pParent) the parent page becomes overfull, this buffer is
51300 ** used to store the parent's overflow cells. Because this function inserts
51301 ** a maximum of four divider cells into the parent page, and the maximum
51302 ** size of a cell stored within an internal node is always less than 1/4
51303 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
51304 ** enough for all overflow cells.
51305 **
51306 ** If aOvflSpace is set to a null pointer, this function returns 
51307 ** SQLITE_NOMEM.
51308 */
51309 static int balance_nonroot(
51310   MemPage *pParent,               /* Parent page of siblings being balanced */
51311   int iParentIdx,                 /* Index of "the page" in pParent */
51312   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
51313   int isRoot                      /* True if pParent is a root-page */
51314 ){
51315   BtShared *pBt;               /* The whole database */
51316   int nCell = 0;               /* Number of cells in apCell[] */
51317   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
51318   int nNew = 0;                /* Number of pages in apNew[] */
51319   int nOld;                    /* Number of pages in apOld[] */
51320   int i, j, k;                 /* Loop counters */
51321   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
51322   int rc = SQLITE_OK;          /* The return code */
51323   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
51324   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
51325   int usableSpace;             /* Bytes in pPage beyond the header */
51326   int pageFlags;               /* Value of pPage->aData[0] */
51327   int subtotal;                /* Subtotal of bytes in cells on one page */
51328   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
51329   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
51330   int szScratch;               /* Size of scratch memory requested */
51331   MemPage *apOld[NB];          /* pPage and up to two siblings */
51332   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
51333   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
51334   u8 *pRight;                  /* Location in parent of right-sibling pointer */
51335   u8 *apDiv[NB-1];             /* Divider cells in pParent */
51336   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
51337   int szNew[NB+2];             /* Combined size of cells place on i-th page */
51338   u8 **apCell = 0;             /* All cells begin balanced */
51339   u16 *szCell;                 /* Local size of all cells in apCell[] */
51340   u8 *aSpace1;                 /* Space for copies of dividers cells */
51341   Pgno pgno;                   /* Temp var to store a page number in */
51342
51343   pBt = pParent->pBt;
51344   assert( sqlite3_mutex_held(pBt->mutex) );
51345   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
51346
51347 #if 0
51348   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
51349 #endif
51350
51351   /* At this point pParent may have at most one overflow cell. And if
51352   ** this overflow cell is present, it must be the cell with 
51353   ** index iParentIdx. This scenario comes about when this function
51354   ** is called (indirectly) from sqlite3BtreeDelete().
51355   */
51356   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
51357   assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
51358
51359   if( !aOvflSpace ){
51360     return SQLITE_NOMEM;
51361   }
51362
51363   /* Find the sibling pages to balance. Also locate the cells in pParent 
51364   ** that divide the siblings. An attempt is made to find NN siblings on 
51365   ** either side of pPage. More siblings are taken from one side, however, 
51366   ** if there are fewer than NN siblings on the other side. If pParent
51367   ** has NB or fewer children then all children of pParent are taken.  
51368   **
51369   ** This loop also drops the divider cells from the parent page. This
51370   ** way, the remainder of the function does not have to deal with any
51371   ** overflow cells in the parent page, since if any existed they will
51372   ** have already been removed.
51373   */
51374   i = pParent->nOverflow + pParent->nCell;
51375   if( i<2 ){
51376     nxDiv = 0;
51377     nOld = i+1;
51378   }else{
51379     nOld = 3;
51380     if( iParentIdx==0 ){                 
51381       nxDiv = 0;
51382     }else if( iParentIdx==i ){
51383       nxDiv = i-2;
51384     }else{
51385       nxDiv = iParentIdx-1;
51386     }
51387     i = 2;
51388   }
51389   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
51390     pRight = &pParent->aData[pParent->hdrOffset+8];
51391   }else{
51392     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
51393   }
51394   pgno = get4byte(pRight);
51395   while( 1 ){
51396     rc = getAndInitPage(pBt, pgno, &apOld[i]);
51397     if( rc ){
51398       memset(apOld, 0, (i+1)*sizeof(MemPage*));
51399       goto balance_cleanup;
51400     }
51401     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
51402     if( (i--)==0 ) break;
51403
51404     if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
51405       apDiv[i] = pParent->aOvfl[0].pCell;
51406       pgno = get4byte(apDiv[i]);
51407       szNew[i] = cellSizePtr(pParent, apDiv[i]);
51408       pParent->nOverflow = 0;
51409     }else{
51410       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
51411       pgno = get4byte(apDiv[i]);
51412       szNew[i] = cellSizePtr(pParent, apDiv[i]);
51413
51414       /* Drop the cell from the parent page. apDiv[i] still points to
51415       ** the cell within the parent, even though it has been dropped.
51416       ** This is safe because dropping a cell only overwrites the first
51417       ** four bytes of it, and this function does not need the first
51418       ** four bytes of the divider cell. So the pointer is safe to use
51419       ** later on.  
51420       **
51421       ** Unless SQLite is compiled in secure-delete mode. In this case,
51422       ** the dropCell() routine will overwrite the entire cell with zeroes.
51423       ** In this case, temporarily copy the cell into the aOvflSpace[]
51424       ** buffer. It will be copied out again as soon as the aSpace[] buffer
51425       ** is allocated.  */
51426       if( pBt->secureDelete ){
51427         int iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
51428         if( (iOff+szNew[i])>(int)pBt->usableSize ){
51429           rc = SQLITE_CORRUPT_BKPT;
51430           memset(apOld, 0, (i+1)*sizeof(MemPage*));
51431           goto balance_cleanup;
51432         }else{
51433           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
51434           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
51435         }
51436       }
51437       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
51438     }
51439   }
51440
51441   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
51442   ** alignment */
51443   nMaxCells = (nMaxCells + 3)&~3;
51444
51445   /*
51446   ** Allocate space for memory structures
51447   */
51448   k = pBt->pageSize + ROUND8(sizeof(MemPage));
51449   szScratch =
51450        nMaxCells*sizeof(u8*)                       /* apCell */
51451      + nMaxCells*sizeof(u16)                       /* szCell */
51452      + pBt->pageSize                               /* aSpace1 */
51453      + k*nOld;                                     /* Page copies (apCopy) */
51454   apCell = sqlite3ScratchMalloc( szScratch ); 
51455   if( apCell==0 ){
51456     rc = SQLITE_NOMEM;
51457     goto balance_cleanup;
51458   }
51459   szCell = (u16*)&apCell[nMaxCells];
51460   aSpace1 = (u8*)&szCell[nMaxCells];
51461   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
51462
51463   /*
51464   ** Load pointers to all cells on sibling pages and the divider cells
51465   ** into the local apCell[] array.  Make copies of the divider cells
51466   ** into space obtained from aSpace1[] and remove the the divider Cells
51467   ** from pParent.
51468   **
51469   ** If the siblings are on leaf pages, then the child pointers of the
51470   ** divider cells are stripped from the cells before they are copied
51471   ** into aSpace1[].  In this way, all cells in apCell[] are without
51472   ** child pointers.  If siblings are not leaves, then all cell in
51473   ** apCell[] include child pointers.  Either way, all cells in apCell[]
51474   ** are alike.
51475   **
51476   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
51477   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
51478   */
51479   leafCorrection = apOld[0]->leaf*4;
51480   leafData = apOld[0]->hasData;
51481   for(i=0; i<nOld; i++){
51482     int limit;
51483     
51484     /* Before doing anything else, take a copy of the i'th original sibling
51485     ** The rest of this function will use data from the copies rather
51486     ** that the original pages since the original pages will be in the
51487     ** process of being overwritten.  */
51488     MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
51489     memcpy(pOld, apOld[i], sizeof(MemPage));
51490     pOld->aData = (void*)&pOld[1];
51491     memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
51492
51493     limit = pOld->nCell+pOld->nOverflow;
51494     for(j=0; j<limit; j++){
51495       assert( nCell<nMaxCells );
51496       apCell[nCell] = findOverflowCell(pOld, j);
51497       szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
51498       nCell++;
51499     }
51500     if( i<nOld-1 && !leafData){
51501       u16 sz = (u16)szNew[i];
51502       u8 *pTemp;
51503       assert( nCell<nMaxCells );
51504       szCell[nCell] = sz;
51505       pTemp = &aSpace1[iSpace1];
51506       iSpace1 += sz;
51507       assert( sz<=pBt->maxLocal+23 );
51508       assert( iSpace1<=pBt->pageSize );
51509       memcpy(pTemp, apDiv[i], sz);
51510       apCell[nCell] = pTemp+leafCorrection;
51511       assert( leafCorrection==0 || leafCorrection==4 );
51512       szCell[nCell] = szCell[nCell] - leafCorrection;
51513       if( !pOld->leaf ){
51514         assert( leafCorrection==0 );
51515         assert( pOld->hdrOffset==0 );
51516         /* The right pointer of the child page pOld becomes the left
51517         ** pointer of the divider cell */
51518         memcpy(apCell[nCell], &pOld->aData[8], 4);
51519       }else{
51520         assert( leafCorrection==4 );
51521         if( szCell[nCell]<4 ){
51522           /* Do not allow any cells smaller than 4 bytes. */
51523           szCell[nCell] = 4;
51524         }
51525       }
51526       nCell++;
51527     }
51528   }
51529
51530   /*
51531   ** Figure out the number of pages needed to hold all nCell cells.
51532   ** Store this number in "k".  Also compute szNew[] which is the total
51533   ** size of all cells on the i-th page and cntNew[] which is the index
51534   ** in apCell[] of the cell that divides page i from page i+1.  
51535   ** cntNew[k] should equal nCell.
51536   **
51537   ** Values computed by this block:
51538   **
51539   **           k: The total number of sibling pages
51540   **    szNew[i]: Spaced used on the i-th sibling page.
51541   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
51542   **              the right of the i-th sibling page.
51543   ** usableSpace: Number of bytes of space available on each sibling.
51544   ** 
51545   */
51546   usableSpace = pBt->usableSize - 12 + leafCorrection;
51547   for(subtotal=k=i=0; i<nCell; i++){
51548     assert( i<nMaxCells );
51549     subtotal += szCell[i] + 2;
51550     if( subtotal > usableSpace ){
51551       szNew[k] = subtotal - szCell[i];
51552       cntNew[k] = i;
51553       if( leafData ){ i--; }
51554       subtotal = 0;
51555       k++;
51556       if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
51557     }
51558   }
51559   szNew[k] = subtotal;
51560   cntNew[k] = nCell;
51561   k++;
51562
51563   /*
51564   ** The packing computed by the previous block is biased toward the siblings
51565   ** on the left side.  The left siblings are always nearly full, while the
51566   ** right-most sibling might be nearly empty.  This block of code attempts
51567   ** to adjust the packing of siblings to get a better balance.
51568   **
51569   ** This adjustment is more than an optimization.  The packing above might
51570   ** be so out of balance as to be illegal.  For example, the right-most
51571   ** sibling might be completely empty.  This adjustment is not optional.
51572   */
51573   for(i=k-1; i>0; i--){
51574     int szRight = szNew[i];  /* Size of sibling on the right */
51575     int szLeft = szNew[i-1]; /* Size of sibling on the left */
51576     int r;              /* Index of right-most cell in left sibling */
51577     int d;              /* Index of first cell to the left of right sibling */
51578
51579     r = cntNew[i-1] - 1;
51580     d = r + 1 - leafData;
51581     assert( d<nMaxCells );
51582     assert( r<nMaxCells );
51583     while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
51584       szRight += szCell[d] + 2;
51585       szLeft -= szCell[r] + 2;
51586       cntNew[i-1]--;
51587       r = cntNew[i-1] - 1;
51588       d = r + 1 - leafData;
51589     }
51590     szNew[i] = szRight;
51591     szNew[i-1] = szLeft;
51592   }
51593
51594   /* Either we found one or more cells (cntnew[0])>0) or pPage is
51595   ** a virtual root page.  A virtual root page is when the real root
51596   ** page is page 1 and we are the only child of that page.
51597   */
51598   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
51599
51600   TRACE(("BALANCE: old: %d %d %d  ",
51601     apOld[0]->pgno, 
51602     nOld>=2 ? apOld[1]->pgno : 0,
51603     nOld>=3 ? apOld[2]->pgno : 0
51604   ));
51605
51606   /*
51607   ** Allocate k new pages.  Reuse old pages where possible.
51608   */
51609   if( apOld[0]->pgno<=1 ){
51610     rc = SQLITE_CORRUPT_BKPT;
51611     goto balance_cleanup;
51612   }
51613   pageFlags = apOld[0]->aData[0];
51614   for(i=0; i<k; i++){
51615     MemPage *pNew;
51616     if( i<nOld ){
51617       pNew = apNew[i] = apOld[i];
51618       apOld[i] = 0;
51619       rc = sqlite3PagerWrite(pNew->pDbPage);
51620       nNew++;
51621       if( rc ) goto balance_cleanup;
51622     }else{
51623       assert( i>0 );
51624       rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
51625       if( rc ) goto balance_cleanup;
51626       apNew[i] = pNew;
51627       nNew++;
51628
51629       /* Set the pointer-map entry for the new sibling page. */
51630       if( ISAUTOVACUUM ){
51631         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
51632         if( rc!=SQLITE_OK ){
51633           goto balance_cleanup;
51634         }
51635       }
51636     }
51637   }
51638
51639   /* Free any old pages that were not reused as new pages.
51640   */
51641   while( i<nOld ){
51642     freePage(apOld[i], &rc);
51643     if( rc ) goto balance_cleanup;
51644     releasePage(apOld[i]);
51645     apOld[i] = 0;
51646     i++;
51647   }
51648
51649   /*
51650   ** Put the new pages in accending order.  This helps to
51651   ** keep entries in the disk file in order so that a scan
51652   ** of the table is a linear scan through the file.  That
51653   ** in turn helps the operating system to deliver pages
51654   ** from the disk more rapidly.
51655   **
51656   ** An O(n^2) insertion sort algorithm is used, but since
51657   ** n is never more than NB (a small constant), that should
51658   ** not be a problem.
51659   **
51660   ** When NB==3, this one optimization makes the database
51661   ** about 25% faster for large insertions and deletions.
51662   */
51663   for(i=0; i<k-1; i++){
51664     int minV = apNew[i]->pgno;
51665     int minI = i;
51666     for(j=i+1; j<k; j++){
51667       if( apNew[j]->pgno<(unsigned)minV ){
51668         minI = j;
51669         minV = apNew[j]->pgno;
51670       }
51671     }
51672     if( minI>i ){
51673       int t;
51674       MemPage *pT;
51675       t = apNew[i]->pgno;
51676       pT = apNew[i];
51677       apNew[i] = apNew[minI];
51678       apNew[minI] = pT;
51679     }
51680   }
51681   TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
51682     apNew[0]->pgno, szNew[0],
51683     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
51684     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
51685     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
51686     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
51687
51688   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
51689   put4byte(pRight, apNew[nNew-1]->pgno);
51690
51691   /*
51692   ** Evenly distribute the data in apCell[] across the new pages.
51693   ** Insert divider cells into pParent as necessary.
51694   */
51695   j = 0;
51696   for(i=0; i<nNew; i++){
51697     /* Assemble the new sibling page. */
51698     MemPage *pNew = apNew[i];
51699     assert( j<nMaxCells );
51700     zeroPage(pNew, pageFlags);
51701     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
51702     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
51703     assert( pNew->nOverflow==0 );
51704
51705     j = cntNew[i];
51706
51707     /* If the sibling page assembled above was not the right-most sibling,
51708     ** insert a divider cell into the parent page.
51709     */
51710     assert( i<nNew-1 || j==nCell );
51711     if( j<nCell ){
51712       u8 *pCell;
51713       u8 *pTemp;
51714       int sz;
51715
51716       assert( j<nMaxCells );
51717       pCell = apCell[j];
51718       sz = szCell[j] + leafCorrection;
51719       pTemp = &aOvflSpace[iOvflSpace];
51720       if( !pNew->leaf ){
51721         memcpy(&pNew->aData[8], pCell, 4);
51722       }else if( leafData ){
51723         /* If the tree is a leaf-data tree, and the siblings are leaves, 
51724         ** then there is no divider cell in apCell[]. Instead, the divider 
51725         ** cell consists of the integer key for the right-most cell of 
51726         ** the sibling-page assembled above only.
51727         */
51728         CellInfo info;
51729         j--;
51730         btreeParseCellPtr(pNew, apCell[j], &info);
51731         pCell = pTemp;
51732         sz = 4 + putVarint(&pCell[4], info.nKey);
51733         pTemp = 0;
51734       }else{
51735         pCell -= 4;
51736         /* Obscure case for non-leaf-data trees: If the cell at pCell was
51737         ** previously stored on a leaf node, and its reported size was 4
51738         ** bytes, then it may actually be smaller than this 
51739         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
51740         ** any cell). But it is important to pass the correct size to 
51741         ** insertCell(), so reparse the cell now.
51742         **
51743         ** Note that this can never happen in an SQLite data file, as all
51744         ** cells are at least 4 bytes. It only happens in b-trees used
51745         ** to evaluate "IN (SELECT ...)" and similar clauses.
51746         */
51747         if( szCell[j]==4 ){
51748           assert(leafCorrection==4);
51749           sz = cellSizePtr(pParent, pCell);
51750         }
51751       }
51752       iOvflSpace += sz;
51753       assert( sz<=pBt->maxLocal+23 );
51754       assert( iOvflSpace<=pBt->pageSize );
51755       insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
51756       if( rc!=SQLITE_OK ) goto balance_cleanup;
51757       assert( sqlite3PagerIswriteable(pParent->pDbPage) );
51758
51759       j++;
51760       nxDiv++;
51761     }
51762   }
51763   assert( j==nCell );
51764   assert( nOld>0 );
51765   assert( nNew>0 );
51766   if( (pageFlags & PTF_LEAF)==0 ){
51767     u8 *zChild = &apCopy[nOld-1]->aData[8];
51768     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
51769   }
51770
51771   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
51772     /* The root page of the b-tree now contains no cells. The only sibling
51773     ** page is the right-child of the parent. Copy the contents of the
51774     ** child page into the parent, decreasing the overall height of the
51775     ** b-tree structure by one. This is described as the "balance-shallower"
51776     ** sub-algorithm in some documentation.
51777     **
51778     ** If this is an auto-vacuum database, the call to copyNodeContent() 
51779     ** sets all pointer-map entries corresponding to database image pages 
51780     ** for which the pointer is stored within the content being copied.
51781     **
51782     ** The second assert below verifies that the child page is defragmented
51783     ** (it must be, as it was just reconstructed using assemblePage()). This
51784     ** is important if the parent page happens to be page 1 of the database
51785     ** image.  */
51786     assert( nNew==1 );
51787     assert( apNew[0]->nFree == 
51788         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2) 
51789     );
51790     copyNodeContent(apNew[0], pParent, &rc);
51791     freePage(apNew[0], &rc);
51792   }else if( ISAUTOVACUUM ){
51793     /* Fix the pointer-map entries for all the cells that were shifted around. 
51794     ** There are several different types of pointer-map entries that need to
51795     ** be dealt with by this routine. Some of these have been set already, but
51796     ** many have not. The following is a summary:
51797     **
51798     **   1) The entries associated with new sibling pages that were not
51799     **      siblings when this function was called. These have already
51800     **      been set. We don't need to worry about old siblings that were
51801     **      moved to the free-list - the freePage() code has taken care
51802     **      of those.
51803     **
51804     **   2) The pointer-map entries associated with the first overflow
51805     **      page in any overflow chains used by new divider cells. These 
51806     **      have also already been taken care of by the insertCell() code.
51807     **
51808     **   3) If the sibling pages are not leaves, then the child pages of
51809     **      cells stored on the sibling pages may need to be updated.
51810     **
51811     **   4) If the sibling pages are not internal intkey nodes, then any
51812     **      overflow pages used by these cells may need to be updated
51813     **      (internal intkey nodes never contain pointers to overflow pages).
51814     **
51815     **   5) If the sibling pages are not leaves, then the pointer-map
51816     **      entries for the right-child pages of each sibling may need
51817     **      to be updated.
51818     **
51819     ** Cases 1 and 2 are dealt with above by other code. The next
51820     ** block deals with cases 3 and 4 and the one after that, case 5. Since
51821     ** setting a pointer map entry is a relatively expensive operation, this
51822     ** code only sets pointer map entries for child or overflow pages that have
51823     ** actually moved between pages.  */
51824     MemPage *pNew = apNew[0];
51825     MemPage *pOld = apCopy[0];
51826     int nOverflow = pOld->nOverflow;
51827     int iNextOld = pOld->nCell + nOverflow;
51828     int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
51829     j = 0;                             /* Current 'old' sibling page */
51830     k = 0;                             /* Current 'new' sibling page */
51831     for(i=0; i<nCell; i++){
51832       int isDivider = 0;
51833       while( i==iNextOld ){
51834         /* Cell i is the cell immediately following the last cell on old
51835         ** sibling page j. If the siblings are not leaf pages of an
51836         ** intkey b-tree, then cell i was a divider cell. */
51837         pOld = apCopy[++j];
51838         iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
51839         if( pOld->nOverflow ){
51840           nOverflow = pOld->nOverflow;
51841           iOverflow = i + !leafData + pOld->aOvfl[0].idx;
51842         }
51843         isDivider = !leafData;  
51844       }
51845
51846       assert(nOverflow>0 || iOverflow<i );
51847       assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
51848       assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
51849       if( i==iOverflow ){
51850         isDivider = 1;
51851         if( (--nOverflow)>0 ){
51852           iOverflow++;
51853         }
51854       }
51855
51856       if( i==cntNew[k] ){
51857         /* Cell i is the cell immediately following the last cell on new
51858         ** sibling page k. If the siblings are not leaf pages of an
51859         ** intkey b-tree, then cell i is a divider cell.  */
51860         pNew = apNew[++k];
51861         if( !leafData ) continue;
51862       }
51863       assert( j<nOld );
51864       assert( k<nNew );
51865
51866       /* If the cell was originally divider cell (and is not now) or
51867       ** an overflow cell, or if the cell was located on a different sibling
51868       ** page before the balancing, then the pointer map entries associated
51869       ** with any child or overflow pages need to be updated.  */
51870       if( isDivider || pOld->pgno!=pNew->pgno ){
51871         if( !leafCorrection ){
51872           ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
51873         }
51874         if( szCell[i]>pNew->minLocal ){
51875           ptrmapPutOvflPtr(pNew, apCell[i], &rc);
51876         }
51877       }
51878     }
51879
51880     if( !leafCorrection ){
51881       for(i=0; i<nNew; i++){
51882         u32 key = get4byte(&apNew[i]->aData[8]);
51883         ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
51884       }
51885     }
51886
51887 #if 0
51888     /* The ptrmapCheckPages() contains assert() statements that verify that
51889     ** all pointer map pages are set correctly. This is helpful while 
51890     ** debugging. This is usually disabled because a corrupt database may
51891     ** cause an assert() statement to fail.  */
51892     ptrmapCheckPages(apNew, nNew);
51893     ptrmapCheckPages(&pParent, 1);
51894 #endif
51895   }
51896
51897   assert( pParent->isInit );
51898   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
51899           nOld, nNew, nCell));
51900
51901   /*
51902   ** Cleanup before returning.
51903   */
51904 balance_cleanup:
51905   sqlite3ScratchFree(apCell);
51906   for(i=0; i<nOld; i++){
51907     releasePage(apOld[i]);
51908   }
51909   for(i=0; i<nNew; i++){
51910     releasePage(apNew[i]);
51911   }
51912
51913   return rc;
51914 }
51915
51916
51917 /*
51918 ** This function is called when the root page of a b-tree structure is
51919 ** overfull (has one or more overflow pages).
51920 **
51921 ** A new child page is allocated and the contents of the current root
51922 ** page, including overflow cells, are copied into the child. The root
51923 ** page is then overwritten to make it an empty page with the right-child 
51924 ** pointer pointing to the new page.
51925 **
51926 ** Before returning, all pointer-map entries corresponding to pages 
51927 ** that the new child-page now contains pointers to are updated. The
51928 ** entry corresponding to the new right-child pointer of the root
51929 ** page is also updated.
51930 **
51931 ** If successful, *ppChild is set to contain a reference to the child 
51932 ** page and SQLITE_OK is returned. In this case the caller is required
51933 ** to call releasePage() on *ppChild exactly once. If an error occurs,
51934 ** an error code is returned and *ppChild is set to 0.
51935 */
51936 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
51937   int rc;                        /* Return value from subprocedures */
51938   MemPage *pChild = 0;           /* Pointer to a new child page */
51939   Pgno pgnoChild = 0;            /* Page number of the new child page */
51940   BtShared *pBt = pRoot->pBt;    /* The BTree */
51941
51942   assert( pRoot->nOverflow>0 );
51943   assert( sqlite3_mutex_held(pBt->mutex) );
51944
51945   /* Make pRoot, the root page of the b-tree, writable. Allocate a new 
51946   ** page that will become the new right-child of pPage. Copy the contents
51947   ** of the node stored on pRoot into the new child page.
51948   */
51949   rc = sqlite3PagerWrite(pRoot->pDbPage);
51950   if( rc==SQLITE_OK ){
51951     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
51952     copyNodeContent(pRoot, pChild, &rc);
51953     if( ISAUTOVACUUM ){
51954       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
51955     }
51956   }
51957   if( rc ){
51958     *ppChild = 0;
51959     releasePage(pChild);
51960     return rc;
51961   }
51962   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
51963   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
51964   assert( pChild->nCell==pRoot->nCell );
51965
51966   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
51967
51968   /* Copy the overflow cells from pRoot to pChild */
51969   memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
51970   pChild->nOverflow = pRoot->nOverflow;
51971
51972   /* Zero the contents of pRoot. Then install pChild as the right-child. */
51973   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
51974   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
51975
51976   *ppChild = pChild;
51977   return SQLITE_OK;
51978 }
51979
51980 /*
51981 ** The page that pCur currently points to has just been modified in
51982 ** some way. This function figures out if this modification means the
51983 ** tree needs to be balanced, and if so calls the appropriate balancing 
51984 ** routine. Balancing routines are:
51985 **
51986 **   balance_quick()
51987 **   balance_deeper()
51988 **   balance_nonroot()
51989 */
51990 static int balance(BtCursor *pCur){
51991   int rc = SQLITE_OK;
51992   const int nMin = pCur->pBt->usableSize * 2 / 3;
51993   u8 aBalanceQuickSpace[13];
51994   u8 *pFree = 0;
51995
51996   TESTONLY( int balance_quick_called = 0 );
51997   TESTONLY( int balance_deeper_called = 0 );
51998
51999   do {
52000     int iPage = pCur->iPage;
52001     MemPage *pPage = pCur->apPage[iPage];
52002
52003     if( iPage==0 ){
52004       if( pPage->nOverflow ){
52005         /* The root page of the b-tree is overfull. In this case call the
52006         ** balance_deeper() function to create a new child for the root-page
52007         ** and copy the current contents of the root-page to it. The
52008         ** next iteration of the do-loop will balance the child page.
52009         */ 
52010         assert( (balance_deeper_called++)==0 );
52011         rc = balance_deeper(pPage, &pCur->apPage[1]);
52012         if( rc==SQLITE_OK ){
52013           pCur->iPage = 1;
52014           pCur->aiIdx[0] = 0;
52015           pCur->aiIdx[1] = 0;
52016           assert( pCur->apPage[1]->nOverflow );
52017         }
52018       }else{
52019         break;
52020       }
52021     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
52022       break;
52023     }else{
52024       MemPage * const pParent = pCur->apPage[iPage-1];
52025       int const iIdx = pCur->aiIdx[iPage-1];
52026
52027       rc = sqlite3PagerWrite(pParent->pDbPage);
52028       if( rc==SQLITE_OK ){
52029 #ifndef SQLITE_OMIT_QUICKBALANCE
52030         if( pPage->hasData
52031          && pPage->nOverflow==1
52032          && pPage->aOvfl[0].idx==pPage->nCell
52033          && pParent->pgno!=1
52034          && pParent->nCell==iIdx
52035         ){
52036           /* Call balance_quick() to create a new sibling of pPage on which
52037           ** to store the overflow cell. balance_quick() inserts a new cell
52038           ** into pParent, which may cause pParent overflow. If this
52039           ** happens, the next interation of the do-loop will balance pParent 
52040           ** use either balance_nonroot() or balance_deeper(). Until this
52041           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
52042           ** buffer. 
52043           **
52044           ** The purpose of the following assert() is to check that only a
52045           ** single call to balance_quick() is made for each call to this
52046           ** function. If this were not verified, a subtle bug involving reuse
52047           ** of the aBalanceQuickSpace[] might sneak in.
52048           */
52049           assert( (balance_quick_called++)==0 );
52050           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
52051         }else
52052 #endif
52053         {
52054           /* In this case, call balance_nonroot() to redistribute cells
52055           ** between pPage and up to 2 of its sibling pages. This involves
52056           ** modifying the contents of pParent, which may cause pParent to
52057           ** become overfull or underfull. The next iteration of the do-loop
52058           ** will balance the parent page to correct this.
52059           ** 
52060           ** If the parent page becomes overfull, the overflow cell or cells
52061           ** are stored in the pSpace buffer allocated immediately below. 
52062           ** A subsequent iteration of the do-loop will deal with this by
52063           ** calling balance_nonroot() (balance_deeper() may be called first,
52064           ** but it doesn't deal with overflow cells - just moves them to a
52065           ** different page). Once this subsequent call to balance_nonroot() 
52066           ** has completed, it is safe to release the pSpace buffer used by
52067           ** the previous call, as the overflow cell data will have been 
52068           ** copied either into the body of a database page or into the new
52069           ** pSpace buffer passed to the latter call to balance_nonroot().
52070           */
52071           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
52072           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
52073           if( pFree ){
52074             /* If pFree is not NULL, it points to the pSpace buffer used 
52075             ** by a previous call to balance_nonroot(). Its contents are
52076             ** now stored either on real database pages or within the 
52077             ** new pSpace buffer, so it may be safely freed here. */
52078             sqlite3PageFree(pFree);
52079           }
52080
52081           /* The pSpace buffer will be freed after the next call to
52082           ** balance_nonroot(), or just before this function returns, whichever
52083           ** comes first. */
52084           pFree = pSpace;
52085         }
52086       }
52087
52088       pPage->nOverflow = 0;
52089
52090       /* The next iteration of the do-loop balances the parent page. */
52091       releasePage(pPage);
52092       pCur->iPage--;
52093     }
52094   }while( rc==SQLITE_OK );
52095
52096   if( pFree ){
52097     sqlite3PageFree(pFree);
52098   }
52099   return rc;
52100 }
52101
52102
52103 /*
52104 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
52105 ** and the data is given by (pData,nData).  The cursor is used only to
52106 ** define what table the record should be inserted into.  The cursor
52107 ** is left pointing at a random location.
52108 **
52109 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
52110 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
52111 **
52112 ** If the seekResult parameter is non-zero, then a successful call to
52113 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
52114 ** been performed. seekResult is the search result returned (a negative
52115 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
52116 ** a positive value if pCur points at an etry that is larger than 
52117 ** (pKey, nKey)). 
52118 **
52119 ** If the seekResult parameter is non-zero, then the caller guarantees that
52120 ** cursor pCur is pointing at the existing copy of a row that is to be
52121 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
52122 ** point to any entry or to no entry at all and so this function has to seek
52123 ** the cursor before the new key can be inserted.
52124 */
52125 SQLITE_PRIVATE int sqlite3BtreeInsert(
52126   BtCursor *pCur,                /* Insert data into the table of this cursor */
52127   const void *pKey, i64 nKey,    /* The key of the new record */
52128   const void *pData, int nData,  /* The data of the new record */
52129   int nZero,                     /* Number of extra 0 bytes to append to data */
52130   int appendBias,                /* True if this is likely an append */
52131   int seekResult                 /* Result of prior MovetoUnpacked() call */
52132 ){
52133   int rc;
52134   int loc = seekResult;          /* -1: before desired location  +1: after */
52135   int szNew = 0;
52136   int idx;
52137   MemPage *pPage;
52138   Btree *p = pCur->pBtree;
52139   BtShared *pBt = p->pBt;
52140   unsigned char *oldCell;
52141   unsigned char *newCell = 0;
52142
52143   if( pCur->eState==CURSOR_FAULT ){
52144     assert( pCur->skipNext!=SQLITE_OK );
52145     return pCur->skipNext;
52146   }
52147
52148   assert( cursorHoldsMutex(pCur) );
52149   assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
52150   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
52151
52152   /* Assert that the caller has been consistent. If this cursor was opened
52153   ** expecting an index b-tree, then the caller should be inserting blob
52154   ** keys with no associated data. If the cursor was opened expecting an
52155   ** intkey table, the caller should be inserting integer keys with a
52156   ** blob of associated data.  */
52157   assert( (pKey==0)==(pCur->pKeyInfo==0) );
52158
52159   /* If this is an insert into a table b-tree, invalidate any incrblob 
52160   ** cursors open on the row being replaced (assuming this is a replace
52161   ** operation - if it is not, the following is a no-op).  */
52162   if( pCur->pKeyInfo==0 ){
52163     invalidateIncrblobCursors(p, nKey, 0);
52164   }
52165
52166   /* Save the positions of any other cursors open on this table.
52167   **
52168   ** In some cases, the call to btreeMoveto() below is a no-op. For
52169   ** example, when inserting data into a table with auto-generated integer
52170   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the 
52171   ** integer key to use. It then calls this function to actually insert the 
52172   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
52173   ** that the cursor is already where it needs to be and returns without
52174   ** doing any work. To avoid thwarting these optimizations, it is important
52175   ** not to clear the cursor here.
52176   */
52177   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
52178   if( rc ) return rc;
52179   if( !loc ){
52180     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
52181     if( rc ) return rc;
52182   }
52183   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
52184
52185   pPage = pCur->apPage[pCur->iPage];
52186   assert( pPage->intKey || nKey>=0 );
52187   assert( pPage->leaf || !pPage->intKey );
52188
52189   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
52190           pCur->pgnoRoot, nKey, nData, pPage->pgno,
52191           loc==0 ? "overwrite" : "new entry"));
52192   assert( pPage->isInit );
52193   allocateTempSpace(pBt);
52194   newCell = pBt->pTmpSpace;
52195   if( newCell==0 ) return SQLITE_NOMEM;
52196   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
52197   if( rc ) goto end_insert;
52198   assert( szNew==cellSizePtr(pPage, newCell) );
52199   assert( szNew<=MX_CELL_SIZE(pBt) );
52200   idx = pCur->aiIdx[pCur->iPage];
52201   if( loc==0 ){
52202     u16 szOld;
52203     assert( idx<pPage->nCell );
52204     rc = sqlite3PagerWrite(pPage->pDbPage);
52205     if( rc ){
52206       goto end_insert;
52207     }
52208     oldCell = findCell(pPage, idx);
52209     if( !pPage->leaf ){
52210       memcpy(newCell, oldCell, 4);
52211     }
52212     szOld = cellSizePtr(pPage, oldCell);
52213     rc = clearCell(pPage, oldCell);
52214     dropCell(pPage, idx, szOld, &rc);
52215     if( rc ) goto end_insert;
52216   }else if( loc<0 && pPage->nCell>0 ){
52217     assert( pPage->leaf );
52218     idx = ++pCur->aiIdx[pCur->iPage];
52219   }else{
52220     assert( pPage->leaf );
52221   }
52222   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
52223   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
52224
52225   /* If no error has occured and pPage has an overflow cell, call balance() 
52226   ** to redistribute the cells within the tree. Since balance() may move
52227   ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
52228   ** variables.
52229   **
52230   ** Previous versions of SQLite called moveToRoot() to move the cursor
52231   ** back to the root page as balance() used to invalidate the contents
52232   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
52233   ** set the cursor state to "invalid". This makes common insert operations
52234   ** slightly faster.
52235   **
52236   ** There is a subtle but important optimization here too. When inserting
52237   ** multiple records into an intkey b-tree using a single cursor (as can
52238   ** happen while processing an "INSERT INTO ... SELECT" statement), it
52239   ** is advantageous to leave the cursor pointing to the last entry in
52240   ** the b-tree if possible. If the cursor is left pointing to the last
52241   ** entry in the table, and the next row inserted has an integer key
52242   ** larger than the largest existing key, it is possible to insert the
52243   ** row without seeking the cursor. This can be a big performance boost.
52244   */
52245   pCur->info.nSize = 0;
52246   pCur->validNKey = 0;
52247   if( rc==SQLITE_OK && pPage->nOverflow ){
52248     rc = balance(pCur);
52249
52250     /* Must make sure nOverflow is reset to zero even if the balance()
52251     ** fails. Internal data structure corruption will result otherwise. 
52252     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
52253     ** from trying to save the current position of the cursor.  */
52254     pCur->apPage[pCur->iPage]->nOverflow = 0;
52255     pCur->eState = CURSOR_INVALID;
52256   }
52257   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
52258
52259 end_insert:
52260   return rc;
52261 }
52262
52263 /*
52264 ** Delete the entry that the cursor is pointing to.  The cursor
52265 ** is left pointing at a arbitrary location.
52266 */
52267 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
52268   Btree *p = pCur->pBtree;
52269   BtShared *pBt = p->pBt;              
52270   int rc;                              /* Return code */
52271   MemPage *pPage;                      /* Page to delete cell from */
52272   unsigned char *pCell;                /* Pointer to cell to delete */
52273   int iCellIdx;                        /* Index of cell to delete */
52274   int iCellDepth;                      /* Depth of node containing pCell */ 
52275
52276   assert( cursorHoldsMutex(pCur) );
52277   assert( pBt->inTransaction==TRANS_WRITE );
52278   assert( !pBt->readOnly );
52279   assert( pCur->wrFlag );
52280   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
52281   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
52282
52283   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell) 
52284    || NEVER(pCur->eState!=CURSOR_VALID)
52285   ){
52286     return SQLITE_ERROR;  /* Something has gone awry. */
52287   }
52288
52289   /* If this is a delete operation to remove a row from a table b-tree,
52290   ** invalidate any incrblob cursors open on the row being deleted.  */
52291   if( pCur->pKeyInfo==0 ){
52292     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
52293   }
52294
52295   iCellDepth = pCur->iPage;
52296   iCellIdx = pCur->aiIdx[iCellDepth];
52297   pPage = pCur->apPage[iCellDepth];
52298   pCell = findCell(pPage, iCellIdx);
52299
52300   /* If the page containing the entry to delete is not a leaf page, move
52301   ** the cursor to the largest entry in the tree that is smaller than
52302   ** the entry being deleted. This cell will replace the cell being deleted
52303   ** from the internal node. The 'previous' entry is used for this instead
52304   ** of the 'next' entry, as the previous entry is always a part of the
52305   ** sub-tree headed by the child page of the cell being deleted. This makes
52306   ** balancing the tree following the delete operation easier.  */
52307   if( !pPage->leaf ){
52308     int notUsed;
52309     rc = sqlite3BtreePrevious(pCur, &notUsed);
52310     if( rc ) return rc;
52311   }
52312
52313   /* Save the positions of any other cursors open on this table before
52314   ** making any modifications. Make the page containing the entry to be 
52315   ** deleted writable. Then free any overflow pages associated with the 
52316   ** entry and finally remove the cell itself from within the page.  
52317   */
52318   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
52319   if( rc ) return rc;
52320   rc = sqlite3PagerWrite(pPage->pDbPage);
52321   if( rc ) return rc;
52322   rc = clearCell(pPage, pCell);
52323   dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
52324   if( rc ) return rc;
52325
52326   /* If the cell deleted was not located on a leaf page, then the cursor
52327   ** is currently pointing to the largest entry in the sub-tree headed
52328   ** by the child-page of the cell that was just deleted from an internal
52329   ** node. The cell from the leaf node needs to be moved to the internal
52330   ** node to replace the deleted cell.  */
52331   if( !pPage->leaf ){
52332     MemPage *pLeaf = pCur->apPage[pCur->iPage];
52333     int nCell;
52334     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
52335     unsigned char *pTmp;
52336
52337     pCell = findCell(pLeaf, pLeaf->nCell-1);
52338     nCell = cellSizePtr(pLeaf, pCell);
52339     assert( MX_CELL_SIZE(pBt)>=nCell );
52340
52341     allocateTempSpace(pBt);
52342     pTmp = pBt->pTmpSpace;
52343
52344     rc = sqlite3PagerWrite(pLeaf->pDbPage);
52345     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
52346     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
52347     if( rc ) return rc;
52348   }
52349
52350   /* Balance the tree. If the entry deleted was located on a leaf page,
52351   ** then the cursor still points to that page. In this case the first
52352   ** call to balance() repairs the tree, and the if(...) condition is
52353   ** never true.
52354   **
52355   ** Otherwise, if the entry deleted was on an internal node page, then
52356   ** pCur is pointing to the leaf page from which a cell was removed to
52357   ** replace the cell deleted from the internal node. This is slightly
52358   ** tricky as the leaf node may be underfull, and the internal node may
52359   ** be either under or overfull. In this case run the balancing algorithm
52360   ** on the leaf node first. If the balance proceeds far enough up the
52361   ** tree that we can be sure that any problem in the internal node has
52362   ** been corrected, so be it. Otherwise, after balancing the leaf node,
52363   ** walk the cursor up the tree to the internal node and balance it as 
52364   ** well.  */
52365   rc = balance(pCur);
52366   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
52367     while( pCur->iPage>iCellDepth ){
52368       releasePage(pCur->apPage[pCur->iPage--]);
52369     }
52370     rc = balance(pCur);
52371   }
52372
52373   if( rc==SQLITE_OK ){
52374     moveToRoot(pCur);
52375   }
52376   return rc;
52377 }
52378
52379 /*
52380 ** Create a new BTree table.  Write into *piTable the page
52381 ** number for the root page of the new table.
52382 **
52383 ** The type of type is determined by the flags parameter.  Only the
52384 ** following values of flags are currently in use.  Other values for
52385 ** flags might not work:
52386 **
52387 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
52388 **     BTREE_ZERODATA                  Used for SQL indices
52389 */
52390 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
52391   BtShared *pBt = p->pBt;
52392   MemPage *pRoot;
52393   Pgno pgnoRoot;
52394   int rc;
52395   int ptfFlags;          /* Page-type flage for the root page of new table */
52396
52397   assert( sqlite3BtreeHoldsMutex(p) );
52398   assert( pBt->inTransaction==TRANS_WRITE );
52399   assert( !pBt->readOnly );
52400
52401 #ifdef SQLITE_OMIT_AUTOVACUUM
52402   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
52403   if( rc ){
52404     return rc;
52405   }
52406 #else
52407   if( pBt->autoVacuum ){
52408     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
52409     MemPage *pPageMove; /* The page to move to. */
52410
52411     /* Creating a new table may probably require moving an existing database
52412     ** to make room for the new tables root page. In case this page turns
52413     ** out to be an overflow page, delete all overflow page-map caches
52414     ** held by open cursors.
52415     */
52416     invalidateAllOverflowCache(pBt);
52417
52418     /* Read the value of meta[3] from the database to determine where the
52419     ** root page of the new table should go. meta[3] is the largest root-page
52420     ** created so far, so the new root-page is (meta[3]+1).
52421     */
52422     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
52423     pgnoRoot++;
52424
52425     /* The new root-page may not be allocated on a pointer-map page, or the
52426     ** PENDING_BYTE page.
52427     */
52428     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
52429         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
52430       pgnoRoot++;
52431     }
52432     assert( pgnoRoot>=3 );
52433
52434     /* Allocate a page. The page that currently resides at pgnoRoot will
52435     ** be moved to the allocated page (unless the allocated page happens
52436     ** to reside at pgnoRoot).
52437     */
52438     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
52439     if( rc!=SQLITE_OK ){
52440       return rc;
52441     }
52442
52443     if( pgnoMove!=pgnoRoot ){
52444       /* pgnoRoot is the page that will be used for the root-page of
52445       ** the new table (assuming an error did not occur). But we were
52446       ** allocated pgnoMove. If required (i.e. if it was not allocated
52447       ** by extending the file), the current page at position pgnoMove
52448       ** is already journaled.
52449       */
52450       u8 eType = 0;
52451       Pgno iPtrPage = 0;
52452
52453       releasePage(pPageMove);
52454
52455       /* Move the page currently at pgnoRoot to pgnoMove. */
52456       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
52457       if( rc!=SQLITE_OK ){
52458         return rc;
52459       }
52460       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
52461       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
52462         rc = SQLITE_CORRUPT_BKPT;
52463       }
52464       if( rc!=SQLITE_OK ){
52465         releasePage(pRoot);
52466         return rc;
52467       }
52468       assert( eType!=PTRMAP_ROOTPAGE );
52469       assert( eType!=PTRMAP_FREEPAGE );
52470       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
52471       releasePage(pRoot);
52472
52473       /* Obtain the page at pgnoRoot */
52474       if( rc!=SQLITE_OK ){
52475         return rc;
52476       }
52477       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
52478       if( rc!=SQLITE_OK ){
52479         return rc;
52480       }
52481       rc = sqlite3PagerWrite(pRoot->pDbPage);
52482       if( rc!=SQLITE_OK ){
52483         releasePage(pRoot);
52484         return rc;
52485       }
52486     }else{
52487       pRoot = pPageMove;
52488     } 
52489
52490     /* Update the pointer-map and meta-data with the new root-page number. */
52491     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
52492     if( rc ){
52493       releasePage(pRoot);
52494       return rc;
52495     }
52496
52497     /* When the new root page was allocated, page 1 was made writable in
52498     ** order either to increase the database filesize, or to decrement the
52499     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
52500     */
52501     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
52502     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
52503     if( NEVER(rc) ){
52504       releasePage(pRoot);
52505       return rc;
52506     }
52507
52508   }else{
52509     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
52510     if( rc ) return rc;
52511   }
52512 #endif
52513   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
52514   if( createTabFlags & BTREE_INTKEY ){
52515     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
52516   }else{
52517     ptfFlags = PTF_ZERODATA | PTF_LEAF;
52518   }
52519   zeroPage(pRoot, ptfFlags);
52520   sqlite3PagerUnref(pRoot->pDbPage);
52521   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
52522   *piTable = (int)pgnoRoot;
52523   return SQLITE_OK;
52524 }
52525 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
52526   int rc;
52527   sqlite3BtreeEnter(p);
52528   rc = btreeCreateTable(p, piTable, flags);
52529   sqlite3BtreeLeave(p);
52530   return rc;
52531 }
52532
52533 /*
52534 ** Erase the given database page and all its children.  Return
52535 ** the page to the freelist.
52536 */
52537 static int clearDatabasePage(
52538   BtShared *pBt,           /* The BTree that contains the table */
52539   Pgno pgno,               /* Page number to clear */
52540   int freePageFlag,        /* Deallocate page if true */
52541   int *pnChange            /* Add number of Cells freed to this counter */
52542 ){
52543   MemPage *pPage;
52544   int rc;
52545   unsigned char *pCell;
52546   int i;
52547
52548   assert( sqlite3_mutex_held(pBt->mutex) );
52549   if( pgno>btreePagecount(pBt) ){
52550     return SQLITE_CORRUPT_BKPT;
52551   }
52552
52553   rc = getAndInitPage(pBt, pgno, &pPage);
52554   if( rc ) return rc;
52555   for(i=0; i<pPage->nCell; i++){
52556     pCell = findCell(pPage, i);
52557     if( !pPage->leaf ){
52558       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
52559       if( rc ) goto cleardatabasepage_out;
52560     }
52561     rc = clearCell(pPage, pCell);
52562     if( rc ) goto cleardatabasepage_out;
52563   }
52564   if( !pPage->leaf ){
52565     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
52566     if( rc ) goto cleardatabasepage_out;
52567   }else if( pnChange ){
52568     assert( pPage->intKey );
52569     *pnChange += pPage->nCell;
52570   }
52571   if( freePageFlag ){
52572     freePage(pPage, &rc);
52573   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
52574     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
52575   }
52576
52577 cleardatabasepage_out:
52578   releasePage(pPage);
52579   return rc;
52580 }
52581
52582 /*
52583 ** Delete all information from a single table in the database.  iTable is
52584 ** the page number of the root of the table.  After this routine returns,
52585 ** the root page is empty, but still exists.
52586 **
52587 ** This routine will fail with SQLITE_LOCKED if there are any open
52588 ** read cursors on the table.  Open write cursors are moved to the
52589 ** root of the table.
52590 **
52591 ** If pnChange is not NULL, then table iTable must be an intkey table. The
52592 ** integer value pointed to by pnChange is incremented by the number of
52593 ** entries in the table.
52594 */
52595 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
52596   int rc;
52597   BtShared *pBt = p->pBt;
52598   sqlite3BtreeEnter(p);
52599   assert( p->inTrans==TRANS_WRITE );
52600
52601   /* Invalidate all incrblob cursors open on table iTable (assuming iTable
52602   ** is the root of a table b-tree - if it is not, the following call is
52603   ** a no-op).  */
52604   invalidateIncrblobCursors(p, 0, 1);
52605
52606   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
52607   if( SQLITE_OK==rc ){
52608     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
52609   }
52610   sqlite3BtreeLeave(p);
52611   return rc;
52612 }
52613
52614 /*
52615 ** Erase all information in a table and add the root of the table to
52616 ** the freelist.  Except, the root of the principle table (the one on
52617 ** page 1) is never added to the freelist.
52618 **
52619 ** This routine will fail with SQLITE_LOCKED if there are any open
52620 ** cursors on the table.
52621 **
52622 ** If AUTOVACUUM is enabled and the page at iTable is not the last
52623 ** root page in the database file, then the last root page 
52624 ** in the database file is moved into the slot formerly occupied by
52625 ** iTable and that last slot formerly occupied by the last root page
52626 ** is added to the freelist instead of iTable.  In this say, all
52627 ** root pages are kept at the beginning of the database file, which
52628 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
52629 ** page number that used to be the last root page in the file before
52630 ** the move.  If no page gets moved, *piMoved is set to 0.
52631 ** The last root page is recorded in meta[3] and the value of
52632 ** meta[3] is updated by this procedure.
52633 */
52634 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
52635   int rc;
52636   MemPage *pPage = 0;
52637   BtShared *pBt = p->pBt;
52638
52639   assert( sqlite3BtreeHoldsMutex(p) );
52640   assert( p->inTrans==TRANS_WRITE );
52641
52642   /* It is illegal to drop a table if any cursors are open on the
52643   ** database. This is because in auto-vacuum mode the backend may
52644   ** need to move another root-page to fill a gap left by the deleted
52645   ** root page. If an open cursor was using this page a problem would 
52646   ** occur.
52647   **
52648   ** This error is caught long before control reaches this point.
52649   */
52650   if( NEVER(pBt->pCursor) ){
52651     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
52652     return SQLITE_LOCKED_SHAREDCACHE;
52653   }
52654
52655   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
52656   if( rc ) return rc;
52657   rc = sqlite3BtreeClearTable(p, iTable, 0);
52658   if( rc ){
52659     releasePage(pPage);
52660     return rc;
52661   }
52662
52663   *piMoved = 0;
52664
52665   if( iTable>1 ){
52666 #ifdef SQLITE_OMIT_AUTOVACUUM
52667     freePage(pPage, &rc);
52668     releasePage(pPage);
52669 #else
52670     if( pBt->autoVacuum ){
52671       Pgno maxRootPgno;
52672       sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
52673
52674       if( iTable==maxRootPgno ){
52675         /* If the table being dropped is the table with the largest root-page
52676         ** number in the database, put the root page on the free list. 
52677         */
52678         freePage(pPage, &rc);
52679         releasePage(pPage);
52680         if( rc!=SQLITE_OK ){
52681           return rc;
52682         }
52683       }else{
52684         /* The table being dropped does not have the largest root-page
52685         ** number in the database. So move the page that does into the 
52686         ** gap left by the deleted root-page.
52687         */
52688         MemPage *pMove;
52689         releasePage(pPage);
52690         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
52691         if( rc!=SQLITE_OK ){
52692           return rc;
52693         }
52694         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
52695         releasePage(pMove);
52696         if( rc!=SQLITE_OK ){
52697           return rc;
52698         }
52699         pMove = 0;
52700         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
52701         freePage(pMove, &rc);
52702         releasePage(pMove);
52703         if( rc!=SQLITE_OK ){
52704           return rc;
52705         }
52706         *piMoved = maxRootPgno;
52707       }
52708
52709       /* Set the new 'max-root-page' value in the database header. This
52710       ** is the old value less one, less one more if that happens to
52711       ** be a root-page number, less one again if that is the
52712       ** PENDING_BYTE_PAGE.
52713       */
52714       maxRootPgno--;
52715       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
52716              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
52717         maxRootPgno--;
52718       }
52719       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
52720
52721       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
52722     }else{
52723       freePage(pPage, &rc);
52724       releasePage(pPage);
52725     }
52726 #endif
52727   }else{
52728     /* If sqlite3BtreeDropTable was called on page 1.
52729     ** This really never should happen except in a corrupt
52730     ** database. 
52731     */
52732     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
52733     releasePage(pPage);
52734   }
52735   return rc;  
52736 }
52737 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
52738   int rc;
52739   sqlite3BtreeEnter(p);
52740   rc = btreeDropTable(p, iTable, piMoved);
52741   sqlite3BtreeLeave(p);
52742   return rc;
52743 }
52744
52745
52746 /*
52747 ** This function may only be called if the b-tree connection already
52748 ** has a read or write transaction open on the database.
52749 **
52750 ** Read the meta-information out of a database file.  Meta[0]
52751 ** is the number of free pages currently in the database.  Meta[1]
52752 ** through meta[15] are available for use by higher layers.  Meta[0]
52753 ** is read-only, the others are read/write.
52754 ** 
52755 ** The schema layer numbers meta values differently.  At the schema
52756 ** layer (and the SetCookie and ReadCookie opcodes) the number of
52757 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
52758 */
52759 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
52760   BtShared *pBt = p->pBt;
52761
52762   sqlite3BtreeEnter(p);
52763   assert( p->inTrans>TRANS_NONE );
52764   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
52765   assert( pBt->pPage1 );
52766   assert( idx>=0 && idx<=15 );
52767
52768   *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
52769
52770   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
52771   ** database, mark the database as read-only.  */
52772 #ifdef SQLITE_OMIT_AUTOVACUUM
52773   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
52774 #endif
52775
52776   sqlite3BtreeLeave(p);
52777 }
52778
52779 /*
52780 ** Write meta-information back into the database.  Meta[0] is
52781 ** read-only and may not be written.
52782 */
52783 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
52784   BtShared *pBt = p->pBt;
52785   unsigned char *pP1;
52786   int rc;
52787   assert( idx>=1 && idx<=15 );
52788   sqlite3BtreeEnter(p);
52789   assert( p->inTrans==TRANS_WRITE );
52790   assert( pBt->pPage1!=0 );
52791   pP1 = pBt->pPage1->aData;
52792   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
52793   if( rc==SQLITE_OK ){
52794     put4byte(&pP1[36 + idx*4], iMeta);
52795 #ifndef SQLITE_OMIT_AUTOVACUUM
52796     if( idx==BTREE_INCR_VACUUM ){
52797       assert( pBt->autoVacuum || iMeta==0 );
52798       assert( iMeta==0 || iMeta==1 );
52799       pBt->incrVacuum = (u8)iMeta;
52800     }
52801 #endif
52802   }
52803   sqlite3BtreeLeave(p);
52804   return rc;
52805 }
52806
52807 #ifndef SQLITE_OMIT_BTREECOUNT
52808 /*
52809 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
52810 ** number of entries in the b-tree and write the result to *pnEntry.
52811 **
52812 ** SQLITE_OK is returned if the operation is successfully executed. 
52813 ** Otherwise, if an error is encountered (i.e. an IO error or database
52814 ** corruption) an SQLite error code is returned.
52815 */
52816 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
52817   i64 nEntry = 0;                      /* Value to return in *pnEntry */
52818   int rc;                              /* Return code */
52819   rc = moveToRoot(pCur);
52820
52821   /* Unless an error occurs, the following loop runs one iteration for each
52822   ** page in the B-Tree structure (not including overflow pages). 
52823   */
52824   while( rc==SQLITE_OK ){
52825     int iIdx;                          /* Index of child node in parent */
52826     MemPage *pPage;                    /* Current page of the b-tree */
52827
52828     /* If this is a leaf page or the tree is not an int-key tree, then 
52829     ** this page contains countable entries. Increment the entry counter
52830     ** accordingly.
52831     */
52832     pPage = pCur->apPage[pCur->iPage];
52833     if( pPage->leaf || !pPage->intKey ){
52834       nEntry += pPage->nCell;
52835     }
52836
52837     /* pPage is a leaf node. This loop navigates the cursor so that it 
52838     ** points to the first interior cell that it points to the parent of
52839     ** the next page in the tree that has not yet been visited. The
52840     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
52841     ** of the page, or to the number of cells in the page if the next page
52842     ** to visit is the right-child of its parent.
52843     **
52844     ** If all pages in the tree have been visited, return SQLITE_OK to the
52845     ** caller.
52846     */
52847     if( pPage->leaf ){
52848       do {
52849         if( pCur->iPage==0 ){
52850           /* All pages of the b-tree have been visited. Return successfully. */
52851           *pnEntry = nEntry;
52852           return SQLITE_OK;
52853         }
52854         moveToParent(pCur);
52855       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
52856
52857       pCur->aiIdx[pCur->iPage]++;
52858       pPage = pCur->apPage[pCur->iPage];
52859     }
52860
52861     /* Descend to the child node of the cell that the cursor currently 
52862     ** points at. This is the right-child if (iIdx==pPage->nCell).
52863     */
52864     iIdx = pCur->aiIdx[pCur->iPage];
52865     if( iIdx==pPage->nCell ){
52866       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
52867     }else{
52868       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
52869     }
52870   }
52871
52872   /* An error has occurred. Return an error code. */
52873   return rc;
52874 }
52875 #endif
52876
52877 /*
52878 ** Return the pager associated with a BTree.  This routine is used for
52879 ** testing and debugging only.
52880 */
52881 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
52882   return p->pBt->pPager;
52883 }
52884
52885 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
52886 /*
52887 ** Append a message to the error message string.
52888 */
52889 static void checkAppendMsg(
52890   IntegrityCk *pCheck,
52891   char *zMsg1,
52892   const char *zFormat,
52893   ...
52894 ){
52895   va_list ap;
52896   if( !pCheck->mxErr ) return;
52897   pCheck->mxErr--;
52898   pCheck->nErr++;
52899   va_start(ap, zFormat);
52900   if( pCheck->errMsg.nChar ){
52901     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
52902   }
52903   if( zMsg1 ){
52904     sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
52905   }
52906   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
52907   va_end(ap);
52908   if( pCheck->errMsg.mallocFailed ){
52909     pCheck->mallocFailed = 1;
52910   }
52911 }
52912 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
52913
52914 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
52915 /*
52916 ** Add 1 to the reference count for page iPage.  If this is the second
52917 ** reference to the page, add an error message to pCheck->zErrMsg.
52918 ** Return 1 if there are 2 ore more references to the page and 0 if
52919 ** if this is the first reference to the page.
52920 **
52921 ** Also check that the page number is in bounds.
52922 */
52923 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
52924   if( iPage==0 ) return 1;
52925   if( iPage>pCheck->nPage ){
52926     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
52927     return 1;
52928   }
52929   if( pCheck->anRef[iPage]==1 ){
52930     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
52931     return 1;
52932   }
52933   return  (pCheck->anRef[iPage]++)>1;
52934 }
52935
52936 #ifndef SQLITE_OMIT_AUTOVACUUM
52937 /*
52938 ** Check that the entry in the pointer-map for page iChild maps to 
52939 ** page iParent, pointer type ptrType. If not, append an error message
52940 ** to pCheck.
52941 */
52942 static void checkPtrmap(
52943   IntegrityCk *pCheck,   /* Integrity check context */
52944   Pgno iChild,           /* Child page number */
52945   u8 eType,              /* Expected pointer map type */
52946   Pgno iParent,          /* Expected pointer map parent page number */
52947   char *zContext         /* Context description (used for error msg) */
52948 ){
52949   int rc;
52950   u8 ePtrmapType;
52951   Pgno iPtrmapParent;
52952
52953   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
52954   if( rc!=SQLITE_OK ){
52955     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
52956     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
52957     return;
52958   }
52959
52960   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
52961     checkAppendMsg(pCheck, zContext, 
52962       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
52963       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
52964   }
52965 }
52966 #endif
52967
52968 /*
52969 ** Check the integrity of the freelist or of an overflow page list.
52970 ** Verify that the number of pages on the list is N.
52971 */
52972 static void checkList(
52973   IntegrityCk *pCheck,  /* Integrity checking context */
52974   int isFreeList,       /* True for a freelist.  False for overflow page list */
52975   int iPage,            /* Page number for first page in the list */
52976   int N,                /* Expected number of pages in the list */
52977   char *zContext        /* Context for error messages */
52978 ){
52979   int i;
52980   int expected = N;
52981   int iFirst = iPage;
52982   while( N-- > 0 && pCheck->mxErr ){
52983     DbPage *pOvflPage;
52984     unsigned char *pOvflData;
52985     if( iPage<1 ){
52986       checkAppendMsg(pCheck, zContext,
52987          "%d of %d pages missing from overflow list starting at %d",
52988           N+1, expected, iFirst);
52989       break;
52990     }
52991     if( checkRef(pCheck, iPage, zContext) ) break;
52992     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
52993       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
52994       break;
52995     }
52996     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
52997     if( isFreeList ){
52998       int n = get4byte(&pOvflData[4]);
52999 #ifndef SQLITE_OMIT_AUTOVACUUM
53000       if( pCheck->pBt->autoVacuum ){
53001         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
53002       }
53003 #endif
53004       if( n>(int)pCheck->pBt->usableSize/4-2 ){
53005         checkAppendMsg(pCheck, zContext,
53006            "freelist leaf count too big on page %d", iPage);
53007         N--;
53008       }else{
53009         for(i=0; i<n; i++){
53010           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
53011 #ifndef SQLITE_OMIT_AUTOVACUUM
53012           if( pCheck->pBt->autoVacuum ){
53013             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
53014           }
53015 #endif
53016           checkRef(pCheck, iFreePage, zContext);
53017         }
53018         N -= n;
53019       }
53020     }
53021 #ifndef SQLITE_OMIT_AUTOVACUUM
53022     else{
53023       /* If this database supports auto-vacuum and iPage is not the last
53024       ** page in this overflow list, check that the pointer-map entry for
53025       ** the following page matches iPage.
53026       */
53027       if( pCheck->pBt->autoVacuum && N>0 ){
53028         i = get4byte(pOvflData);
53029         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
53030       }
53031     }
53032 #endif
53033     iPage = get4byte(pOvflData);
53034     sqlite3PagerUnref(pOvflPage);
53035   }
53036 }
53037 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
53038
53039 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
53040 /*
53041 ** Do various sanity checks on a single page of a tree.  Return
53042 ** the tree depth.  Root pages return 0.  Parents of root pages
53043 ** return 1, and so forth.
53044 ** 
53045 ** These checks are done:
53046 **
53047 **      1.  Make sure that cells and freeblocks do not overlap
53048 **          but combine to completely cover the page.
53049 **  NO  2.  Make sure cell keys are in order.
53050 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
53051 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
53052 **      5.  Check the integrity of overflow pages.
53053 **      6.  Recursively call checkTreePage on all children.
53054 **      7.  Verify that the depth of all children is the same.
53055 **      8.  Make sure this page is at least 33% full or else it is
53056 **          the root of the tree.
53057 */
53058 static int checkTreePage(
53059   IntegrityCk *pCheck,  /* Context for the sanity check */
53060   int iPage,            /* Page number of the page to check */
53061   char *zParentContext, /* Parent context */
53062   i64 *pnParentMinKey, 
53063   i64 *pnParentMaxKey
53064 ){
53065   MemPage *pPage;
53066   int i, rc, depth, d2, pgno, cnt;
53067   int hdr, cellStart;
53068   int nCell;
53069   u8 *data;
53070   BtShared *pBt;
53071   int usableSize;
53072   char zContext[100];
53073   char *hit = 0;
53074   i64 nMinKey = 0;
53075   i64 nMaxKey = 0;
53076
53077   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
53078
53079   /* Check that the page exists
53080   */
53081   pBt = pCheck->pBt;
53082   usableSize = pBt->usableSize;
53083   if( iPage==0 ) return 0;
53084   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
53085   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
53086     checkAppendMsg(pCheck, zContext,
53087        "unable to get the page. error code=%d", rc);
53088     return 0;
53089   }
53090
53091   /* Clear MemPage.isInit to make sure the corruption detection code in
53092   ** btreeInitPage() is executed.  */
53093   pPage->isInit = 0;
53094   if( (rc = btreeInitPage(pPage))!=0 ){
53095     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
53096     checkAppendMsg(pCheck, zContext, 
53097                    "btreeInitPage() returns error code %d", rc);
53098     releasePage(pPage);
53099     return 0;
53100   }
53101
53102   /* Check out all the cells.
53103   */
53104   depth = 0;
53105   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
53106     u8 *pCell;
53107     u32 sz;
53108     CellInfo info;
53109
53110     /* Check payload overflow pages
53111     */
53112     sqlite3_snprintf(sizeof(zContext), zContext,
53113              "On tree page %d cell %d: ", iPage, i);
53114     pCell = findCell(pPage,i);
53115     btreeParseCellPtr(pPage, pCell, &info);
53116     sz = info.nData;
53117     if( !pPage->intKey ) sz += (int)info.nKey;
53118     /* For intKey pages, check that the keys are in order.
53119     */
53120     else if( i==0 ) nMinKey = nMaxKey = info.nKey;
53121     else{
53122       if( info.nKey <= nMaxKey ){
53123         checkAppendMsg(pCheck, zContext, 
53124             "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
53125       }
53126       nMaxKey = info.nKey;
53127     }
53128     assert( sz==info.nPayload );
53129     if( (sz>info.nLocal) 
53130      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
53131     ){
53132       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
53133       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
53134 #ifndef SQLITE_OMIT_AUTOVACUUM
53135       if( pBt->autoVacuum ){
53136         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
53137       }
53138 #endif
53139       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
53140     }
53141
53142     /* Check sanity of left child page.
53143     */
53144     if( !pPage->leaf ){
53145       pgno = get4byte(pCell);
53146 #ifndef SQLITE_OMIT_AUTOVACUUM
53147       if( pBt->autoVacuum ){
53148         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
53149       }
53150 #endif
53151       d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
53152       if( i>0 && d2!=depth ){
53153         checkAppendMsg(pCheck, zContext, "Child page depth differs");
53154       }
53155       depth = d2;
53156     }
53157   }
53158
53159   if( !pPage->leaf ){
53160     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
53161     sqlite3_snprintf(sizeof(zContext), zContext, 
53162                      "On page %d at right child: ", iPage);
53163 #ifndef SQLITE_OMIT_AUTOVACUUM
53164     if( pBt->autoVacuum ){
53165       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
53166     }
53167 #endif
53168     checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
53169   }
53170  
53171   /* For intKey leaf pages, check that the min/max keys are in order
53172   ** with any left/parent/right pages.
53173   */
53174   if( pPage->leaf && pPage->intKey ){
53175     /* if we are a left child page */
53176     if( pnParentMinKey ){
53177       /* if we are the left most child page */
53178       if( !pnParentMaxKey ){
53179         if( nMaxKey > *pnParentMinKey ){
53180           checkAppendMsg(pCheck, zContext, 
53181               "Rowid %lld out of order (max larger than parent min of %lld)",
53182               nMaxKey, *pnParentMinKey);
53183         }
53184       }else{
53185         if( nMinKey <= *pnParentMinKey ){
53186           checkAppendMsg(pCheck, zContext, 
53187               "Rowid %lld out of order (min less than parent min of %lld)",
53188               nMinKey, *pnParentMinKey);
53189         }
53190         if( nMaxKey > *pnParentMaxKey ){
53191           checkAppendMsg(pCheck, zContext, 
53192               "Rowid %lld out of order (max larger than parent max of %lld)",
53193               nMaxKey, *pnParentMaxKey);
53194         }
53195         *pnParentMinKey = nMaxKey;
53196       }
53197     /* else if we're a right child page */
53198     } else if( pnParentMaxKey ){
53199       if( nMinKey <= *pnParentMaxKey ){
53200         checkAppendMsg(pCheck, zContext, 
53201             "Rowid %lld out of order (min less than parent max of %lld)",
53202             nMinKey, *pnParentMaxKey);
53203       }
53204     }
53205   }
53206
53207   /* Check for complete coverage of the page
53208   */
53209   data = pPage->aData;
53210   hdr = pPage->hdrOffset;
53211   hit = sqlite3PageMalloc( pBt->pageSize );
53212   if( hit==0 ){
53213     pCheck->mallocFailed = 1;
53214   }else{
53215     int contentOffset = get2byteNotZero(&data[hdr+5]);
53216     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
53217     memset(hit+contentOffset, 0, usableSize-contentOffset);
53218     memset(hit, 1, contentOffset);
53219     nCell = get2byte(&data[hdr+3]);
53220     cellStart = hdr + 12 - 4*pPage->leaf;
53221     for(i=0; i<nCell; i++){
53222       int pc = get2byte(&data[cellStart+i*2]);
53223       u32 size = 65536;
53224       int j;
53225       if( pc<=usableSize-4 ){
53226         size = cellSizePtr(pPage, &data[pc]);
53227       }
53228       if( (int)(pc+size-1)>=usableSize ){
53229         checkAppendMsg(pCheck, 0, 
53230             "Corruption detected in cell %d on page %d",i,iPage);
53231       }else{
53232         for(j=pc+size-1; j>=pc; j--) hit[j]++;
53233       }
53234     }
53235     i = get2byte(&data[hdr+1]);
53236     while( i>0 ){
53237       int size, j;
53238       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
53239       size = get2byte(&data[i+2]);
53240       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
53241       for(j=i+size-1; j>=i; j--) hit[j]++;
53242       j = get2byte(&data[i]);
53243       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
53244       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
53245       i = j;
53246     }
53247     for(i=cnt=0; i<usableSize; i++){
53248       if( hit[i]==0 ){
53249         cnt++;
53250       }else if( hit[i]>1 ){
53251         checkAppendMsg(pCheck, 0,
53252           "Multiple uses for byte %d of page %d", i, iPage);
53253         break;
53254       }
53255     }
53256     if( cnt!=data[hdr+7] ){
53257       checkAppendMsg(pCheck, 0, 
53258           "Fragmentation of %d bytes reported as %d on page %d",
53259           cnt, data[hdr+7], iPage);
53260     }
53261   }
53262   sqlite3PageFree(hit);
53263   releasePage(pPage);
53264   return depth+1;
53265 }
53266 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
53267
53268 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
53269 /*
53270 ** This routine does a complete check of the given BTree file.  aRoot[] is
53271 ** an array of pages numbers were each page number is the root page of
53272 ** a table.  nRoot is the number of entries in aRoot.
53273 **
53274 ** A read-only or read-write transaction must be opened before calling
53275 ** this function.
53276 **
53277 ** Write the number of error seen in *pnErr.  Except for some memory
53278 ** allocation errors,  an error message held in memory obtained from
53279 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
53280 ** returned.  If a memory allocation error occurs, NULL is returned.
53281 */
53282 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
53283   Btree *p,     /* The btree to be checked */
53284   int *aRoot,   /* An array of root pages numbers for individual trees */
53285   int nRoot,    /* Number of entries in aRoot[] */
53286   int mxErr,    /* Stop reporting errors after this many */
53287   int *pnErr    /* Write number of errors seen to this variable */
53288 ){
53289   Pgno i;
53290   int nRef;
53291   IntegrityCk sCheck;
53292   BtShared *pBt = p->pBt;
53293   char zErr[100];
53294
53295   sqlite3BtreeEnter(p);
53296   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
53297   nRef = sqlite3PagerRefcount(pBt->pPager);
53298   sCheck.pBt = pBt;
53299   sCheck.pPager = pBt->pPager;
53300   sCheck.nPage = btreePagecount(sCheck.pBt);
53301   sCheck.mxErr = mxErr;
53302   sCheck.nErr = 0;
53303   sCheck.mallocFailed = 0;
53304   *pnErr = 0;
53305   if( sCheck.nPage==0 ){
53306     sqlite3BtreeLeave(p);
53307     return 0;
53308   }
53309   sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
53310   if( !sCheck.anRef ){
53311     *pnErr = 1;
53312     sqlite3BtreeLeave(p);
53313     return 0;
53314   }
53315   for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
53316   i = PENDING_BYTE_PAGE(pBt);
53317   if( i<=sCheck.nPage ){
53318     sCheck.anRef[i] = 1;
53319   }
53320   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
53321   sCheck.errMsg.useMalloc = 2;
53322
53323   /* Check the integrity of the freelist
53324   */
53325   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
53326             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
53327
53328   /* Check all the tables.
53329   */
53330   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
53331     if( aRoot[i]==0 ) continue;
53332 #ifndef SQLITE_OMIT_AUTOVACUUM
53333     if( pBt->autoVacuum && aRoot[i]>1 ){
53334       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
53335     }
53336 #endif
53337     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
53338   }
53339
53340   /* Make sure every page in the file is referenced
53341   */
53342   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
53343 #ifdef SQLITE_OMIT_AUTOVACUUM
53344     if( sCheck.anRef[i]==0 ){
53345       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
53346     }
53347 #else
53348     /* If the database supports auto-vacuum, make sure no tables contain
53349     ** references to pointer-map pages.
53350     */
53351     if( sCheck.anRef[i]==0 && 
53352        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
53353       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
53354     }
53355     if( sCheck.anRef[i]!=0 && 
53356        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
53357       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
53358     }
53359 #endif
53360   }
53361
53362   /* Make sure this analysis did not leave any unref() pages.
53363   ** This is an internal consistency check; an integrity check
53364   ** of the integrity check.
53365   */
53366   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
53367     checkAppendMsg(&sCheck, 0, 
53368       "Outstanding page count goes from %d to %d during this analysis",
53369       nRef, sqlite3PagerRefcount(pBt->pPager)
53370     );
53371   }
53372
53373   /* Clean  up and report errors.
53374   */
53375   sqlite3BtreeLeave(p);
53376   sqlite3_free(sCheck.anRef);
53377   if( sCheck.mallocFailed ){
53378     sqlite3StrAccumReset(&sCheck.errMsg);
53379     *pnErr = sCheck.nErr+1;
53380     return 0;
53381   }
53382   *pnErr = sCheck.nErr;
53383   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
53384   return sqlite3StrAccumFinish(&sCheck.errMsg);
53385 }
53386 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
53387
53388 /*
53389 ** Return the full pathname of the underlying database file.
53390 **
53391 ** The pager filename is invariant as long as the pager is
53392 ** open so it is safe to access without the BtShared mutex.
53393 */
53394 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
53395   assert( p->pBt->pPager!=0 );
53396   return sqlite3PagerFilename(p->pBt->pPager);
53397 }
53398
53399 /*
53400 ** Return the pathname of the journal file for this database. The return
53401 ** value of this routine is the same regardless of whether the journal file
53402 ** has been created or not.
53403 **
53404 ** The pager journal filename is invariant as long as the pager is
53405 ** open so it is safe to access without the BtShared mutex.
53406 */
53407 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
53408   assert( p->pBt->pPager!=0 );
53409   return sqlite3PagerJournalname(p->pBt->pPager);
53410 }
53411
53412 /*
53413 ** Return non-zero if a transaction is active.
53414 */
53415 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
53416   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
53417   return (p && (p->inTrans==TRANS_WRITE));
53418 }
53419
53420 #ifndef SQLITE_OMIT_WAL
53421 /*
53422 ** Run a checkpoint on the Btree passed as the first argument.
53423 **
53424 ** Return SQLITE_LOCKED if this or any other connection has an open 
53425 ** transaction on the shared-cache the argument Btree is connected to.
53426 */
53427 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p){
53428   int rc = SQLITE_OK;
53429   if( p ){
53430     BtShared *pBt = p->pBt;
53431     sqlite3BtreeEnter(p);
53432     if( pBt->inTransaction!=TRANS_NONE ){
53433       rc = SQLITE_LOCKED;
53434     }else{
53435       rc = sqlite3PagerCheckpoint(pBt->pPager);
53436     }
53437     sqlite3BtreeLeave(p);
53438   }
53439   return rc;
53440 }
53441 #endif
53442
53443 /*
53444 ** Return non-zero if a read (or write) transaction is active.
53445 */
53446 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
53447   assert( p );
53448   assert( sqlite3_mutex_held(p->db->mutex) );
53449   return p->inTrans!=TRANS_NONE;
53450 }
53451
53452 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
53453   assert( p );
53454   assert( sqlite3_mutex_held(p->db->mutex) );
53455   return p->nBackup!=0;
53456 }
53457
53458 /*
53459 ** This function returns a pointer to a blob of memory associated with
53460 ** a single shared-btree. The memory is used by client code for its own
53461 ** purposes (for example, to store a high-level schema associated with 
53462 ** the shared-btree). The btree layer manages reference counting issues.
53463 **
53464 ** The first time this is called on a shared-btree, nBytes bytes of memory
53465 ** are allocated, zeroed, and returned to the caller. For each subsequent 
53466 ** call the nBytes parameter is ignored and a pointer to the same blob
53467 ** of memory returned. 
53468 **
53469 ** If the nBytes parameter is 0 and the blob of memory has not yet been
53470 ** allocated, a null pointer is returned. If the blob has already been
53471 ** allocated, it is returned as normal.
53472 **
53473 ** Just before the shared-btree is closed, the function passed as the 
53474 ** xFree argument when the memory allocation was made is invoked on the 
53475 ** blob of allocated memory. This function should not call sqlite3_free()
53476 ** on the memory, the btree layer does that.
53477 */
53478 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
53479   BtShared *pBt = p->pBt;
53480   sqlite3BtreeEnter(p);
53481   if( !pBt->pSchema && nBytes ){
53482     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
53483     pBt->xFreeSchema = xFree;
53484   }
53485   sqlite3BtreeLeave(p);
53486   return pBt->pSchema;
53487 }
53488
53489 /*
53490 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared 
53491 ** btree as the argument handle holds an exclusive lock on the 
53492 ** sqlite_master table. Otherwise SQLITE_OK.
53493 */
53494 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
53495   int rc;
53496   assert( sqlite3_mutex_held(p->db->mutex) );
53497   sqlite3BtreeEnter(p);
53498   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
53499   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
53500   sqlite3BtreeLeave(p);
53501   return rc;
53502 }
53503
53504
53505 #ifndef SQLITE_OMIT_SHARED_CACHE
53506 /*
53507 ** Obtain a lock on the table whose root page is iTab.  The
53508 ** lock is a write lock if isWritelock is true or a read lock
53509 ** if it is false.
53510 */
53511 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
53512   int rc = SQLITE_OK;
53513   assert( p->inTrans!=TRANS_NONE );
53514   if( p->sharable ){
53515     u8 lockType = READ_LOCK + isWriteLock;
53516     assert( READ_LOCK+1==WRITE_LOCK );
53517     assert( isWriteLock==0 || isWriteLock==1 );
53518
53519     sqlite3BtreeEnter(p);
53520     rc = querySharedCacheTableLock(p, iTab, lockType);
53521     if( rc==SQLITE_OK ){
53522       rc = setSharedCacheTableLock(p, iTab, lockType);
53523     }
53524     sqlite3BtreeLeave(p);
53525   }
53526   return rc;
53527 }
53528 #endif
53529
53530 #ifndef SQLITE_OMIT_INCRBLOB
53531 /*
53532 ** Argument pCsr must be a cursor opened for writing on an 
53533 ** INTKEY table currently pointing at a valid table entry. 
53534 ** This function modifies the data stored as part of that entry.
53535 **
53536 ** Only the data content may only be modified, it is not possible to 
53537 ** change the length of the data stored. If this function is called with
53538 ** parameters that attempt to write past the end of the existing data,
53539 ** no modifications are made and SQLITE_CORRUPT is returned.
53540 */
53541 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
53542   int rc;
53543   assert( cursorHoldsMutex(pCsr) );
53544   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
53545   assert( pCsr->isIncrblobHandle );
53546
53547   rc = restoreCursorPosition(pCsr);
53548   if( rc!=SQLITE_OK ){
53549     return rc;
53550   }
53551   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
53552   if( pCsr->eState!=CURSOR_VALID ){
53553     return SQLITE_ABORT;
53554   }
53555
53556   /* Check some assumptions: 
53557   **   (a) the cursor is open for writing,
53558   **   (b) there is a read/write transaction open,
53559   **   (c) the connection holds a write-lock on the table (if required),
53560   **   (d) there are no conflicting read-locks, and
53561   **   (e) the cursor points at a valid row of an intKey table.
53562   */
53563   if( !pCsr->wrFlag ){
53564     return SQLITE_READONLY;
53565   }
53566   assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
53567   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
53568   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
53569   assert( pCsr->apPage[pCsr->iPage]->intKey );
53570
53571   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
53572 }
53573
53574 /* 
53575 ** Set a flag on this cursor to cache the locations of pages from the 
53576 ** overflow list for the current row. This is used by cursors opened
53577 ** for incremental blob IO only.
53578 **
53579 ** This function sets a flag only. The actual page location cache
53580 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
53581 ** accessPayload() (the worker function for sqlite3BtreeData() and
53582 ** sqlite3BtreePutData()).
53583 */
53584 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
53585   assert( cursorHoldsMutex(pCur) );
53586   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
53587   invalidateOverflowCache(pCur);
53588   pCur->isIncrblobHandle = 1;
53589 }
53590 #endif
53591
53592 /*
53593 ** Set both the "read version" (single byte at byte offset 18) and 
53594 ** "write version" (single byte at byte offset 19) fields in the database
53595 ** header to iVersion.
53596 */
53597 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
53598   BtShared *pBt = pBtree->pBt;
53599   int rc;                         /* Return code */
53600  
53601   assert( pBtree->inTrans==TRANS_NONE );
53602   assert( iVersion==1 || iVersion==2 );
53603
53604   /* If setting the version fields to 1, do not automatically open the
53605   ** WAL connection, even if the version fields are currently set to 2.
53606   */
53607   pBt->doNotUseWAL = (u8)(iVersion==1);
53608
53609   rc = sqlite3BtreeBeginTrans(pBtree, 0);
53610   if( rc==SQLITE_OK ){
53611     u8 *aData = pBt->pPage1->aData;
53612     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
53613       rc = sqlite3BtreeBeginTrans(pBtree, 2);
53614       if( rc==SQLITE_OK ){
53615         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
53616         if( rc==SQLITE_OK ){
53617           aData[18] = (u8)iVersion;
53618           aData[19] = (u8)iVersion;
53619         }
53620       }
53621     }
53622   }
53623
53624   pBt->doNotUseWAL = 0;
53625   return rc;
53626 }
53627
53628 /************** End of btree.c ***********************************************/
53629 /************** Begin file backup.c ******************************************/
53630 /*
53631 ** 2009 January 28
53632 **
53633 ** The author disclaims copyright to this source code.  In place of
53634 ** a legal notice, here is a blessing:
53635 **
53636 **    May you do good and not evil.
53637 **    May you find forgiveness for yourself and forgive others.
53638 **    May you share freely, never taking more than you give.
53639 **
53640 *************************************************************************
53641 ** This file contains the implementation of the sqlite3_backup_XXX() 
53642 ** API functions and the related features.
53643 */
53644
53645 /* Macro to find the minimum of two numeric values.
53646 */
53647 #ifndef MIN
53648 # define MIN(x,y) ((x)<(y)?(x):(y))
53649 #endif
53650
53651 /*
53652 ** Structure allocated for each backup operation.
53653 */
53654 struct sqlite3_backup {
53655   sqlite3* pDestDb;        /* Destination database handle */
53656   Btree *pDest;            /* Destination b-tree file */
53657   u32 iDestSchema;         /* Original schema cookie in destination */
53658   int bDestLocked;         /* True once a write-transaction is open on pDest */
53659
53660   Pgno iNext;              /* Page number of the next source page to copy */
53661   sqlite3* pSrcDb;         /* Source database handle */
53662   Btree *pSrc;             /* Source b-tree file */
53663
53664   int rc;                  /* Backup process error code */
53665
53666   /* These two variables are set by every call to backup_step(). They are
53667   ** read by calls to backup_remaining() and backup_pagecount().
53668   */
53669   Pgno nRemaining;         /* Number of pages left to copy */
53670   Pgno nPagecount;         /* Total number of pages to copy */
53671
53672   int isAttached;          /* True once backup has been registered with pager */
53673   sqlite3_backup *pNext;   /* Next backup associated with source pager */
53674 };
53675
53676 /*
53677 ** THREAD SAFETY NOTES:
53678 **
53679 **   Once it has been created using backup_init(), a single sqlite3_backup
53680 **   structure may be accessed via two groups of thread-safe entry points:
53681 **
53682 **     * Via the sqlite3_backup_XXX() API function backup_step() and 
53683 **       backup_finish(). Both these functions obtain the source database
53684 **       handle mutex and the mutex associated with the source BtShared 
53685 **       structure, in that order.
53686 **
53687 **     * Via the BackupUpdate() and BackupRestart() functions, which are
53688 **       invoked by the pager layer to report various state changes in
53689 **       the page cache associated with the source database. The mutex
53690 **       associated with the source database BtShared structure will always 
53691 **       be held when either of these functions are invoked.
53692 **
53693 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
53694 **   backup_pagecount() are not thread-safe functions. If they are called
53695 **   while some other thread is calling backup_step() or backup_finish(),
53696 **   the values returned may be invalid. There is no way for a call to
53697 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
53698 **   or backup_pagecount().
53699 **
53700 **   Depending on the SQLite configuration, the database handles and/or
53701 **   the Btree objects may have their own mutexes that require locking.
53702 **   Non-sharable Btrees (in-memory databases for example), do not have
53703 **   associated mutexes.
53704 */
53705
53706 /*
53707 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
53708 ** in connection handle pDb. If such a database cannot be found, return
53709 ** a NULL pointer and write an error message to pErrorDb.
53710 **
53711 ** If the "temp" database is requested, it may need to be opened by this 
53712 ** function. If an error occurs while doing so, return 0 and write an 
53713 ** error message to pErrorDb.
53714 */
53715 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
53716   int i = sqlite3FindDbName(pDb, zDb);
53717
53718   if( i==1 ){
53719     Parse *pParse;
53720     int rc = 0;
53721     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
53722     if( pParse==0 ){
53723       sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
53724       rc = SQLITE_NOMEM;
53725     }else{
53726       pParse->db = pDb;
53727       if( sqlite3OpenTempDatabase(pParse) ){
53728         sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
53729         rc = SQLITE_ERROR;
53730       }
53731       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
53732       sqlite3StackFree(pErrorDb, pParse);
53733     }
53734     if( rc ){
53735       return 0;
53736     }
53737   }
53738
53739   if( i<0 ){
53740     sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
53741     return 0;
53742   }
53743
53744   return pDb->aDb[i].pBt;
53745 }
53746
53747 /*
53748 ** Attempt to set the page size of the destination to match the page size
53749 ** of the source.
53750 */
53751 static int setDestPgsz(sqlite3_backup *p){
53752   int rc;
53753   rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
53754   return rc;
53755 }
53756
53757 /*
53758 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
53759 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
53760 ** a pointer to the new sqlite3_backup object.
53761 **
53762 ** If an error occurs, NULL is returned and an error code and error message
53763 ** stored in database handle pDestDb.
53764 */
53765 SQLITE_API sqlite3_backup *sqlite3_backup_init(
53766   sqlite3* pDestDb,                     /* Database to write to */
53767   const char *zDestDb,                  /* Name of database within pDestDb */
53768   sqlite3* pSrcDb,                      /* Database connection to read from */
53769   const char *zSrcDb                    /* Name of database within pSrcDb */
53770 ){
53771   sqlite3_backup *p;                    /* Value to return */
53772
53773   /* Lock the source database handle. The destination database
53774   ** handle is not locked in this routine, but it is locked in
53775   ** sqlite3_backup_step(). The user is required to ensure that no
53776   ** other thread accesses the destination handle for the duration
53777   ** of the backup operation.  Any attempt to use the destination
53778   ** database connection while a backup is in progress may cause
53779   ** a malfunction or a deadlock.
53780   */
53781   sqlite3_mutex_enter(pSrcDb->mutex);
53782   sqlite3_mutex_enter(pDestDb->mutex);
53783
53784   if( pSrcDb==pDestDb ){
53785     sqlite3Error(
53786         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
53787     );
53788     p = 0;
53789   }else {
53790     /* Allocate space for a new sqlite3_backup object...
53791     ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
53792     ** call to sqlite3_backup_init() and is destroyed by a call to
53793     ** sqlite3_backup_finish(). */
53794     p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
53795     if( !p ){
53796       sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
53797     }
53798   }
53799
53800   /* If the allocation succeeded, populate the new object. */
53801   if( p ){
53802     memset(p, 0, sizeof(sqlite3_backup));
53803     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
53804     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
53805     p->pDestDb = pDestDb;
53806     p->pSrcDb = pSrcDb;
53807     p->iNext = 1;
53808     p->isAttached = 0;
53809
53810     if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
53811       /* One (or both) of the named databases did not exist or an OOM
53812       ** error was hit.  The error has already been written into the
53813       ** pDestDb handle.  All that is left to do here is free the
53814       ** sqlite3_backup structure.
53815       */
53816       sqlite3_free(p);
53817       p = 0;
53818     }
53819   }
53820   if( p ){
53821     p->pSrc->nBackup++;
53822   }
53823
53824   sqlite3_mutex_leave(pDestDb->mutex);
53825   sqlite3_mutex_leave(pSrcDb->mutex);
53826   return p;
53827 }
53828
53829 /*
53830 ** Argument rc is an SQLite error code. Return true if this error is 
53831 ** considered fatal if encountered during a backup operation. All errors
53832 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
53833 */
53834 static int isFatalError(int rc){
53835   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
53836 }
53837
53838 /*
53839 ** Parameter zSrcData points to a buffer containing the data for 
53840 ** page iSrcPg from the source database. Copy this data into the 
53841 ** destination database.
53842 */
53843 static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
53844   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
53845   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
53846   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
53847   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
53848   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
53849
53850   int rc = SQLITE_OK;
53851   i64 iOff;
53852
53853   assert( p->bDestLocked );
53854   assert( !isFatalError(p->rc) );
53855   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
53856   assert( zSrcData );
53857
53858   /* Catch the case where the destination is an in-memory database and the
53859   ** page sizes of the source and destination differ. 
53860   */
53861   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
53862     rc = SQLITE_READONLY;
53863   }
53864
53865 #ifdef SQLITE_HAS_CODEC
53866   /* Backup is not possible if the page size of the destination is changing
53867   ** a a codec is in use.
53868   */
53869   if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
53870     rc = SQLITE_READONLY;
53871   }
53872 #endif
53873
53874   /* This loop runs once for each destination page spanned by the source 
53875   ** page. For each iteration, variable iOff is set to the byte offset
53876   ** of the destination page.
53877   */
53878   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
53879     DbPage *pDestPg = 0;
53880     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
53881     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
53882     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
53883      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
53884     ){
53885       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
53886       u8 *zDestData = sqlite3PagerGetData(pDestPg);
53887       u8 *zOut = &zDestData[iOff%nDestPgsz];
53888
53889       /* Copy the data from the source page into the destination page.
53890       ** Then clear the Btree layer MemPage.isInit flag. Both this module
53891       ** and the pager code use this trick (clearing the first byte
53892       ** of the page 'extra' space to invalidate the Btree layers
53893       ** cached parse of the page). MemPage.isInit is marked 
53894       ** "MUST BE FIRST" for this purpose.
53895       */
53896       memcpy(zOut, zIn, nCopy);
53897       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
53898     }
53899     sqlite3PagerUnref(pDestPg);
53900   }
53901
53902   return rc;
53903 }
53904
53905 /*
53906 ** If pFile is currently larger than iSize bytes, then truncate it to
53907 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
53908 ** this function is a no-op.
53909 **
53910 ** Return SQLITE_OK if everything is successful, or an SQLite error 
53911 ** code if an error occurs.
53912 */
53913 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
53914   i64 iCurrent;
53915   int rc = sqlite3OsFileSize(pFile, &iCurrent);
53916   if( rc==SQLITE_OK && iCurrent>iSize ){
53917     rc = sqlite3OsTruncate(pFile, iSize);
53918   }
53919   return rc;
53920 }
53921
53922 /*
53923 ** Register this backup object with the associated source pager for
53924 ** callbacks when pages are changed or the cache invalidated.
53925 */
53926 static void attachBackupObject(sqlite3_backup *p){
53927   sqlite3_backup **pp;
53928   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
53929   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
53930   p->pNext = *pp;
53931   *pp = p;
53932   p->isAttached = 1;
53933 }
53934
53935 /*
53936 ** Copy nPage pages from the source b-tree to the destination.
53937 */
53938 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
53939   int rc;
53940   int destMode;       /* Destination journal mode */
53941   int pgszSrc = 0;    /* Source page size */
53942   int pgszDest = 0;   /* Destination page size */
53943
53944   sqlite3_mutex_enter(p->pSrcDb->mutex);
53945   sqlite3BtreeEnter(p->pSrc);
53946   if( p->pDestDb ){
53947     sqlite3_mutex_enter(p->pDestDb->mutex);
53948   }
53949
53950   rc = p->rc;
53951   if( !isFatalError(rc) ){
53952     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
53953     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
53954     int ii;                            /* Iterator variable */
53955     int nSrcPage = -1;                 /* Size of source db in pages */
53956     int bCloseTrans = 0;               /* True if src db requires unlocking */
53957
53958     /* If the source pager is currently in a write-transaction, return
53959     ** SQLITE_BUSY immediately.
53960     */
53961     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
53962       rc = SQLITE_BUSY;
53963     }else{
53964       rc = SQLITE_OK;
53965     }
53966
53967     /* Lock the destination database, if it is not locked already. */
53968     if( SQLITE_OK==rc && p->bDestLocked==0
53969      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) 
53970     ){
53971       p->bDestLocked = 1;
53972       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
53973     }
53974
53975     /* If there is no open read-transaction on the source database, open
53976     ** one now. If a transaction is opened here, then it will be closed
53977     ** before this function exits.
53978     */
53979     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
53980       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
53981       bCloseTrans = 1;
53982     }
53983
53984     /* Do not allow backup if the destination database is in WAL mode
53985     ** and the page sizes are different between source and destination */
53986     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
53987     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
53988     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
53989     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
53990       rc = SQLITE_READONLY;
53991     }
53992   
53993     /* Now that there is a read-lock on the source database, query the
53994     ** source pager for the number of pages in the database.
53995     */
53996     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
53997     assert( nSrcPage>=0 );
53998     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
53999       const Pgno iSrcPg = p->iNext;                 /* Source page number */
54000       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
54001         DbPage *pSrcPg;                             /* Source page object */
54002         rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
54003         if( rc==SQLITE_OK ){
54004           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
54005           sqlite3PagerUnref(pSrcPg);
54006         }
54007       }
54008       p->iNext++;
54009     }
54010     if( rc==SQLITE_OK ){
54011       p->nPagecount = nSrcPage;
54012       p->nRemaining = nSrcPage+1-p->iNext;
54013       if( p->iNext>(Pgno)nSrcPage ){
54014         rc = SQLITE_DONE;
54015       }else if( !p->isAttached ){
54016         attachBackupObject(p);
54017       }
54018     }
54019   
54020     /* Update the schema version field in the destination database. This
54021     ** is to make sure that the schema-version really does change in
54022     ** the case where the source and destination databases have the
54023     ** same schema version.
54024     */
54025     if( rc==SQLITE_DONE 
54026      && (rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1))==SQLITE_OK
54027     ){
54028       int nDestTruncate;
54029   
54030       if( p->pDestDb ){
54031         sqlite3ResetInternalSchema(p->pDestDb, 0);
54032       }
54033
54034       /* Set nDestTruncate to the final number of pages in the destination
54035       ** database. The complication here is that the destination page
54036       ** size may be different to the source page size. 
54037       **
54038       ** If the source page size is smaller than the destination page size, 
54039       ** round up. In this case the call to sqlite3OsTruncate() below will
54040       ** fix the size of the file. However it is important to call
54041       ** sqlite3PagerTruncateImage() here so that any pages in the 
54042       ** destination file that lie beyond the nDestTruncate page mark are
54043       ** journalled by PagerCommitPhaseOne() before they are destroyed
54044       ** by the file truncation.
54045       */
54046       assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
54047       assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
54048       if( pgszSrc<pgszDest ){
54049         int ratio = pgszDest/pgszSrc;
54050         nDestTruncate = (nSrcPage+ratio-1)/ratio;
54051         if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
54052           nDestTruncate--;
54053         }
54054       }else{
54055         nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
54056       }
54057       sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
54058
54059       if( pgszSrc<pgszDest ){
54060         /* If the source page-size is smaller than the destination page-size,
54061         ** two extra things may need to happen:
54062         **
54063         **   * The destination may need to be truncated, and
54064         **
54065         **   * Data stored on the pages immediately following the 
54066         **     pending-byte page in the source database may need to be
54067         **     copied into the destination database.
54068         */
54069         const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
54070         sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
54071         i64 iOff;
54072         i64 iEnd;
54073
54074         assert( pFile );
54075         assert( (i64)nDestTruncate*(i64)pgszDest >= iSize || (
54076               nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
54077            && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
54078         ));
54079
54080         /* This call ensures that all data required to recreate the original
54081         ** database has been stored in the journal for pDestPager and the
54082         ** journal synced to disk. So at this point we may safely modify
54083         ** the database file in any way, knowing that if a power failure
54084         ** occurs, the original database will be reconstructed from the 
54085         ** journal file.  */
54086         rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
54087
54088         /* Write the extra pages and truncate the database file as required. */
54089         iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
54090         for(
54091           iOff=PENDING_BYTE+pgszSrc; 
54092           rc==SQLITE_OK && iOff<iEnd; 
54093           iOff+=pgszSrc
54094         ){
54095           PgHdr *pSrcPg = 0;
54096           const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
54097           rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
54098           if( rc==SQLITE_OK ){
54099             u8 *zData = sqlite3PagerGetData(pSrcPg);
54100             rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
54101           }
54102           sqlite3PagerUnref(pSrcPg);
54103         }
54104         if( rc==SQLITE_OK ){
54105           rc = backupTruncateFile(pFile, iSize);
54106         }
54107
54108         /* Sync the database file to disk. */
54109         if( rc==SQLITE_OK ){
54110           rc = sqlite3PagerSync(pDestPager);
54111         }
54112       }else{
54113         rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
54114       }
54115   
54116       /* Finish committing the transaction to the destination database. */
54117       if( SQLITE_OK==rc
54118        && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest))
54119       ){
54120         rc = SQLITE_DONE;
54121       }
54122     }
54123   
54124     /* If bCloseTrans is true, then this function opened a read transaction
54125     ** on the source database. Close the read transaction here. There is
54126     ** no need to check the return values of the btree methods here, as
54127     ** "committing" a read-only transaction cannot fail.
54128     */
54129     if( bCloseTrans ){
54130       TESTONLY( int rc2 );
54131       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
54132       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc);
54133       assert( rc2==SQLITE_OK );
54134     }
54135   
54136     if( rc==SQLITE_IOERR_NOMEM ){
54137       rc = SQLITE_NOMEM;
54138     }
54139     p->rc = rc;
54140   }
54141   if( p->pDestDb ){
54142     sqlite3_mutex_leave(p->pDestDb->mutex);
54143   }
54144   sqlite3BtreeLeave(p->pSrc);
54145   sqlite3_mutex_leave(p->pSrcDb->mutex);
54146   return rc;
54147 }
54148
54149 /*
54150 ** Release all resources associated with an sqlite3_backup* handle.
54151 */
54152 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
54153   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
54154   sqlite3_mutex *mutex;                /* Mutex to protect source database */
54155   int rc;                              /* Value to return */
54156
54157   /* Enter the mutexes */
54158   if( p==0 ) return SQLITE_OK;
54159   sqlite3_mutex_enter(p->pSrcDb->mutex);
54160   sqlite3BtreeEnter(p->pSrc);
54161   mutex = p->pSrcDb->mutex;
54162   if( p->pDestDb ){
54163     sqlite3_mutex_enter(p->pDestDb->mutex);
54164   }
54165
54166   /* Detach this backup from the source pager. */
54167   if( p->pDestDb ){
54168     p->pSrc->nBackup--;
54169   }
54170   if( p->isAttached ){
54171     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
54172     while( *pp!=p ){
54173       pp = &(*pp)->pNext;
54174     }
54175     *pp = p->pNext;
54176   }
54177
54178   /* If a transaction is still open on the Btree, roll it back. */
54179   sqlite3BtreeRollback(p->pDest);
54180
54181   /* Set the error code of the destination database handle. */
54182   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
54183   sqlite3Error(p->pDestDb, rc, 0);
54184
54185   /* Exit the mutexes and free the backup context structure. */
54186   if( p->pDestDb ){
54187     sqlite3_mutex_leave(p->pDestDb->mutex);
54188   }
54189   sqlite3BtreeLeave(p->pSrc);
54190   if( p->pDestDb ){
54191     /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
54192     ** call to sqlite3_backup_init() and is destroyed by a call to
54193     ** sqlite3_backup_finish(). */
54194     sqlite3_free(p);
54195   }
54196   sqlite3_mutex_leave(mutex);
54197   return rc;
54198 }
54199
54200 /*
54201 ** Return the number of pages still to be backed up as of the most recent
54202 ** call to sqlite3_backup_step().
54203 */
54204 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
54205   return p->nRemaining;
54206 }
54207
54208 /*
54209 ** Return the total number of pages in the source database as of the most 
54210 ** recent call to sqlite3_backup_step().
54211 */
54212 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
54213   return p->nPagecount;
54214 }
54215
54216 /*
54217 ** This function is called after the contents of page iPage of the
54218 ** source database have been modified. If page iPage has already been 
54219 ** copied into the destination database, then the data written to the
54220 ** destination is now invalidated. The destination copy of iPage needs
54221 ** to be updated with the new data before the backup operation is
54222 ** complete.
54223 **
54224 ** It is assumed that the mutex associated with the BtShared object
54225 ** corresponding to the source database is held when this function is
54226 ** called.
54227 */
54228 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
54229   sqlite3_backup *p;                   /* Iterator variable */
54230   for(p=pBackup; p; p=p->pNext){
54231     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
54232     if( !isFatalError(p->rc) && iPage<p->iNext ){
54233       /* The backup process p has already copied page iPage. But now it
54234       ** has been modified by a transaction on the source pager. Copy
54235       ** the new data into the backup.
54236       */
54237       int rc = backupOnePage(p, iPage, aData);
54238       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
54239       if( rc!=SQLITE_OK ){
54240         p->rc = rc;
54241       }
54242     }
54243   }
54244 }
54245
54246 /*
54247 ** Restart the backup process. This is called when the pager layer
54248 ** detects that the database has been modified by an external database
54249 ** connection. In this case there is no way of knowing which of the
54250 ** pages that have been copied into the destination database are still 
54251 ** valid and which are not, so the entire process needs to be restarted.
54252 **
54253 ** It is assumed that the mutex associated with the BtShared object
54254 ** corresponding to the source database is held when this function is
54255 ** called.
54256 */
54257 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
54258   sqlite3_backup *p;                   /* Iterator variable */
54259   for(p=pBackup; p; p=p->pNext){
54260     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
54261     p->iNext = 1;
54262   }
54263 }
54264
54265 #ifndef SQLITE_OMIT_VACUUM
54266 /*
54267 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
54268 ** must be active for both files.
54269 **
54270 ** The size of file pTo may be reduced by this operation. If anything 
54271 ** goes wrong, the transaction on pTo is rolled back. If successful, the 
54272 ** transaction is committed before returning.
54273 */
54274 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
54275   int rc;
54276   sqlite3_backup b;
54277   sqlite3BtreeEnter(pTo);
54278   sqlite3BtreeEnter(pFrom);
54279
54280   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
54281   ** to 0. This is used by the implementations of sqlite3_backup_step()
54282   ** and sqlite3_backup_finish() to detect that they are being called
54283   ** from this function, not directly by the user.
54284   */
54285   memset(&b, 0, sizeof(b));
54286   b.pSrcDb = pFrom->db;
54287   b.pSrc = pFrom;
54288   b.pDest = pTo;
54289   b.iNext = 1;
54290
54291   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
54292   ** file. By passing this as the number of pages to copy to
54293   ** sqlite3_backup_step(), we can guarantee that the copy finishes 
54294   ** within a single call (unless an error occurs). The assert() statement
54295   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE 
54296   ** or an error code.
54297   */
54298   sqlite3_backup_step(&b, 0x7FFFFFFF);
54299   assert( b.rc!=SQLITE_OK );
54300   rc = sqlite3_backup_finish(&b);
54301   if( rc==SQLITE_OK ){
54302     pTo->pBt->pageSizeFixed = 0;
54303   }
54304
54305   sqlite3BtreeLeave(pFrom);
54306   sqlite3BtreeLeave(pTo);
54307   return rc;
54308 }
54309 #endif /* SQLITE_OMIT_VACUUM */
54310
54311 /************** End of backup.c **********************************************/
54312 /************** Begin file vdbemem.c *****************************************/
54313 /*
54314 ** 2004 May 26
54315 **
54316 ** The author disclaims copyright to this source code.  In place of
54317 ** a legal notice, here is a blessing:
54318 **
54319 **    May you do good and not evil.
54320 **    May you find forgiveness for yourself and forgive others.
54321 **    May you share freely, never taking more than you give.
54322 **
54323 *************************************************************************
54324 **
54325 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
54326 ** stores a single value in the VDBE.  Mem is an opaque structure visible
54327 ** only within the VDBE.  Interface routines refer to a Mem using the
54328 ** name sqlite_value
54329 */
54330
54331 /*
54332 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
54333 ** P if required.
54334 */
54335 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
54336
54337 /*
54338 ** If pMem is an object with a valid string representation, this routine
54339 ** ensures the internal encoding for the string representation is
54340 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
54341 **
54342 ** If pMem is not a string object, or the encoding of the string
54343 ** representation is already stored using the requested encoding, then this
54344 ** routine is a no-op.
54345 **
54346 ** SQLITE_OK is returned if the conversion is successful (or not required).
54347 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
54348 ** between formats.
54349 */
54350 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
54351   int rc;
54352   assert( (pMem->flags&MEM_RowSet)==0 );
54353   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
54354            || desiredEnc==SQLITE_UTF16BE );
54355   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
54356     return SQLITE_OK;
54357   }
54358   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54359 #ifdef SQLITE_OMIT_UTF16
54360   return SQLITE_ERROR;
54361 #else
54362
54363   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
54364   ** then the encoding of the value may not have changed.
54365   */
54366   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
54367   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
54368   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
54369   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
54370   return rc;
54371 #endif
54372 }
54373
54374 /*
54375 ** Make sure pMem->z points to a writable allocation of at least 
54376 ** n bytes.
54377 **
54378 ** If the memory cell currently contains string or blob data
54379 ** and the third argument passed to this function is true, the 
54380 ** current content of the cell is preserved. Otherwise, it may
54381 ** be discarded.  
54382 **
54383 ** This function sets the MEM_Dyn flag and clears any xDel callback.
54384 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is 
54385 ** not set, Mem.n is zeroed.
54386 */
54387 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
54388   assert( 1 >=
54389     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
54390     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + 
54391     ((pMem->flags&MEM_Ephem) ? 1 : 0) + 
54392     ((pMem->flags&MEM_Static) ? 1 : 0)
54393   );
54394   assert( (pMem->flags&MEM_RowSet)==0 );
54395
54396   if( n<32 ) n = 32;
54397   if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
54398     if( preserve && pMem->z==pMem->zMalloc ){
54399       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
54400       preserve = 0;
54401     }else{
54402       sqlite3DbFree(pMem->db, pMem->zMalloc);
54403       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
54404     }
54405   }
54406
54407   if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
54408     memcpy(pMem->zMalloc, pMem->z, pMem->n);
54409   }
54410   if( pMem->flags&MEM_Dyn && pMem->xDel ){
54411     pMem->xDel((void *)(pMem->z));
54412   }
54413
54414   pMem->z = pMem->zMalloc;
54415   if( pMem->z==0 ){
54416     pMem->flags = MEM_Null;
54417   }else{
54418     pMem->flags &= ~(MEM_Ephem|MEM_Static);
54419   }
54420   pMem->xDel = 0;
54421   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
54422 }
54423
54424 /*
54425 ** Make the given Mem object MEM_Dyn.  In other words, make it so
54426 ** that any TEXT or BLOB content is stored in memory obtained from
54427 ** malloc().  In this way, we know that the memory is safe to be
54428 ** overwritten or altered.
54429 **
54430 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
54431 */
54432 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
54433   int f;
54434   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54435   assert( (pMem->flags&MEM_RowSet)==0 );
54436   expandBlob(pMem);
54437   f = pMem->flags;
54438   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
54439     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
54440       return SQLITE_NOMEM;
54441     }
54442     pMem->z[pMem->n] = 0;
54443     pMem->z[pMem->n+1] = 0;
54444     pMem->flags |= MEM_Term;
54445 #ifdef SQLITE_DEBUG
54446     pMem->pScopyFrom = 0;
54447 #endif
54448   }
54449
54450   return SQLITE_OK;
54451 }
54452
54453 /*
54454 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
54455 ** blob stored in dynamically allocated space.
54456 */
54457 #ifndef SQLITE_OMIT_INCRBLOB
54458 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
54459   if( pMem->flags & MEM_Zero ){
54460     int nByte;
54461     assert( pMem->flags&MEM_Blob );
54462     assert( (pMem->flags&MEM_RowSet)==0 );
54463     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54464
54465     /* Set nByte to the number of bytes required to store the expanded blob. */
54466     nByte = pMem->n + pMem->u.nZero;
54467     if( nByte<=0 ){
54468       nByte = 1;
54469     }
54470     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
54471       return SQLITE_NOMEM;
54472     }
54473
54474     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
54475     pMem->n += pMem->u.nZero;
54476     pMem->flags &= ~(MEM_Zero|MEM_Term);
54477   }
54478   return SQLITE_OK;
54479 }
54480 #endif
54481
54482
54483 /*
54484 ** Make sure the given Mem is \u0000 terminated.
54485 */
54486 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
54487   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54488   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
54489     return SQLITE_OK;   /* Nothing to do */
54490   }
54491   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
54492     return SQLITE_NOMEM;
54493   }
54494   pMem->z[pMem->n] = 0;
54495   pMem->z[pMem->n+1] = 0;
54496   pMem->flags |= MEM_Term;
54497   return SQLITE_OK;
54498 }
54499
54500 /*
54501 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
54502 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
54503 ** is a no-op.
54504 **
54505 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
54506 **
54507 ** A MEM_Null value will never be passed to this function. This function is
54508 ** used for converting values to text for returning to the user (i.e. via
54509 ** sqlite3_value_text()), or for ensuring that values to be used as btree
54510 ** keys are strings. In the former case a NULL pointer is returned the
54511 ** user and the later is an internal programming error.
54512 */
54513 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
54514   int rc = SQLITE_OK;
54515   int fg = pMem->flags;
54516   const int nByte = 32;
54517
54518   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54519   assert( !(fg&MEM_Zero) );
54520   assert( !(fg&(MEM_Str|MEM_Blob)) );
54521   assert( fg&(MEM_Int|MEM_Real) );
54522   assert( (pMem->flags&MEM_RowSet)==0 );
54523   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
54524
54525
54526   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
54527     return SQLITE_NOMEM;
54528   }
54529
54530   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
54531   ** string representation of the value. Then, if the required encoding
54532   ** is UTF-16le or UTF-16be do a translation.
54533   ** 
54534   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
54535   */
54536   if( fg & MEM_Int ){
54537     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
54538   }else{
54539     assert( fg & MEM_Real );
54540     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
54541   }
54542   pMem->n = sqlite3Strlen30(pMem->z);
54543   pMem->enc = SQLITE_UTF8;
54544   pMem->flags |= MEM_Str|MEM_Term;
54545   sqlite3VdbeChangeEncoding(pMem, enc);
54546   return rc;
54547 }
54548
54549 /*
54550 ** Memory cell pMem contains the context of an aggregate function.
54551 ** This routine calls the finalize method for that function.  The
54552 ** result of the aggregate is stored back into pMem.
54553 **
54554 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
54555 ** otherwise.
54556 */
54557 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
54558   int rc = SQLITE_OK;
54559   if( ALWAYS(pFunc && pFunc->xFinalize) ){
54560     sqlite3_context ctx;
54561     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
54562     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54563     memset(&ctx, 0, sizeof(ctx));
54564     ctx.s.flags = MEM_Null;
54565     ctx.s.db = pMem->db;
54566     ctx.pMem = pMem;
54567     ctx.pFunc = pFunc;
54568     pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
54569     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
54570     sqlite3DbFree(pMem->db, pMem->zMalloc);
54571     memcpy(pMem, &ctx.s, sizeof(ctx.s));
54572     rc = ctx.isError;
54573   }
54574   return rc;
54575 }
54576
54577 /*
54578 ** If the memory cell contains a string value that must be freed by
54579 ** invoking an external callback, free it now. Calling this function
54580 ** does not free any Mem.zMalloc buffer.
54581 */
54582 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
54583   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
54584   testcase( p->flags & MEM_Agg );
54585   testcase( p->flags & MEM_Dyn );
54586   testcase( p->flags & MEM_RowSet );
54587   testcase( p->flags & MEM_Frame );
54588   if( p->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame) ){
54589     if( p->flags&MEM_Agg ){
54590       sqlite3VdbeMemFinalize(p, p->u.pDef);
54591       assert( (p->flags & MEM_Agg)==0 );
54592       sqlite3VdbeMemRelease(p);
54593     }else if( p->flags&MEM_Dyn && p->xDel ){
54594       assert( (p->flags&MEM_RowSet)==0 );
54595       p->xDel((void *)p->z);
54596       p->xDel = 0;
54597     }else if( p->flags&MEM_RowSet ){
54598       sqlite3RowSetClear(p->u.pRowSet);
54599     }else if( p->flags&MEM_Frame ){
54600       sqlite3VdbeMemSetNull(p);
54601     }
54602   }
54603 }
54604
54605 /*
54606 ** Release any memory held by the Mem. This may leave the Mem in an
54607 ** inconsistent state, for example with (Mem.z==0) and
54608 ** (Mem.type==SQLITE_TEXT).
54609 */
54610 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
54611   sqlite3VdbeMemReleaseExternal(p);
54612   sqlite3DbFree(p->db, p->zMalloc);
54613   p->z = 0;
54614   p->zMalloc = 0;
54615   p->xDel = 0;
54616 }
54617
54618 /*
54619 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
54620 ** If the double is too large, return 0x8000000000000000.
54621 **
54622 ** Most systems appear to do this simply by assigning
54623 ** variables and without the extra range tests.  But
54624 ** there are reports that windows throws an expection
54625 ** if the floating point value is out of range. (See ticket #2880.)
54626 ** Because we do not completely understand the problem, we will
54627 ** take the conservative approach and always do range tests
54628 ** before attempting the conversion.
54629 */
54630 static i64 doubleToInt64(double r){
54631 #ifdef SQLITE_OMIT_FLOATING_POINT
54632   /* When floating-point is omitted, double and int64 are the same thing */
54633   return r;
54634 #else
54635   /*
54636   ** Many compilers we encounter do not define constants for the
54637   ** minimum and maximum 64-bit integers, or they define them
54638   ** inconsistently.  And many do not understand the "LL" notation.
54639   ** So we define our own static constants here using nothing
54640   ** larger than a 32-bit integer constant.
54641   */
54642   static const i64 maxInt = LARGEST_INT64;
54643   static const i64 minInt = SMALLEST_INT64;
54644
54645   if( r<(double)minInt ){
54646     return minInt;
54647   }else if( r>(double)maxInt ){
54648     /* minInt is correct here - not maxInt.  It turns out that assigning
54649     ** a very large positive number to an integer results in a very large
54650     ** negative integer.  This makes no sense, but it is what x86 hardware
54651     ** does so for compatibility we will do the same in software. */
54652     return minInt;
54653   }else{
54654     return (i64)r;
54655   }
54656 #endif
54657 }
54658
54659 /*
54660 ** Return some kind of integer value which is the best we can do
54661 ** at representing the value that *pMem describes as an integer.
54662 ** If pMem is an integer, then the value is exact.  If pMem is
54663 ** a floating-point then the value returned is the integer part.
54664 ** If pMem is a string or blob, then we make an attempt to convert
54665 ** it into a integer and return that.  If pMem represents an
54666 ** an SQL-NULL value, return 0.
54667 **
54668 ** If pMem represents a string value, its encoding might be changed.
54669 */
54670 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
54671   int flags;
54672   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54673   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
54674   flags = pMem->flags;
54675   if( flags & MEM_Int ){
54676     return pMem->u.i;
54677   }else if( flags & MEM_Real ){
54678     return doubleToInt64(pMem->r);
54679   }else if( flags & (MEM_Str|MEM_Blob) ){
54680     i64 value;
54681     assert( pMem->z || pMem->n==0 );
54682     testcase( pMem->z==0 );
54683     sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
54684     return value;
54685   }else{
54686     return 0;
54687   }
54688 }
54689
54690 /*
54691 ** Return the best representation of pMem that we can get into a
54692 ** double.  If pMem is already a double or an integer, return its
54693 ** value.  If it is a string or blob, try to convert it to a double.
54694 ** If it is a NULL, return 0.0.
54695 */
54696 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
54697   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54698   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
54699   if( pMem->flags & MEM_Real ){
54700     return pMem->r;
54701   }else if( pMem->flags & MEM_Int ){
54702     return (double)pMem->u.i;
54703   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
54704     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
54705     double val = (double)0;
54706     sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
54707     return val;
54708   }else{
54709     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
54710     return (double)0;
54711   }
54712 }
54713
54714 /*
54715 ** The MEM structure is already a MEM_Real.  Try to also make it a
54716 ** MEM_Int if we can.
54717 */
54718 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
54719   assert( pMem->flags & MEM_Real );
54720   assert( (pMem->flags & MEM_RowSet)==0 );
54721   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54722   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
54723
54724   pMem->u.i = doubleToInt64(pMem->r);
54725
54726   /* Only mark the value as an integer if
54727   **
54728   **    (1) the round-trip conversion real->int->real is a no-op, and
54729   **    (2) The integer is neither the largest nor the smallest
54730   **        possible integer (ticket #3922)
54731   **
54732   ** The second and third terms in the following conditional enforces
54733   ** the second condition under the assumption that addition overflow causes
54734   ** values to wrap around.  On x86 hardware, the third term is always
54735   ** true and could be omitted.  But we leave it in because other
54736   ** architectures might behave differently.
54737   */
54738   if( pMem->r==(double)pMem->u.i && pMem->u.i>SMALLEST_INT64
54739       && ALWAYS(pMem->u.i<LARGEST_INT64) ){
54740     pMem->flags |= MEM_Int;
54741   }
54742 }
54743
54744 /*
54745 ** Convert pMem to type integer.  Invalidate any prior representations.
54746 */
54747 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
54748   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54749   assert( (pMem->flags & MEM_RowSet)==0 );
54750   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
54751
54752   pMem->u.i = sqlite3VdbeIntValue(pMem);
54753   MemSetTypeFlag(pMem, MEM_Int);
54754   return SQLITE_OK;
54755 }
54756
54757 /*
54758 ** Convert pMem so that it is of type MEM_Real.
54759 ** Invalidate any prior representations.
54760 */
54761 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
54762   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54763   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
54764
54765   pMem->r = sqlite3VdbeRealValue(pMem);
54766   MemSetTypeFlag(pMem, MEM_Real);
54767   return SQLITE_OK;
54768 }
54769
54770 /*
54771 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
54772 ** Invalidate any prior representations.
54773 **
54774 ** Every effort is made to force the conversion, even if the input
54775 ** is a string that does not look completely like a number.  Convert
54776 ** as much of the string as we can and ignore the rest.
54777 */
54778 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
54779   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
54780     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
54781     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54782     if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
54783       MemSetTypeFlag(pMem, MEM_Int);
54784     }else{
54785       pMem->r = sqlite3VdbeRealValue(pMem);
54786       MemSetTypeFlag(pMem, MEM_Real);
54787       sqlite3VdbeIntegerAffinity(pMem);
54788     }
54789   }
54790   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
54791   pMem->flags &= ~(MEM_Str|MEM_Blob);
54792   return SQLITE_OK;
54793 }
54794
54795 /*
54796 ** Delete any previous value and set the value stored in *pMem to NULL.
54797 */
54798 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
54799   if( pMem->flags & MEM_Frame ){
54800     VdbeFrame *pFrame = pMem->u.pFrame;
54801     pFrame->pParent = pFrame->v->pDelFrame;
54802     pFrame->v->pDelFrame = pFrame;
54803   }
54804   if( pMem->flags & MEM_RowSet ){
54805     sqlite3RowSetClear(pMem->u.pRowSet);
54806   }
54807   MemSetTypeFlag(pMem, MEM_Null);
54808   pMem->type = SQLITE_NULL;
54809 }
54810
54811 /*
54812 ** Delete any previous value and set the value to be a BLOB of length
54813 ** n containing all zeros.
54814 */
54815 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
54816   sqlite3VdbeMemRelease(pMem);
54817   pMem->flags = MEM_Blob|MEM_Zero;
54818   pMem->type = SQLITE_BLOB;
54819   pMem->n = 0;
54820   if( n<0 ) n = 0;
54821   pMem->u.nZero = n;
54822   pMem->enc = SQLITE_UTF8;
54823
54824 #ifdef SQLITE_OMIT_INCRBLOB
54825   sqlite3VdbeMemGrow(pMem, n, 0);
54826   if( pMem->z ){
54827     pMem->n = n;
54828     memset(pMem->z, 0, n);
54829   }
54830 #endif
54831 }
54832
54833 /*
54834 ** Delete any previous value and set the value stored in *pMem to val,
54835 ** manifest type INTEGER.
54836 */
54837 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
54838   sqlite3VdbeMemRelease(pMem);
54839   pMem->u.i = val;
54840   pMem->flags = MEM_Int;
54841   pMem->type = SQLITE_INTEGER;
54842 }
54843
54844 #ifndef SQLITE_OMIT_FLOATING_POINT
54845 /*
54846 ** Delete any previous value and set the value stored in *pMem to val,
54847 ** manifest type REAL.
54848 */
54849 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
54850   if( sqlite3IsNaN(val) ){
54851     sqlite3VdbeMemSetNull(pMem);
54852   }else{
54853     sqlite3VdbeMemRelease(pMem);
54854     pMem->r = val;
54855     pMem->flags = MEM_Real;
54856     pMem->type = SQLITE_FLOAT;
54857   }
54858 }
54859 #endif
54860
54861 /*
54862 ** Delete any previous value and set the value of pMem to be an
54863 ** empty boolean index.
54864 */
54865 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
54866   sqlite3 *db = pMem->db;
54867   assert( db!=0 );
54868   assert( (pMem->flags & MEM_RowSet)==0 );
54869   sqlite3VdbeMemRelease(pMem);
54870   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
54871   if( db->mallocFailed ){
54872     pMem->flags = MEM_Null;
54873   }else{
54874     assert( pMem->zMalloc );
54875     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, 
54876                                        sqlite3DbMallocSize(db, pMem->zMalloc));
54877     assert( pMem->u.pRowSet!=0 );
54878     pMem->flags = MEM_RowSet;
54879   }
54880 }
54881
54882 /*
54883 ** Return true if the Mem object contains a TEXT or BLOB that is
54884 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
54885 */
54886 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
54887   assert( p->db!=0 );
54888   if( p->flags & (MEM_Str|MEM_Blob) ){
54889     int n = p->n;
54890     if( p->flags & MEM_Zero ){
54891       n += p->u.nZero;
54892     }
54893     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
54894   }
54895   return 0; 
54896 }
54897
54898 #ifdef SQLITE_DEBUG
54899 /*
54900 ** This routine prepares a memory cell for modication by breaking
54901 ** its link to a shallow copy and by marking any current shallow
54902 ** copies of this cell as invalid.
54903 **
54904 ** This is used for testing and debugging only - to make sure shallow
54905 ** copies are not misused.
54906 */
54907 SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe *pVdbe, Mem *pMem){
54908   int i;
54909   Mem *pX;
54910   for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
54911     if( pX->pScopyFrom==pMem ){
54912       pX->flags |= MEM_Invalid;
54913       pX->pScopyFrom = 0;
54914     }
54915   }
54916   pMem->pScopyFrom = 0;
54917 }
54918 #endif /* SQLITE_DEBUG */
54919
54920 /*
54921 ** Size of struct Mem not including the Mem.zMalloc member.
54922 */
54923 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
54924
54925 /*
54926 ** Make an shallow copy of pFrom into pTo.  Prior contents of
54927 ** pTo are freed.  The pFrom->z field is not duplicated.  If
54928 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
54929 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
54930 */
54931 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
54932   assert( (pFrom->flags & MEM_RowSet)==0 );
54933   sqlite3VdbeMemReleaseExternal(pTo);
54934   memcpy(pTo, pFrom, MEMCELLSIZE);
54935   pTo->xDel = 0;
54936   if( (pFrom->flags&MEM_Static)==0 ){
54937     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
54938     assert( srcType==MEM_Ephem || srcType==MEM_Static );
54939     pTo->flags |= srcType;
54940   }
54941 }
54942
54943 /*
54944 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
54945 ** freed before the copy is made.
54946 */
54947 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
54948   int rc = SQLITE_OK;
54949
54950   assert( (pFrom->flags & MEM_RowSet)==0 );
54951   sqlite3VdbeMemReleaseExternal(pTo);
54952   memcpy(pTo, pFrom, MEMCELLSIZE);
54953   pTo->flags &= ~MEM_Dyn;
54954
54955   if( pTo->flags&(MEM_Str|MEM_Blob) ){
54956     if( 0==(pFrom->flags&MEM_Static) ){
54957       pTo->flags |= MEM_Ephem;
54958       rc = sqlite3VdbeMemMakeWriteable(pTo);
54959     }
54960   }
54961
54962   return rc;
54963 }
54964
54965 /*
54966 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
54967 ** freed. If pFrom contains ephemeral data, a copy is made.
54968 **
54969 ** pFrom contains an SQL NULL when this routine returns.
54970 */
54971 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
54972   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
54973   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
54974   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
54975
54976   sqlite3VdbeMemRelease(pTo);
54977   memcpy(pTo, pFrom, sizeof(Mem));
54978   pFrom->flags = MEM_Null;
54979   pFrom->xDel = 0;
54980   pFrom->zMalloc = 0;
54981 }
54982
54983 /*
54984 ** Change the value of a Mem to be a string or a BLOB.
54985 **
54986 ** The memory management strategy depends on the value of the xDel
54987 ** parameter. If the value passed is SQLITE_TRANSIENT, then the 
54988 ** string is copied into a (possibly existing) buffer managed by the 
54989 ** Mem structure. Otherwise, any existing buffer is freed and the
54990 ** pointer copied.
54991 **
54992 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
54993 ** size limit) then no memory allocation occurs.  If the string can be
54994 ** stored without allocating memory, then it is.  If a memory allocation
54995 ** is required to store the string, then value of pMem is unchanged.  In
54996 ** either case, SQLITE_TOOBIG is returned.
54997 */
54998 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
54999   Mem *pMem,          /* Memory cell to set to string value */
55000   const char *z,      /* String pointer */
55001   int n,              /* Bytes in string, or negative */
55002   u8 enc,             /* Encoding of z.  0 for BLOBs */
55003   void (*xDel)(void*) /* Destructor function */
55004 ){
55005   int nByte = n;      /* New value for pMem->n */
55006   int iLimit;         /* Maximum allowed string or blob size */
55007   u16 flags = 0;      /* New value for pMem->flags */
55008
55009   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
55010   assert( (pMem->flags & MEM_RowSet)==0 );
55011
55012   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
55013   if( !z ){
55014     sqlite3VdbeMemSetNull(pMem);
55015     return SQLITE_OK;
55016   }
55017
55018   if( pMem->db ){
55019     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
55020   }else{
55021     iLimit = SQLITE_MAX_LENGTH;
55022   }
55023   flags = (enc==0?MEM_Blob:MEM_Str);
55024   if( nByte<0 ){
55025     assert( enc!=0 );
55026     if( enc==SQLITE_UTF8 ){
55027       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
55028     }else{
55029       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
55030     }
55031     flags |= MEM_Term;
55032   }
55033
55034   /* The following block sets the new values of Mem.z and Mem.xDel. It
55035   ** also sets a flag in local variable "flags" to indicate the memory
55036   ** management (one of MEM_Dyn or MEM_Static).
55037   */
55038   if( xDel==SQLITE_TRANSIENT ){
55039     int nAlloc = nByte;
55040     if( flags&MEM_Term ){
55041       nAlloc += (enc==SQLITE_UTF8?1:2);
55042     }
55043     if( nByte>iLimit ){
55044       return SQLITE_TOOBIG;
55045     }
55046     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
55047       return SQLITE_NOMEM;
55048     }
55049     memcpy(pMem->z, z, nAlloc);
55050   }else if( xDel==SQLITE_DYNAMIC ){
55051     sqlite3VdbeMemRelease(pMem);
55052     pMem->zMalloc = pMem->z = (char *)z;
55053     pMem->xDel = 0;
55054   }else{
55055     sqlite3VdbeMemRelease(pMem);
55056     pMem->z = (char *)z;
55057     pMem->xDel = xDel;
55058     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
55059   }
55060
55061   pMem->n = nByte;
55062   pMem->flags = flags;
55063   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
55064   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
55065
55066 #ifndef SQLITE_OMIT_UTF16
55067   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
55068     return SQLITE_NOMEM;
55069   }
55070 #endif
55071
55072   if( nByte>iLimit ){
55073     return SQLITE_TOOBIG;
55074   }
55075
55076   return SQLITE_OK;
55077 }
55078
55079 /*
55080 ** Compare the values contained by the two memory cells, returning
55081 ** negative, zero or positive if pMem1 is less than, equal to, or greater
55082 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
55083 ** and reals) sorted numerically, followed by text ordered by the collating
55084 ** sequence pColl and finally blob's ordered by memcmp().
55085 **
55086 ** Two NULL values are considered equal by this function.
55087 */
55088 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
55089   int rc;
55090   int f1, f2;
55091   int combined_flags;
55092
55093   f1 = pMem1->flags;
55094   f2 = pMem2->flags;
55095   combined_flags = f1|f2;
55096   assert( (combined_flags & MEM_RowSet)==0 );
55097  
55098   /* If one value is NULL, it is less than the other. If both values
55099   ** are NULL, return 0.
55100   */
55101   if( combined_flags&MEM_Null ){
55102     return (f2&MEM_Null) - (f1&MEM_Null);
55103   }
55104
55105   /* If one value is a number and the other is not, the number is less.
55106   ** If both are numbers, compare as reals if one is a real, or as integers
55107   ** if both values are integers.
55108   */
55109   if( combined_flags&(MEM_Int|MEM_Real) ){
55110     if( !(f1&(MEM_Int|MEM_Real)) ){
55111       return 1;
55112     }
55113     if( !(f2&(MEM_Int|MEM_Real)) ){
55114       return -1;
55115     }
55116     if( (f1 & f2 & MEM_Int)==0 ){
55117       double r1, r2;
55118       if( (f1&MEM_Real)==0 ){
55119         r1 = (double)pMem1->u.i;
55120       }else{
55121         r1 = pMem1->r;
55122       }
55123       if( (f2&MEM_Real)==0 ){
55124         r2 = (double)pMem2->u.i;
55125       }else{
55126         r2 = pMem2->r;
55127       }
55128       if( r1<r2 ) return -1;
55129       if( r1>r2 ) return 1;
55130       return 0;
55131     }else{
55132       assert( f1&MEM_Int );
55133       assert( f2&MEM_Int );
55134       if( pMem1->u.i < pMem2->u.i ) return -1;
55135       if( pMem1->u.i > pMem2->u.i ) return 1;
55136       return 0;
55137     }
55138   }
55139
55140   /* If one value is a string and the other is a blob, the string is less.
55141   ** If both are strings, compare using the collating functions.
55142   */
55143   if( combined_flags&MEM_Str ){
55144     if( (f1 & MEM_Str)==0 ){
55145       return 1;
55146     }
55147     if( (f2 & MEM_Str)==0 ){
55148       return -1;
55149     }
55150
55151     assert( pMem1->enc==pMem2->enc );
55152     assert( pMem1->enc==SQLITE_UTF8 || 
55153             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
55154
55155     /* The collation sequence must be defined at this point, even if
55156     ** the user deletes the collation sequence after the vdbe program is
55157     ** compiled (this was not always the case).
55158     */
55159     assert( !pColl || pColl->xCmp );
55160
55161     if( pColl ){
55162       if( pMem1->enc==pColl->enc ){
55163         /* The strings are already in the correct encoding.  Call the
55164         ** comparison function directly */
55165         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
55166       }else{
55167         const void *v1, *v2;
55168         int n1, n2;
55169         Mem c1;
55170         Mem c2;
55171         memset(&c1, 0, sizeof(c1));
55172         memset(&c2, 0, sizeof(c2));
55173         sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
55174         sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
55175         v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
55176         n1 = v1==0 ? 0 : c1.n;
55177         v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
55178         n2 = v2==0 ? 0 : c2.n;
55179         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
55180         sqlite3VdbeMemRelease(&c1);
55181         sqlite3VdbeMemRelease(&c2);
55182         return rc;
55183       }
55184     }
55185     /* If a NULL pointer was passed as the collate function, fall through
55186     ** to the blob case and use memcmp().  */
55187   }
55188  
55189   /* Both values must be blobs.  Compare using memcmp().  */
55190   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
55191   if( rc==0 ){
55192     rc = pMem1->n - pMem2->n;
55193   }
55194   return rc;
55195 }
55196
55197 /*
55198 ** Move data out of a btree key or data field and into a Mem structure.
55199 ** The data or key is taken from the entry that pCur is currently pointing
55200 ** to.  offset and amt determine what portion of the data or key to retrieve.
55201 ** key is true to get the key or false to get data.  The result is written
55202 ** into the pMem element.
55203 **
55204 ** The pMem structure is assumed to be uninitialized.  Any prior content
55205 ** is overwritten without being freed.
55206 **
55207 ** If this routine fails for any reason (malloc returns NULL or unable
55208 ** to read from the disk) then the pMem is left in an inconsistent state.
55209 */
55210 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
55211   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
55212   int offset,       /* Offset from the start of data to return bytes from. */
55213   int amt,          /* Number of bytes to return. */
55214   int key,          /* If true, retrieve from the btree key, not data. */
55215   Mem *pMem         /* OUT: Return data in this Mem structure. */
55216 ){
55217   char *zData;        /* Data from the btree layer */
55218   int available = 0;  /* Number of bytes available on the local btree page */
55219   int rc = SQLITE_OK; /* Return code */
55220
55221   assert( sqlite3BtreeCursorIsValid(pCur) );
55222
55223   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() 
55224   ** that both the BtShared and database handle mutexes are held. */
55225   assert( (pMem->flags & MEM_RowSet)==0 );
55226   if( key ){
55227     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
55228   }else{
55229     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
55230   }
55231   assert( zData!=0 );
55232
55233   if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
55234     sqlite3VdbeMemRelease(pMem);
55235     pMem->z = &zData[offset];
55236     pMem->flags = MEM_Blob|MEM_Ephem;
55237   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
55238     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
55239     pMem->enc = 0;
55240     pMem->type = SQLITE_BLOB;
55241     if( key ){
55242       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
55243     }else{
55244       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
55245     }
55246     pMem->z[amt] = 0;
55247     pMem->z[amt+1] = 0;
55248     if( rc!=SQLITE_OK ){
55249       sqlite3VdbeMemRelease(pMem);
55250     }
55251   }
55252   pMem->n = amt;
55253
55254   return rc;
55255 }
55256
55257 /* This function is only available internally, it is not part of the
55258 ** external API. It works in a similar way to sqlite3_value_text(),
55259 ** except the data returned is in the encoding specified by the second
55260 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
55261 ** SQLITE_UTF8.
55262 **
55263 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
55264 ** If that is the case, then the result must be aligned on an even byte
55265 ** boundary.
55266 */
55267 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
55268   if( !pVal ) return 0;
55269
55270   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
55271   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
55272   assert( (pVal->flags & MEM_RowSet)==0 );
55273
55274   if( pVal->flags&MEM_Null ){
55275     return 0;
55276   }
55277   assert( (MEM_Blob>>3) == MEM_Str );
55278   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
55279   expandBlob(pVal);
55280   if( pVal->flags&MEM_Str ){
55281     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
55282     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
55283       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
55284       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
55285         return 0;
55286       }
55287     }
55288     sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-59893-45467 */
55289   }else{
55290     assert( (pVal->flags&MEM_Blob)==0 );
55291     sqlite3VdbeMemStringify(pVal, enc);
55292     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
55293   }
55294   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
55295               || pVal->db->mallocFailed );
55296   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
55297     return pVal->z;
55298   }else{
55299     return 0;
55300   }
55301 }
55302
55303 /*
55304 ** Create a new sqlite3_value object.
55305 */
55306 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
55307   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
55308   if( p ){
55309     p->flags = MEM_Null;
55310     p->type = SQLITE_NULL;
55311     p->db = db;
55312   }
55313   return p;
55314 }
55315
55316 /*
55317 ** Create a new sqlite3_value object, containing the value of pExpr.
55318 **
55319 ** This only works for very simple expressions that consist of one constant
55320 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
55321 ** be converted directly into a value, then the value is allocated and
55322 ** a pointer written to *ppVal. The caller is responsible for deallocating
55323 ** the value by passing it to sqlite3ValueFree() later on. If the expression
55324 ** cannot be converted to a value, then *ppVal is set to NULL.
55325 */
55326 SQLITE_PRIVATE int sqlite3ValueFromExpr(
55327   sqlite3 *db,              /* The database connection */
55328   Expr *pExpr,              /* The expression to evaluate */
55329   u8 enc,                   /* Encoding to use */
55330   u8 affinity,              /* Affinity to use */
55331   sqlite3_value **ppVal     /* Write the new value here */
55332 ){
55333   int op;
55334   char *zVal = 0;
55335   sqlite3_value *pVal = 0;
55336   int negInt = 1;
55337   const char *zNeg = "";
55338
55339   if( !pExpr ){
55340     *ppVal = 0;
55341     return SQLITE_OK;
55342   }
55343   op = pExpr->op;
55344
55345   /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT2.
55346   ** The ifdef here is to enable us to achieve 100% branch test coverage even
55347   ** when SQLITE_ENABLE_STAT2 is omitted.
55348   */
55349 #ifdef SQLITE_ENABLE_STAT2
55350   if( op==TK_REGISTER ) op = pExpr->op2;
55351 #else
55352   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
55353 #endif
55354
55355   /* Handle negative integers in a single step.  This is needed in the
55356   ** case when the value is -9223372036854775808.
55357   */
55358   if( op==TK_UMINUS
55359    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
55360     pExpr = pExpr->pLeft;
55361     op = pExpr->op;
55362     negInt = -1;
55363     zNeg = "-";
55364   }
55365
55366   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
55367     pVal = sqlite3ValueNew(db);
55368     if( pVal==0 ) goto no_mem;
55369     if( ExprHasProperty(pExpr, EP_IntValue) ){
55370       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
55371     }else{
55372       zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
55373       if( zVal==0 ) goto no_mem;
55374       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
55375       if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
55376     }
55377     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
55378       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
55379     }else{
55380       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
55381     }
55382     if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
55383     if( enc!=SQLITE_UTF8 ){
55384       sqlite3VdbeChangeEncoding(pVal, enc);
55385     }
55386   }else if( op==TK_UMINUS ) {
55387     /* This branch happens for multiple negative signs.  Ex: -(-5) */
55388     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
55389       sqlite3VdbeMemNumerify(pVal);
55390       pVal->u.i = -1 * pVal->u.i;
55391       /* (double)-1 In case of SQLITE_OMIT_FLOATING_POINT... */
55392       pVal->r = (double)-1 * pVal->r;
55393       sqlite3ValueApplyAffinity(pVal, affinity, enc);
55394     }
55395   }
55396 #ifndef SQLITE_OMIT_BLOB_LITERAL
55397   else if( op==TK_BLOB ){
55398     int nVal;
55399     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
55400     assert( pExpr->u.zToken[1]=='\'' );
55401     pVal = sqlite3ValueNew(db);
55402     if( !pVal ) goto no_mem;
55403     zVal = &pExpr->u.zToken[2];
55404     nVal = sqlite3Strlen30(zVal)-1;
55405     assert( zVal[nVal]=='\'' );
55406     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
55407                          0, SQLITE_DYNAMIC);
55408   }
55409 #endif
55410
55411   if( pVal ){
55412     sqlite3VdbeMemStoreType(pVal);
55413   }
55414   *ppVal = pVal;
55415   return SQLITE_OK;
55416
55417 no_mem:
55418   db->mallocFailed = 1;
55419   sqlite3DbFree(db, zVal);
55420   sqlite3ValueFree(pVal);
55421   *ppVal = 0;
55422   return SQLITE_NOMEM;
55423 }
55424
55425 /*
55426 ** Change the string value of an sqlite3_value object
55427 */
55428 SQLITE_PRIVATE void sqlite3ValueSetStr(
55429   sqlite3_value *v,     /* Value to be set */
55430   int n,                /* Length of string z */
55431   const void *z,        /* Text of the new string */
55432   u8 enc,               /* Encoding to use */
55433   void (*xDel)(void*)   /* Destructor for the string */
55434 ){
55435   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
55436 }
55437
55438 /*
55439 ** Free an sqlite3_value object
55440 */
55441 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
55442   if( !v ) return;
55443   sqlite3VdbeMemRelease((Mem *)v);
55444   sqlite3DbFree(((Mem*)v)->db, v);
55445 }
55446
55447 /*
55448 ** Return the number of bytes in the sqlite3_value object assuming
55449 ** that it uses the encoding "enc"
55450 */
55451 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
55452   Mem *p = (Mem*)pVal;
55453   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
55454     if( p->flags & MEM_Zero ){
55455       return p->n + p->u.nZero;
55456     }else{
55457       return p->n;
55458     }
55459   }
55460   return 0;
55461 }
55462
55463 /************** End of vdbemem.c *********************************************/
55464 /************** Begin file vdbeaux.c *****************************************/
55465 /*
55466 ** 2003 September 6
55467 **
55468 ** The author disclaims copyright to this source code.  In place of
55469 ** a legal notice, here is a blessing:
55470 **
55471 **    May you do good and not evil.
55472 **    May you find forgiveness for yourself and forgive others.
55473 **    May you share freely, never taking more than you give.
55474 **
55475 *************************************************************************
55476 ** This file contains code used for creating, destroying, and populating
55477 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
55478 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
55479 ** But that file was getting too big so this subroutines were split out.
55480 */
55481
55482
55483
55484 /*
55485 ** When debugging the code generator in a symbolic debugger, one can
55486 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
55487 ** as they are added to the instruction stream.
55488 */
55489 #ifdef SQLITE_DEBUG
55490 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
55491 #endif
55492
55493
55494 /*
55495 ** Create a new virtual database engine.
55496 */
55497 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
55498   Vdbe *p;
55499   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
55500   if( p==0 ) return 0;
55501   p->db = db;
55502   if( db->pVdbe ){
55503     db->pVdbe->pPrev = p;
55504   }
55505   p->pNext = db->pVdbe;
55506   p->pPrev = 0;
55507   db->pVdbe = p;
55508   p->magic = VDBE_MAGIC_INIT;
55509   return p;
55510 }
55511
55512 /*
55513 ** Remember the SQL string for a prepared statement.
55514 */
55515 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
55516   assert( isPrepareV2==1 || isPrepareV2==0 );
55517   if( p==0 ) return;
55518 #ifdef SQLITE_OMIT_TRACE
55519   if( !isPrepareV2 ) return;
55520 #endif
55521   assert( p->zSql==0 );
55522   p->zSql = sqlite3DbStrNDup(p->db, z, n);
55523   p->isPrepareV2 = (u8)isPrepareV2;
55524 }
55525
55526 /*
55527 ** Return the SQL associated with a prepared statement
55528 */
55529 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
55530   Vdbe *p = (Vdbe *)pStmt;
55531   return (p && p->isPrepareV2) ? p->zSql : 0;
55532 }
55533
55534 /*
55535 ** Swap all content between two VDBE structures.
55536 */
55537 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
55538   Vdbe tmp, *pTmp;
55539   char *zTmp;
55540   tmp = *pA;
55541   *pA = *pB;
55542   *pB = tmp;
55543   pTmp = pA->pNext;
55544   pA->pNext = pB->pNext;
55545   pB->pNext = pTmp;
55546   pTmp = pA->pPrev;
55547   pA->pPrev = pB->pPrev;
55548   pB->pPrev = pTmp;
55549   zTmp = pA->zSql;
55550   pA->zSql = pB->zSql;
55551   pB->zSql = zTmp;
55552   pB->isPrepareV2 = pA->isPrepareV2;
55553 }
55554
55555 #ifdef SQLITE_DEBUG
55556 /*
55557 ** Turn tracing on or off
55558 */
55559 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
55560   p->trace = trace;
55561 }
55562 #endif
55563
55564 /*
55565 ** Resize the Vdbe.aOp array so that it is at least one op larger than 
55566 ** it was.
55567 **
55568 ** If an out-of-memory error occurs while resizing the array, return
55569 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain 
55570 ** unchanged (this is so that any opcodes already allocated can be 
55571 ** correctly deallocated along with the rest of the Vdbe).
55572 */
55573 static int growOpArray(Vdbe *p){
55574   VdbeOp *pNew;
55575   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
55576   pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
55577   if( pNew ){
55578     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
55579     p->aOp = pNew;
55580   }
55581   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
55582 }
55583
55584 /*
55585 ** Add a new instruction to the list of instructions current in the
55586 ** VDBE.  Return the address of the new instruction.
55587 **
55588 ** Parameters:
55589 **
55590 **    p               Pointer to the VDBE
55591 **
55592 **    op              The opcode for this instruction
55593 **
55594 **    p1, p2, p3      Operands
55595 **
55596 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
55597 ** the sqlite3VdbeChangeP4() function to change the value of the P4
55598 ** operand.
55599 */
55600 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
55601   int i;
55602   VdbeOp *pOp;
55603
55604   i = p->nOp;
55605   assert( p->magic==VDBE_MAGIC_INIT );
55606   assert( op>0 && op<0xff );
55607   if( p->nOpAlloc<=i ){
55608     if( growOpArray(p) ){
55609       return 1;
55610     }
55611   }
55612   p->nOp++;
55613   pOp = &p->aOp[i];
55614   pOp->opcode = (u8)op;
55615   pOp->p5 = 0;
55616   pOp->p1 = p1;
55617   pOp->p2 = p2;
55618   pOp->p3 = p3;
55619   pOp->p4.p = 0;
55620   pOp->p4type = P4_NOTUSED;
55621   p->expired = 0;
55622 #ifdef SQLITE_DEBUG
55623   pOp->zComment = 0;
55624   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
55625 #endif
55626 #ifdef VDBE_PROFILE
55627   pOp->cycles = 0;
55628   pOp->cnt = 0;
55629 #endif
55630   return i;
55631 }
55632 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
55633   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
55634 }
55635 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
55636   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
55637 }
55638 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
55639   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
55640 }
55641
55642
55643 /*
55644 ** Add an opcode that includes the p4 value as a pointer.
55645 */
55646 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
55647   Vdbe *p,            /* Add the opcode to this VM */
55648   int op,             /* The new opcode */
55649   int p1,             /* The P1 operand */
55650   int p2,             /* The P2 operand */
55651   int p3,             /* The P3 operand */
55652   const char *zP4,    /* The P4 operand */
55653   int p4type          /* P4 operand type */
55654 ){
55655   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
55656   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
55657   return addr;
55658 }
55659
55660 /*
55661 ** Add an opcode that includes the p4 value as an integer.
55662 */
55663 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
55664   Vdbe *p,            /* Add the opcode to this VM */
55665   int op,             /* The new opcode */
55666   int p1,             /* The P1 operand */
55667   int p2,             /* The P2 operand */
55668   int p3,             /* The P3 operand */
55669   int p4              /* The P4 operand as an integer */
55670 ){
55671   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
55672   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
55673   return addr;
55674 }
55675
55676 /*
55677 ** Create a new symbolic label for an instruction that has yet to be
55678 ** coded.  The symbolic label is really just a negative number.  The
55679 ** label can be used as the P2 value of an operation.  Later, when
55680 ** the label is resolved to a specific address, the VDBE will scan
55681 ** through its operation list and change all values of P2 which match
55682 ** the label into the resolved address.
55683 **
55684 ** The VDBE knows that a P2 value is a label because labels are
55685 ** always negative and P2 values are suppose to be non-negative.
55686 ** Hence, a negative P2 value is a label that has yet to be resolved.
55687 **
55688 ** Zero is returned if a malloc() fails.
55689 */
55690 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
55691   int i;
55692   i = p->nLabel++;
55693   assert( p->magic==VDBE_MAGIC_INIT );
55694   if( i>=p->nLabelAlloc ){
55695     int n = p->nLabelAlloc*2 + 5;
55696     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
55697                                        n*sizeof(p->aLabel[0]));
55698     p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
55699   }
55700   if( p->aLabel ){
55701     p->aLabel[i] = -1;
55702   }
55703   return -1-i;
55704 }
55705
55706 /*
55707 ** Resolve label "x" to be the address of the next instruction to
55708 ** be inserted.  The parameter "x" must have been obtained from
55709 ** a prior call to sqlite3VdbeMakeLabel().
55710 */
55711 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
55712   int j = -1-x;
55713   assert( p->magic==VDBE_MAGIC_INIT );
55714   assert( j>=0 && j<p->nLabel );
55715   if( p->aLabel ){
55716     p->aLabel[j] = p->nOp;
55717   }
55718 }
55719
55720 /*
55721 ** Mark the VDBE as one that can only be run one time.
55722 */
55723 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
55724   p->runOnlyOnce = 1;
55725 }
55726
55727 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
55728
55729 /*
55730 ** The following type and function are used to iterate through all opcodes
55731 ** in a Vdbe main program and each of the sub-programs (triggers) it may 
55732 ** invoke directly or indirectly. It should be used as follows:
55733 **
55734 **   Op *pOp;
55735 **   VdbeOpIter sIter;
55736 **
55737 **   memset(&sIter, 0, sizeof(sIter));
55738 **   sIter.v = v;                            // v is of type Vdbe* 
55739 **   while( (pOp = opIterNext(&sIter)) ){
55740 **     // Do something with pOp
55741 **   }
55742 **   sqlite3DbFree(v->db, sIter.apSub);
55743 ** 
55744 */
55745 typedef struct VdbeOpIter VdbeOpIter;
55746 struct VdbeOpIter {
55747   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
55748   SubProgram **apSub;        /* Array of subprograms */
55749   int nSub;                  /* Number of entries in apSub */
55750   int iAddr;                 /* Address of next instruction to return */
55751   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
55752 };
55753 static Op *opIterNext(VdbeOpIter *p){
55754   Vdbe *v = p->v;
55755   Op *pRet = 0;
55756   Op *aOp;
55757   int nOp;
55758
55759   if( p->iSub<=p->nSub ){
55760
55761     if( p->iSub==0 ){
55762       aOp = v->aOp;
55763       nOp = v->nOp;
55764     }else{
55765       aOp = p->apSub[p->iSub-1]->aOp;
55766       nOp = p->apSub[p->iSub-1]->nOp;
55767     }
55768     assert( p->iAddr<nOp );
55769
55770     pRet = &aOp[p->iAddr];
55771     p->iAddr++;
55772     if( p->iAddr==nOp ){
55773       p->iSub++;
55774       p->iAddr = 0;
55775     }
55776   
55777     if( pRet->p4type==P4_SUBPROGRAM ){
55778       int nByte = (p->nSub+1)*sizeof(SubProgram*);
55779       int j;
55780       for(j=0; j<p->nSub; j++){
55781         if( p->apSub[j]==pRet->p4.pProgram ) break;
55782       }
55783       if( j==p->nSub ){
55784         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
55785         if( !p->apSub ){
55786           pRet = 0;
55787         }else{
55788           p->apSub[p->nSub++] = pRet->p4.pProgram;
55789         }
55790       }
55791     }
55792   }
55793
55794   return pRet;
55795 }
55796
55797 /*
55798 ** Check if the program stored in the VM associated with pParse may
55799 ** throw an ABORT exception (causing the statement, but not entire transaction
55800 ** to be rolled back). This condition is true if the main program or any
55801 ** sub-programs contains any of the following:
55802 **
55803 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
55804 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
55805 **   *  OP_Destroy
55806 **   *  OP_VUpdate
55807 **   *  OP_VRename
55808 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
55809 **
55810 ** Then check that the value of Parse.mayAbort is true if an
55811 ** ABORT may be thrown, or false otherwise. Return true if it does
55812 ** match, or false otherwise. This function is intended to be used as
55813 ** part of an assert statement in the compiler. Similar to:
55814 **
55815 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
55816 */
55817 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
55818   int hasAbort = 0;
55819   Op *pOp;
55820   VdbeOpIter sIter;
55821   memset(&sIter, 0, sizeof(sIter));
55822   sIter.v = v;
55823
55824   while( (pOp = opIterNext(&sIter))!=0 ){
55825     int opcode = pOp->opcode;
55826     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename 
55827 #ifndef SQLITE_OMIT_FOREIGN_KEY
55828      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1) 
55829 #endif
55830      || ((opcode==OP_Halt || opcode==OP_HaltIfNull) 
55831       && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
55832     ){
55833       hasAbort = 1;
55834       break;
55835     }
55836   }
55837   sqlite3DbFree(v->db, sIter.apSub);
55838
55839   /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
55840   ** If malloc failed, then the while() loop above may not have iterated
55841   ** through all opcodes and hasAbort may be set incorrectly. Return
55842   ** true for this case to prevent the assert() in the callers frame
55843   ** from failing.  */
55844   return ( v->db->mallocFailed || hasAbort==mayAbort );
55845 }
55846 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
55847
55848 /*
55849 ** Loop through the program looking for P2 values that are negative
55850 ** on jump instructions.  Each such value is a label.  Resolve the
55851 ** label by setting the P2 value to its correct non-zero value.
55852 **
55853 ** This routine is called once after all opcodes have been inserted.
55854 **
55855 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
55856 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
55857 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
55858 **
55859 ** The Op.opflags field is set on all opcodes.
55860 */
55861 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
55862   int i;
55863   int nMaxArgs = *pMaxFuncArgs;
55864   Op *pOp;
55865   int *aLabel = p->aLabel;
55866   p->readOnly = 1;
55867   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
55868     u8 opcode = pOp->opcode;
55869
55870     pOp->opflags = sqlite3OpcodeProperty[opcode];
55871     if( opcode==OP_Function || opcode==OP_AggStep ){
55872       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
55873     }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
55874       p->readOnly = 0;
55875 #ifndef SQLITE_OMIT_VIRTUALTABLE
55876     }else if( opcode==OP_VUpdate ){
55877       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
55878     }else if( opcode==OP_VFilter ){
55879       int n;
55880       assert( p->nOp - i >= 3 );
55881       assert( pOp[-1].opcode==OP_Integer );
55882       n = pOp[-1].p1;
55883       if( n>nMaxArgs ) nMaxArgs = n;
55884 #endif
55885     }
55886
55887     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
55888       assert( -1-pOp->p2<p->nLabel );
55889       pOp->p2 = aLabel[-1-pOp->p2];
55890     }
55891   }
55892   sqlite3DbFree(p->db, p->aLabel);
55893   p->aLabel = 0;
55894
55895   *pMaxFuncArgs = nMaxArgs;
55896 }
55897
55898 /*
55899 ** Return the address of the next instruction to be inserted.
55900 */
55901 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
55902   assert( p->magic==VDBE_MAGIC_INIT );
55903   return p->nOp;
55904 }
55905
55906 /*
55907 ** This function returns a pointer to the array of opcodes associated with
55908 ** the Vdbe passed as the first argument. It is the callers responsibility
55909 ** to arrange for the returned array to be eventually freed using the 
55910 ** vdbeFreeOpArray() function.
55911 **
55912 ** Before returning, *pnOp is set to the number of entries in the returned
55913 ** array. Also, *pnMaxArg is set to the larger of its current value and 
55914 ** the number of entries in the Vdbe.apArg[] array required to execute the 
55915 ** returned program.
55916 */
55917 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
55918   VdbeOp *aOp = p->aOp;
55919   assert( aOp && !p->db->mallocFailed );
55920
55921   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
55922   assert( p->aMutex.nMutex==0 );
55923
55924   resolveP2Values(p, pnMaxArg);
55925   *pnOp = p->nOp;
55926   p->aOp = 0;
55927   return aOp;
55928 }
55929
55930 /*
55931 ** Add a whole list of operations to the operation stack.  Return the
55932 ** address of the first operation added.
55933 */
55934 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
55935   int addr;
55936   assert( p->magic==VDBE_MAGIC_INIT );
55937   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
55938     return 0;
55939   }
55940   addr = p->nOp;
55941   if( ALWAYS(nOp>0) ){
55942     int i;
55943     VdbeOpList const *pIn = aOp;
55944     for(i=0; i<nOp; i++, pIn++){
55945       int p2 = pIn->p2;
55946       VdbeOp *pOut = &p->aOp[i+addr];
55947       pOut->opcode = pIn->opcode;
55948       pOut->p1 = pIn->p1;
55949       if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
55950         pOut->p2 = addr + ADDR(p2);
55951       }else{
55952         pOut->p2 = p2;
55953       }
55954       pOut->p3 = pIn->p3;
55955       pOut->p4type = P4_NOTUSED;
55956       pOut->p4.p = 0;
55957       pOut->p5 = 0;
55958 #ifdef SQLITE_DEBUG
55959       pOut->zComment = 0;
55960       if( sqlite3VdbeAddopTrace ){
55961         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
55962       }
55963 #endif
55964     }
55965     p->nOp += nOp;
55966   }
55967   return addr;
55968 }
55969
55970 /*
55971 ** Change the value of the P1 operand for a specific instruction.
55972 ** This routine is useful when a large program is loaded from a
55973 ** static array using sqlite3VdbeAddOpList but we want to make a
55974 ** few minor changes to the program.
55975 */
55976 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
55977   assert( p!=0 );
55978   assert( addr>=0 );
55979   if( p->nOp>addr ){
55980     p->aOp[addr].p1 = val;
55981   }
55982 }
55983
55984 /*
55985 ** Change the value of the P2 operand for a specific instruction.
55986 ** This routine is useful for setting a jump destination.
55987 */
55988 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
55989   assert( p!=0 );
55990   assert( addr>=0 );
55991   if( p->nOp>addr ){
55992     p->aOp[addr].p2 = val;
55993   }
55994 }
55995
55996 /*
55997 ** Change the value of the P3 operand for a specific instruction.
55998 */
55999 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
56000   assert( p!=0 );
56001   assert( addr>=0 );
56002   if( p->nOp>addr ){
56003     p->aOp[addr].p3 = val;
56004   }
56005 }
56006
56007 /*
56008 ** Change the value of the P5 operand for the most recently
56009 ** added operation.
56010 */
56011 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
56012   assert( p!=0 );
56013   if( p->aOp ){
56014     assert( p->nOp>0 );
56015     p->aOp[p->nOp-1].p5 = val;
56016   }
56017 }
56018
56019 /*
56020 ** Change the P2 operand of instruction addr so that it points to
56021 ** the address of the next instruction to be coded.
56022 */
56023 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
56024   sqlite3VdbeChangeP2(p, addr, p->nOp);
56025 }
56026
56027
56028 /*
56029 ** If the input FuncDef structure is ephemeral, then free it.  If
56030 ** the FuncDef is not ephermal, then do nothing.
56031 */
56032 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
56033   if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
56034     sqlite3DbFree(db, pDef);
56035   }
56036 }
56037
56038 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
56039
56040 /*
56041 ** Delete a P4 value if necessary.
56042 */
56043 static void freeP4(sqlite3 *db, int p4type, void *p4){
56044   if( p4 ){
56045     assert( db );
56046     switch( p4type ){
56047       case P4_REAL:
56048       case P4_INT64:
56049       case P4_DYNAMIC:
56050       case P4_KEYINFO:
56051       case P4_INTARRAY:
56052       case P4_KEYINFO_HANDOFF: {
56053         sqlite3DbFree(db, p4);
56054         break;
56055       }
56056       case P4_MPRINTF: {
56057         if( db->pnBytesFreed==0 ) sqlite3_free(p4);
56058         break;
56059       }
56060       case P4_VDBEFUNC: {
56061         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
56062         freeEphemeralFunction(db, pVdbeFunc->pFunc);
56063         if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
56064         sqlite3DbFree(db, pVdbeFunc);
56065         break;
56066       }
56067       case P4_FUNCDEF: {
56068         freeEphemeralFunction(db, (FuncDef*)p4);
56069         break;
56070       }
56071       case P4_MEM: {
56072         if( db->pnBytesFreed==0 ){
56073           sqlite3ValueFree((sqlite3_value*)p4);
56074         }else{
56075           Mem *p = (Mem*)p4;
56076           sqlite3DbFree(db, p->zMalloc);
56077           sqlite3DbFree(db, p);
56078         }
56079         break;
56080       }
56081       case P4_VTAB : {
56082         if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
56083         break;
56084       }
56085     }
56086   }
56087 }
56088
56089 /*
56090 ** Free the space allocated for aOp and any p4 values allocated for the
56091 ** opcodes contained within. If aOp is not NULL it is assumed to contain 
56092 ** nOp entries. 
56093 */
56094 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
56095   if( aOp ){
56096     Op *pOp;
56097     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
56098       freeP4(db, pOp->p4type, pOp->p4.p);
56099 #ifdef SQLITE_DEBUG
56100       sqlite3DbFree(db, pOp->zComment);
56101 #endif     
56102     }
56103   }
56104   sqlite3DbFree(db, aOp);
56105 }
56106
56107 /*
56108 ** Link the SubProgram object passed as the second argument into the linked
56109 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
56110 ** objects when the VM is no longer required.
56111 */
56112 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
56113   p->pNext = pVdbe->pProgram;
56114   pVdbe->pProgram = p;
56115 }
56116
56117 /*
56118 ** Change N opcodes starting at addr to No-ops.
56119 */
56120 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
56121   if( p->aOp ){
56122     VdbeOp *pOp = &p->aOp[addr];
56123     sqlite3 *db = p->db;
56124     while( N-- ){
56125       freeP4(db, pOp->p4type, pOp->p4.p);
56126       memset(pOp, 0, sizeof(pOp[0]));
56127       pOp->opcode = OP_Noop;
56128       pOp++;
56129     }
56130   }
56131 }
56132
56133 /*
56134 ** Change the value of the P4 operand for a specific instruction.
56135 ** This routine is useful when a large program is loaded from a
56136 ** static array using sqlite3VdbeAddOpList but we want to make a
56137 ** few minor changes to the program.
56138 **
56139 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
56140 ** the string is made into memory obtained from sqlite3_malloc().
56141 ** A value of n==0 means copy bytes of zP4 up to and including the
56142 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
56143 **
56144 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
56145 ** A copy is made of the KeyInfo structure into memory obtained from
56146 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
56147 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
56148 ** stored in memory that the caller has obtained from sqlite3_malloc. The 
56149 ** caller should not free the allocation, it will be freed when the Vdbe is
56150 ** finalized.
56151 ** 
56152 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
56153 ** to a string or structure that is guaranteed to exist for the lifetime of
56154 ** the Vdbe. In these cases we can just copy the pointer.
56155 **
56156 ** If addr<0 then change P4 on the most recently inserted instruction.
56157 */
56158 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
56159   Op *pOp;
56160   sqlite3 *db;
56161   assert( p!=0 );
56162   db = p->db;
56163   assert( p->magic==VDBE_MAGIC_INIT );
56164   if( p->aOp==0 || db->mallocFailed ){
56165     if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
56166       freeP4(db, n, (void*)*(char**)&zP4);
56167     }
56168     return;
56169   }
56170   assert( p->nOp>0 );
56171   assert( addr<p->nOp );
56172   if( addr<0 ){
56173     addr = p->nOp - 1;
56174   }
56175   pOp = &p->aOp[addr];
56176   freeP4(db, pOp->p4type, pOp->p4.p);
56177   pOp->p4.p = 0;
56178   if( n==P4_INT32 ){
56179     /* Note: this cast is safe, because the origin data point was an int
56180     ** that was cast to a (const char *). */
56181     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
56182     pOp->p4type = P4_INT32;
56183   }else if( zP4==0 ){
56184     pOp->p4.p = 0;
56185     pOp->p4type = P4_NOTUSED;
56186   }else if( n==P4_KEYINFO ){
56187     KeyInfo *pKeyInfo;
56188     int nField, nByte;
56189
56190     nField = ((KeyInfo*)zP4)->nField;
56191     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
56192     pKeyInfo = sqlite3DbMallocRaw(0, nByte);
56193     pOp->p4.pKeyInfo = pKeyInfo;
56194     if( pKeyInfo ){
56195       u8 *aSortOrder;
56196       memcpy((char*)pKeyInfo, zP4, nByte - nField);
56197       aSortOrder = pKeyInfo->aSortOrder;
56198       if( aSortOrder ){
56199         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
56200         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
56201       }
56202       pOp->p4type = P4_KEYINFO;
56203     }else{
56204       p->db->mallocFailed = 1;
56205       pOp->p4type = P4_NOTUSED;
56206     }
56207   }else if( n==P4_KEYINFO_HANDOFF ){
56208     pOp->p4.p = (void*)zP4;
56209     pOp->p4type = P4_KEYINFO;
56210   }else if( n==P4_VTAB ){
56211     pOp->p4.p = (void*)zP4;
56212     pOp->p4type = P4_VTAB;
56213     sqlite3VtabLock((VTable *)zP4);
56214     assert( ((VTable *)zP4)->db==p->db );
56215   }else if( n<0 ){
56216     pOp->p4.p = (void*)zP4;
56217     pOp->p4type = (signed char)n;
56218   }else{
56219     if( n==0 ) n = sqlite3Strlen30(zP4);
56220     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
56221     pOp->p4type = P4_DYNAMIC;
56222   }
56223 }
56224
56225 #ifndef NDEBUG
56226 /*
56227 ** Change the comment on the the most recently coded instruction.  Or
56228 ** insert a No-op and add the comment to that new instruction.  This
56229 ** makes the code easier to read during debugging.  None of this happens
56230 ** in a production build.
56231 */
56232 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
56233   va_list ap;
56234   if( !p ) return;
56235   assert( p->nOp>0 || p->aOp==0 );
56236   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
56237   if( p->nOp ){
56238     char **pz = &p->aOp[p->nOp-1].zComment;
56239     va_start(ap, zFormat);
56240     sqlite3DbFree(p->db, *pz);
56241     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
56242     va_end(ap);
56243   }
56244 }
56245 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
56246   va_list ap;
56247   if( !p ) return;
56248   sqlite3VdbeAddOp0(p, OP_Noop);
56249   assert( p->nOp>0 || p->aOp==0 );
56250   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
56251   if( p->nOp ){
56252     char **pz = &p->aOp[p->nOp-1].zComment;
56253     va_start(ap, zFormat);
56254     sqlite3DbFree(p->db, *pz);
56255     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
56256     va_end(ap);
56257   }
56258 }
56259 #endif  /* NDEBUG */
56260
56261 /*
56262 ** Return the opcode for a given address.  If the address is -1, then
56263 ** return the most recently inserted opcode.
56264 **
56265 ** If a memory allocation error has occurred prior to the calling of this
56266 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
56267 ** is readable but not writable, though it is cast to a writable value.
56268 ** The return of a dummy opcode allows the call to continue functioning
56269 ** after a OOM fault without having to check to see if the return from 
56270 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
56271 ** dummy will never be written to.  This is verified by code inspection and
56272 ** by running with Valgrind.
56273 **
56274 ** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
56275 ** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
56276 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
56277 ** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
56278 ** having to double-check to make sure that the result is non-negative. But
56279 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
56280 ** check the value of p->nOp-1 before continuing.
56281 */
56282 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
56283   /* C89 specifies that the constant "dummy" will be initialized to all
56284   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
56285   static const VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
56286   assert( p->magic==VDBE_MAGIC_INIT );
56287   if( addr<0 ){
56288 #ifdef SQLITE_OMIT_TRACE
56289     if( p->nOp==0 ) return (VdbeOp*)&dummy;
56290 #endif
56291     addr = p->nOp - 1;
56292   }
56293   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
56294   if( p->db->mallocFailed ){
56295     return (VdbeOp*)&dummy;
56296   }else{
56297     return &p->aOp[addr];
56298   }
56299 }
56300
56301 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
56302      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
56303 /*
56304 ** Compute a string that describes the P4 parameter for an opcode.
56305 ** Use zTemp for any required temporary buffer space.
56306 */
56307 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
56308   char *zP4 = zTemp;
56309   assert( nTemp>=20 );
56310   switch( pOp->p4type ){
56311     case P4_KEYINFO_STATIC:
56312     case P4_KEYINFO: {
56313       int i, j;
56314       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
56315       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
56316       i = sqlite3Strlen30(zTemp);
56317       for(j=0; j<pKeyInfo->nField; j++){
56318         CollSeq *pColl = pKeyInfo->aColl[j];
56319         if( pColl ){
56320           int n = sqlite3Strlen30(pColl->zName);
56321           if( i+n>nTemp-6 ){
56322             memcpy(&zTemp[i],",...",4);
56323             break;
56324           }
56325           zTemp[i++] = ',';
56326           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
56327             zTemp[i++] = '-';
56328           }
56329           memcpy(&zTemp[i], pColl->zName,n+1);
56330           i += n;
56331         }else if( i+4<nTemp-6 ){
56332           memcpy(&zTemp[i],",nil",4);
56333           i += 4;
56334         }
56335       }
56336       zTemp[i++] = ')';
56337       zTemp[i] = 0;
56338       assert( i<nTemp );
56339       break;
56340     }
56341     case P4_COLLSEQ: {
56342       CollSeq *pColl = pOp->p4.pColl;
56343       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
56344       break;
56345     }
56346     case P4_FUNCDEF: {
56347       FuncDef *pDef = pOp->p4.pFunc;
56348       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
56349       break;
56350     }
56351     case P4_INT64: {
56352       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
56353       break;
56354     }
56355     case P4_INT32: {
56356       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
56357       break;
56358     }
56359     case P4_REAL: {
56360       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
56361       break;
56362     }
56363     case P4_MEM: {
56364       Mem *pMem = pOp->p4.pMem;
56365       assert( (pMem->flags & MEM_Null)==0 );
56366       if( pMem->flags & MEM_Str ){
56367         zP4 = pMem->z;
56368       }else if( pMem->flags & MEM_Int ){
56369         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
56370       }else if( pMem->flags & MEM_Real ){
56371         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
56372       }else{
56373         assert( pMem->flags & MEM_Blob );
56374         zP4 = "(blob)";
56375       }
56376       break;
56377     }
56378 #ifndef SQLITE_OMIT_VIRTUALTABLE
56379     case P4_VTAB: {
56380       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
56381       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
56382       break;
56383     }
56384 #endif
56385     case P4_INTARRAY: {
56386       sqlite3_snprintf(nTemp, zTemp, "intarray");
56387       break;
56388     }
56389     case P4_SUBPROGRAM: {
56390       sqlite3_snprintf(nTemp, zTemp, "program");
56391       break;
56392     }
56393     default: {
56394       zP4 = pOp->p4.z;
56395       if( zP4==0 ){
56396         zP4 = zTemp;
56397         zTemp[0] = 0;
56398       }
56399     }
56400   }
56401   assert( zP4!=0 );
56402   return zP4;
56403 }
56404 #endif
56405
56406 /*
56407 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
56408 **
56409 ** The prepared statement has to know in advance which Btree objects
56410 ** will be used so that it can acquire mutexes on them all in sorted
56411 ** order (via sqlite3VdbeMutexArrayEnter().  Mutexes are acquired
56412 ** in order (and released in reverse order) to avoid deadlocks.
56413 */
56414 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
56415   int mask;
56416   assert( i>=0 && i<p->db->nDb && i<sizeof(u32)*8 );
56417   assert( i<(int)sizeof(p->btreeMask)*8 );
56418   mask = ((u32)1)<<i;
56419   if( (p->btreeMask & mask)==0 ){
56420     p->btreeMask |= mask;
56421     sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
56422   }
56423 }
56424
56425
56426 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
56427 /*
56428 ** Print a single opcode.  This routine is used for debugging only.
56429 */
56430 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
56431   char *zP4;
56432   char zPtr[50];
56433   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
56434   if( pOut==0 ) pOut = stdout;
56435   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
56436   fprintf(pOut, zFormat1, pc, 
56437       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
56438 #ifdef SQLITE_DEBUG
56439       pOp->zComment ? pOp->zComment : ""
56440 #else
56441       ""
56442 #endif
56443   );
56444   fflush(pOut);
56445 }
56446 #endif
56447
56448 /*
56449 ** Release an array of N Mem elements
56450 */
56451 static void releaseMemArray(Mem *p, int N){
56452   if( p && N ){
56453     Mem *pEnd;
56454     sqlite3 *db = p->db;
56455     u8 malloc_failed = db->mallocFailed;
56456     if( db->pnBytesFreed ){
56457       for(pEnd=&p[N]; p<pEnd; p++){
56458         sqlite3DbFree(db, p->zMalloc);
56459       }
56460       return;
56461     }
56462     for(pEnd=&p[N]; p<pEnd; p++){
56463       assert( (&p[1])==pEnd || p[0].db==p[1].db );
56464
56465       /* This block is really an inlined version of sqlite3VdbeMemRelease()
56466       ** that takes advantage of the fact that the memory cell value is 
56467       ** being set to NULL after releasing any dynamic resources.
56468       **
56469       ** The justification for duplicating code is that according to 
56470       ** callgrind, this causes a certain test case to hit the CPU 4.7 
56471       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
56472       ** sqlite3MemRelease() were called from here. With -O2, this jumps
56473       ** to 6.6 percent. The test case is inserting 1000 rows into a table 
56474       ** with no indexes using a single prepared INSERT statement, bind() 
56475       ** and reset(). Inserts are grouped into a transaction.
56476       */
56477       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
56478         sqlite3VdbeMemRelease(p);
56479       }else if( p->zMalloc ){
56480         sqlite3DbFree(db, p->zMalloc);
56481         p->zMalloc = 0;
56482       }
56483
56484       p->flags = MEM_Null;
56485     }
56486     db->mallocFailed = malloc_failed;
56487   }
56488 }
56489
56490 /*
56491 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
56492 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
56493 */
56494 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
56495   int i;
56496   Mem *aMem = VdbeFrameMem(p);
56497   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
56498   for(i=0; i<p->nChildCsr; i++){
56499     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
56500   }
56501   releaseMemArray(aMem, p->nChildMem);
56502   sqlite3DbFree(p->v->db, p);
56503 }
56504
56505 #ifndef SQLITE_OMIT_EXPLAIN
56506 /*
56507 ** Give a listing of the program in the virtual machine.
56508 **
56509 ** The interface is the same as sqlite3VdbeExec().  But instead of
56510 ** running the code, it invokes the callback once for each instruction.
56511 ** This feature is used to implement "EXPLAIN".
56512 **
56513 ** When p->explain==1, each instruction is listed.  When
56514 ** p->explain==2, only OP_Explain instructions are listed and these
56515 ** are shown in a different format.  p->explain==2 is used to implement
56516 ** EXPLAIN QUERY PLAN.
56517 **
56518 ** When p->explain==1, first the main program is listed, then each of
56519 ** the trigger subprograms are listed one by one.
56520 */
56521 SQLITE_PRIVATE int sqlite3VdbeList(
56522   Vdbe *p                   /* The VDBE */
56523 ){
56524   int nRow;                            /* Stop when row count reaches this */
56525   int nSub = 0;                        /* Number of sub-vdbes seen so far */
56526   SubProgram **apSub = 0;              /* Array of sub-vdbes */
56527   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
56528   sqlite3 *db = p->db;                 /* The database connection */
56529   int i;                               /* Loop counter */
56530   int rc = SQLITE_OK;                  /* Return code */
56531   Mem *pMem = p->pResultSet = &p->aMem[1];  /* First Mem of result set */
56532
56533   assert( p->explain );
56534   assert( p->magic==VDBE_MAGIC_RUN );
56535   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
56536
56537   /* Even though this opcode does not use dynamic strings for
56538   ** the result, result columns may become dynamic if the user calls
56539   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
56540   */
56541   releaseMemArray(pMem, 8);
56542
56543   if( p->rc==SQLITE_NOMEM ){
56544     /* This happens if a malloc() inside a call to sqlite3_column_text() or
56545     ** sqlite3_column_text16() failed.  */
56546     db->mallocFailed = 1;
56547     return SQLITE_ERROR;
56548   }
56549
56550   /* When the number of output rows reaches nRow, that means the
56551   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
56552   ** nRow is the sum of the number of rows in the main program, plus
56553   ** the sum of the number of rows in all trigger subprograms encountered
56554   ** so far.  The nRow value will increase as new trigger subprograms are
56555   ** encountered, but p->pc will eventually catch up to nRow.
56556   */
56557   nRow = p->nOp;
56558   if( p->explain==1 ){
56559     /* The first 8 memory cells are used for the result set.  So we will
56560     ** commandeer the 9th cell to use as storage for an array of pointers
56561     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
56562     ** cells.  */
56563     assert( p->nMem>9 );
56564     pSub = &p->aMem[9];
56565     if( pSub->flags&MEM_Blob ){
56566       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
56567       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
56568       nSub = pSub->n/sizeof(Vdbe*);
56569       apSub = (SubProgram **)pSub->z;
56570     }
56571     for(i=0; i<nSub; i++){
56572       nRow += apSub[i]->nOp;
56573     }
56574   }
56575
56576   do{
56577     i = p->pc++;
56578   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
56579   if( i>=nRow ){
56580     p->rc = SQLITE_OK;
56581     rc = SQLITE_DONE;
56582   }else if( db->u1.isInterrupted ){
56583     p->rc = SQLITE_INTERRUPT;
56584     rc = SQLITE_ERROR;
56585     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
56586   }else{
56587     char *z;
56588     Op *pOp;
56589     if( i<p->nOp ){
56590       /* The output line number is small enough that we are still in the
56591       ** main program. */
56592       pOp = &p->aOp[i];
56593     }else{
56594       /* We are currently listing subprograms.  Figure out which one and
56595       ** pick up the appropriate opcode. */
56596       int j;
56597       i -= p->nOp;
56598       for(j=0; i>=apSub[j]->nOp; j++){
56599         i -= apSub[j]->nOp;
56600       }
56601       pOp = &apSub[j]->aOp[i];
56602     }
56603     if( p->explain==1 ){
56604       pMem->flags = MEM_Int;
56605       pMem->type = SQLITE_INTEGER;
56606       pMem->u.i = i;                                /* Program counter */
56607       pMem++;
56608   
56609       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
56610       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
56611       assert( pMem->z!=0 );
56612       pMem->n = sqlite3Strlen30(pMem->z);
56613       pMem->type = SQLITE_TEXT;
56614       pMem->enc = SQLITE_UTF8;
56615       pMem++;
56616
56617       /* When an OP_Program opcode is encounter (the only opcode that has
56618       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
56619       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
56620       ** has not already been seen.
56621       */
56622       if( pOp->p4type==P4_SUBPROGRAM ){
56623         int nByte = (nSub+1)*sizeof(SubProgram*);
56624         int j;
56625         for(j=0; j<nSub; j++){
56626           if( apSub[j]==pOp->p4.pProgram ) break;
56627         }
56628         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
56629           apSub = (SubProgram **)pSub->z;
56630           apSub[nSub++] = pOp->p4.pProgram;
56631           pSub->flags |= MEM_Blob;
56632           pSub->n = nSub*sizeof(SubProgram*);
56633         }
56634       }
56635     }
56636
56637     pMem->flags = MEM_Int;
56638     pMem->u.i = pOp->p1;                          /* P1 */
56639     pMem->type = SQLITE_INTEGER;
56640     pMem++;
56641
56642     pMem->flags = MEM_Int;
56643     pMem->u.i = pOp->p2;                          /* P2 */
56644     pMem->type = SQLITE_INTEGER;
56645     pMem++;
56646
56647     pMem->flags = MEM_Int;
56648     pMem->u.i = pOp->p3;                          /* P3 */
56649     pMem->type = SQLITE_INTEGER;
56650     pMem++;
56651
56652     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
56653       assert( p->db->mallocFailed );
56654       return SQLITE_ERROR;
56655     }
56656     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
56657     z = displayP4(pOp, pMem->z, 32);
56658     if( z!=pMem->z ){
56659       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
56660     }else{
56661       assert( pMem->z!=0 );
56662       pMem->n = sqlite3Strlen30(pMem->z);
56663       pMem->enc = SQLITE_UTF8;
56664     }
56665     pMem->type = SQLITE_TEXT;
56666     pMem++;
56667
56668     if( p->explain==1 ){
56669       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
56670         assert( p->db->mallocFailed );
56671         return SQLITE_ERROR;
56672       }
56673       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
56674       pMem->n = 2;
56675       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
56676       pMem->type = SQLITE_TEXT;
56677       pMem->enc = SQLITE_UTF8;
56678       pMem++;
56679   
56680 #ifdef SQLITE_DEBUG
56681       if( pOp->zComment ){
56682         pMem->flags = MEM_Str|MEM_Term;
56683         pMem->z = pOp->zComment;
56684         pMem->n = sqlite3Strlen30(pMem->z);
56685         pMem->enc = SQLITE_UTF8;
56686         pMem->type = SQLITE_TEXT;
56687       }else
56688 #endif
56689       {
56690         pMem->flags = MEM_Null;                       /* Comment */
56691         pMem->type = SQLITE_NULL;
56692       }
56693     }
56694
56695     p->nResColumn = 8 - 4*(p->explain-1);
56696     p->rc = SQLITE_OK;
56697     rc = SQLITE_ROW;
56698   }
56699   return rc;
56700 }
56701 #endif /* SQLITE_OMIT_EXPLAIN */
56702
56703 #ifdef SQLITE_DEBUG
56704 /*
56705 ** Print the SQL that was used to generate a VDBE program.
56706 */
56707 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
56708   int nOp = p->nOp;
56709   VdbeOp *pOp;
56710   if( nOp<1 ) return;
56711   pOp = &p->aOp[0];
56712   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
56713     const char *z = pOp->p4.z;
56714     while( sqlite3Isspace(*z) ) z++;
56715     printf("SQL: [%s]\n", z);
56716   }
56717 }
56718 #endif
56719
56720 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
56721 /*
56722 ** Print an IOTRACE message showing SQL content.
56723 */
56724 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
56725   int nOp = p->nOp;
56726   VdbeOp *pOp;
56727   if( sqlite3IoTrace==0 ) return;
56728   if( nOp<1 ) return;
56729   pOp = &p->aOp[0];
56730   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
56731     int i, j;
56732     char z[1000];
56733     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
56734     for(i=0; sqlite3Isspace(z[i]); i++){}
56735     for(j=0; z[i]; i++){
56736       if( sqlite3Isspace(z[i]) ){
56737         if( z[i-1]!=' ' ){
56738           z[j++] = ' ';
56739         }
56740       }else{
56741         z[j++] = z[i];
56742       }
56743     }
56744     z[j] = 0;
56745     sqlite3IoTrace("SQL %s\n", z);
56746   }
56747 }
56748 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
56749
56750 /*
56751 ** Allocate space from a fixed size buffer and return a pointer to
56752 ** that space.  If insufficient space is available, return NULL.
56753 **
56754 ** The pBuf parameter is the initial value of a pointer which will
56755 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
56756 ** NULL, it means that memory space has already been allocated and that
56757 ** this routine should not allocate any new memory.  When pBuf is not
56758 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
56759 ** is NULL.
56760 **
56761 ** nByte is the number of bytes of space needed.
56762 **
56763 ** *ppFrom points to available space and pEnd points to the end of the
56764 ** available space.  When space is allocated, *ppFrom is advanced past
56765 ** the end of the allocated space.
56766 **
56767 ** *pnByte is a counter of the number of bytes of space that have failed
56768 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
56769 ** request, then increment *pnByte by the amount of the request.
56770 */
56771 static void *allocSpace(
56772   void *pBuf,          /* Where return pointer will be stored */
56773   int nByte,           /* Number of bytes to allocate */
56774   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
56775   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
56776   int *pnByte          /* If allocation cannot be made, increment *pnByte */
56777 ){
56778   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
56779   if( pBuf ) return pBuf;
56780   nByte = ROUND8(nByte);
56781   if( &(*ppFrom)[nByte] <= pEnd ){
56782     pBuf = (void*)*ppFrom;
56783     *ppFrom += nByte;
56784   }else{
56785     *pnByte += nByte;
56786   }
56787   return pBuf;
56788 }
56789
56790 /*
56791 ** Prepare a virtual machine for execution.  This involves things such
56792 ** as allocating stack space and initializing the program counter.
56793 ** After the VDBE has be prepped, it can be executed by one or more
56794 ** calls to sqlite3VdbeExec().  
56795 **
56796 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
56797 ** VDBE_MAGIC_RUN.
56798 **
56799 ** This function may be called more than once on a single virtual machine.
56800 ** The first call is made while compiling the SQL statement. Subsequent
56801 ** calls are made as part of the process of resetting a statement to be
56802 ** re-executed (from a call to sqlite3_reset()). The nVar, nMem, nCursor 
56803 ** and isExplain parameters are only passed correct values the first time
56804 ** the function is called. On subsequent calls, from sqlite3_reset(), nVar
56805 ** is passed -1 and nMem, nCursor and isExplain are all passed zero.
56806 */
56807 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
56808   Vdbe *p,                       /* The VDBE */
56809   int nVar,                      /* Number of '?' see in the SQL statement */
56810   int nMem,                      /* Number of memory cells to allocate */
56811   int nCursor,                   /* Number of cursors to allocate */
56812   int nArg,                      /* Maximum number of args in SubPrograms */
56813   int isExplain,                 /* True if the EXPLAIN keywords is present */
56814   int usesStmtJournal            /* True to set Vdbe.usesStmtJournal */
56815 ){
56816   int n;
56817   sqlite3 *db = p->db;
56818
56819   assert( p!=0 );
56820   assert( p->magic==VDBE_MAGIC_INIT );
56821
56822   /* There should be at least one opcode.
56823   */
56824   assert( p->nOp>0 );
56825
56826   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
56827   p->magic = VDBE_MAGIC_RUN;
56828
56829   /* For each cursor required, also allocate a memory cell. Memory
56830   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
56831   ** the vdbe program. Instead they are used to allocate space for
56832   ** VdbeCursor/BtCursor structures. The blob of memory associated with 
56833   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
56834   ** stores the blob of memory associated with cursor 1, etc.
56835   **
56836   ** See also: allocateCursor().
56837   */
56838   nMem += nCursor;
56839
56840   /* Allocate space for memory registers, SQL variables, VDBE cursors and 
56841   ** an array to marshal SQL function arguments in. This is only done the
56842   ** first time this function is called for a given VDBE, not when it is
56843   ** being called from sqlite3_reset() to reset the virtual machine.
56844   */
56845   if( nVar>=0 && ALWAYS(db->mallocFailed==0) ){
56846     u8 *zCsr = (u8 *)&p->aOp[p->nOp];       /* Memory avaliable for alloation */
56847     u8 *zEnd = (u8 *)&p->aOp[p->nOpAlloc];  /* First byte past available mem */
56848     int nByte;                              /* How much extra memory needed */
56849
56850     resolveP2Values(p, &nArg);
56851     p->usesStmtJournal = (u8)usesStmtJournal;
56852     if( isExplain && nMem<10 ){
56853       nMem = 10;
56854     }
56855     memset(zCsr, 0, zEnd-zCsr);
56856     zCsr += (zCsr - (u8*)0)&7;
56857     assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
56858
56859     /* Memory for registers, parameters, cursor, etc, is allocated in two
56860     ** passes.  On the first pass, we try to reuse unused space at the 
56861     ** end of the opcode array.  If we are unable to satisfy all memory
56862     ** requirements by reusing the opcode array tail, then the second
56863     ** pass will fill in the rest using a fresh allocation.  
56864     **
56865     ** This two-pass approach that reuses as much memory as possible from
56866     ** the leftover space at the end of the opcode array can significantly
56867     ** reduce the amount of memory held by a prepared statement.
56868     */
56869     do {
56870       nByte = 0;
56871       p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
56872       p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
56873       p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
56874       p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
56875       p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
56876                             &zCsr, zEnd, &nByte);
56877       if( nByte ){
56878         p->pFree = sqlite3DbMallocZero(db, nByte);
56879       }
56880       zCsr = p->pFree;
56881       zEnd = &zCsr[nByte];
56882     }while( nByte && !db->mallocFailed );
56883
56884     p->nCursor = (u16)nCursor;
56885     if( p->aVar ){
56886       p->nVar = (ynVar)nVar;
56887       for(n=0; n<nVar; n++){
56888         p->aVar[n].flags = MEM_Null;
56889         p->aVar[n].db = db;
56890       }
56891     }
56892     if( p->aMem ){
56893       p->aMem--;                      /* aMem[] goes from 1..nMem */
56894       p->nMem = nMem;                 /*       not from 0..nMem-1 */
56895       for(n=1; n<=nMem; n++){
56896         p->aMem[n].flags = MEM_Null;
56897         p->aMem[n].db = db;
56898       }
56899     }
56900   }
56901 #ifdef SQLITE_DEBUG
56902   for(n=1; n<p->nMem; n++){
56903     assert( p->aMem[n].db==db );
56904   }
56905 #endif
56906
56907   p->pc = -1;
56908   p->rc = SQLITE_OK;
56909   p->errorAction = OE_Abort;
56910   p->explain |= isExplain;
56911   p->magic = VDBE_MAGIC_RUN;
56912   p->nChange = 0;
56913   p->cacheCtr = 1;
56914   p->minWriteFileFormat = 255;
56915   p->iStatement = 0;
56916   p->nFkConstraint = 0;
56917 #ifdef VDBE_PROFILE
56918   {
56919     int i;
56920     for(i=0; i<p->nOp; i++){
56921       p->aOp[i].cnt = 0;
56922       p->aOp[i].cycles = 0;
56923     }
56924   }
56925 #endif
56926 }
56927
56928 /*
56929 ** Close a VDBE cursor and release all the resources that cursor 
56930 ** happens to hold.
56931 */
56932 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
56933   if( pCx==0 ){
56934     return;
56935   }
56936   if( pCx->pBt ){
56937     sqlite3BtreeClose(pCx->pBt);
56938     /* The pCx->pCursor will be close automatically, if it exists, by
56939     ** the call above. */
56940   }else if( pCx->pCursor ){
56941     sqlite3BtreeCloseCursor(pCx->pCursor);
56942   }
56943 #ifndef SQLITE_OMIT_VIRTUALTABLE
56944   if( pCx->pVtabCursor ){
56945     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
56946     const sqlite3_module *pModule = pCx->pModule;
56947     p->inVtabMethod = 1;
56948     pModule->xClose(pVtabCursor);
56949     p->inVtabMethod = 0;
56950   }
56951 #endif
56952 }
56953
56954 /*
56955 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
56956 ** is used, for example, when a trigger sub-program is halted to restore
56957 ** control to the main program.
56958 */
56959 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
56960   Vdbe *v = pFrame->v;
56961   v->aOp = pFrame->aOp;
56962   v->nOp = pFrame->nOp;
56963   v->aMem = pFrame->aMem;
56964   v->nMem = pFrame->nMem;
56965   v->apCsr = pFrame->apCsr;
56966   v->nCursor = pFrame->nCursor;
56967   v->db->lastRowid = pFrame->lastRowid;
56968   v->nChange = pFrame->nChange;
56969   return pFrame->pc;
56970 }
56971
56972 /*
56973 ** Close all cursors.
56974 **
56975 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory 
56976 ** cell array. This is necessary as the memory cell array may contain
56977 ** pointers to VdbeFrame objects, which may in turn contain pointers to
56978 ** open cursors.
56979 */
56980 static void closeAllCursors(Vdbe *p){
56981   if( p->pFrame ){
56982     VdbeFrame *pFrame = p->pFrame;
56983     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
56984     sqlite3VdbeFrameRestore(pFrame);
56985   }
56986   p->pFrame = 0;
56987   p->nFrame = 0;
56988
56989   if( p->apCsr ){
56990     int i;
56991     for(i=0; i<p->nCursor; i++){
56992       VdbeCursor *pC = p->apCsr[i];
56993       if( pC ){
56994         sqlite3VdbeFreeCursor(p, pC);
56995         p->apCsr[i] = 0;
56996       }
56997     }
56998   }
56999   if( p->aMem ){
57000     releaseMemArray(&p->aMem[1], p->nMem);
57001   }
57002   while( p->pDelFrame ){
57003     VdbeFrame *pDel = p->pDelFrame;
57004     p->pDelFrame = pDel->pParent;
57005     sqlite3VdbeFrameDelete(pDel);
57006   }
57007 }
57008
57009 /*
57010 ** Clean up the VM after execution.
57011 **
57012 ** This routine will automatically close any cursors, lists, and/or
57013 ** sorters that were left open.  It also deletes the values of
57014 ** variables in the aVar[] array.
57015 */
57016 static void Cleanup(Vdbe *p){
57017   sqlite3 *db = p->db;
57018
57019 #ifdef SQLITE_DEBUG
57020   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and 
57021   ** Vdbe.aMem[] arrays have already been cleaned up.  */
57022   int i;
57023   for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
57024   for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
57025 #endif
57026
57027   sqlite3DbFree(db, p->zErrMsg);
57028   p->zErrMsg = 0;
57029   p->pResultSet = 0;
57030 }
57031
57032 /*
57033 ** Set the number of result columns that will be returned by this SQL
57034 ** statement. This is now set at compile time, rather than during
57035 ** execution of the vdbe program so that sqlite3_column_count() can
57036 ** be called on an SQL statement before sqlite3_step().
57037 */
57038 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
57039   Mem *pColName;
57040   int n;
57041   sqlite3 *db = p->db;
57042
57043   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
57044   sqlite3DbFree(db, p->aColName);
57045   n = nResColumn*COLNAME_N;
57046   p->nResColumn = (u16)nResColumn;
57047   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
57048   if( p->aColName==0 ) return;
57049   while( n-- > 0 ){
57050     pColName->flags = MEM_Null;
57051     pColName->db = p->db;
57052     pColName++;
57053   }
57054 }
57055
57056 /*
57057 ** Set the name of the idx'th column to be returned by the SQL statement.
57058 ** zName must be a pointer to a nul terminated string.
57059 **
57060 ** This call must be made after a call to sqlite3VdbeSetNumCols().
57061 **
57062 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
57063 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
57064 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
57065 */
57066 SQLITE_PRIVATE int sqlite3VdbeSetColName(
57067   Vdbe *p,                         /* Vdbe being configured */
57068   int idx,                         /* Index of column zName applies to */
57069   int var,                         /* One of the COLNAME_* constants */
57070   const char *zName,               /* Pointer to buffer containing name */
57071   void (*xDel)(void*)              /* Memory management strategy for zName */
57072 ){
57073   int rc;
57074   Mem *pColName;
57075   assert( idx<p->nResColumn );
57076   assert( var<COLNAME_N );
57077   if( p->db->mallocFailed ){
57078     assert( !zName || xDel!=SQLITE_DYNAMIC );
57079     return SQLITE_NOMEM;
57080   }
57081   assert( p->aColName!=0 );
57082   pColName = &(p->aColName[idx+var*p->nResColumn]);
57083   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
57084   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
57085   return rc;
57086 }
57087
57088 /*
57089 ** A read or write transaction may or may not be active on database handle
57090 ** db. If a transaction is active, commit it. If there is a
57091 ** write-transaction spanning more than one database file, this routine
57092 ** takes care of the master journal trickery.
57093 */
57094 static int vdbeCommit(sqlite3 *db, Vdbe *p){
57095   int i;
57096   int nTrans = 0;  /* Number of databases with an active write-transaction */
57097   int rc = SQLITE_OK;
57098   int needXcommit = 0;
57099
57100 #ifdef SQLITE_OMIT_VIRTUALTABLE
57101   /* With this option, sqlite3VtabSync() is defined to be simply 
57102   ** SQLITE_OK so p is not used. 
57103   */
57104   UNUSED_PARAMETER(p);
57105 #endif
57106
57107   /* Before doing anything else, call the xSync() callback for any
57108   ** virtual module tables written in this transaction. This has to
57109   ** be done before determining whether a master journal file is 
57110   ** required, as an xSync() callback may add an attached database
57111   ** to the transaction.
57112   */
57113   rc = sqlite3VtabSync(db, &p->zErrMsg);
57114
57115   /* This loop determines (a) if the commit hook should be invoked and
57116   ** (b) how many database files have open write transactions, not 
57117   ** including the temp database. (b) is important because if more than 
57118   ** one database file has an open write transaction, a master journal
57119   ** file is required for an atomic commit.
57120   */ 
57121   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
57122     Btree *pBt = db->aDb[i].pBt;
57123     if( sqlite3BtreeIsInTrans(pBt) ){
57124       needXcommit = 1;
57125       if( i!=1 ) nTrans++;
57126       rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
57127     }
57128   }
57129   if( rc!=SQLITE_OK ){
57130     return rc;
57131   }
57132
57133   /* If there are any write-transactions at all, invoke the commit hook */
57134   if( needXcommit && db->xCommitCallback ){
57135     rc = db->xCommitCallback(db->pCommitArg);
57136     if( rc ){
57137       return SQLITE_CONSTRAINT;
57138     }
57139   }
57140
57141   /* The simple case - no more than one database file (not counting the
57142   ** TEMP database) has a transaction active.   There is no need for the
57143   ** master-journal.
57144   **
57145   ** If the return value of sqlite3BtreeGetFilename() is a zero length
57146   ** string, it means the main database is :memory: or a temp file.  In 
57147   ** that case we do not support atomic multi-file commits, so use the 
57148   ** simple case then too.
57149   */
57150   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
57151    || nTrans<=1
57152   ){
57153     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
57154       Btree *pBt = db->aDb[i].pBt;
57155       if( pBt ){
57156         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
57157       }
57158     }
57159
57160     /* Do the commit only if all databases successfully complete phase 1. 
57161     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
57162     ** IO error while deleting or truncating a journal file. It is unlikely,
57163     ** but could happen. In this case abandon processing and return the error.
57164     */
57165     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
57166       Btree *pBt = db->aDb[i].pBt;
57167       if( pBt ){
57168         rc = sqlite3BtreeCommitPhaseTwo(pBt);
57169       }
57170     }
57171     if( rc==SQLITE_OK ){
57172       sqlite3VtabCommit(db);
57173     }
57174   }
57175
57176   /* The complex case - There is a multi-file write-transaction active.
57177   ** This requires a master journal file to ensure the transaction is
57178   ** committed atomicly.
57179   */
57180 #ifndef SQLITE_OMIT_DISKIO
57181   else{
57182     sqlite3_vfs *pVfs = db->pVfs;
57183     int needSync = 0;
57184     char *zMaster = 0;   /* File-name for the master journal */
57185     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
57186     sqlite3_file *pMaster = 0;
57187     i64 offset = 0;
57188     int res;
57189
57190     /* Select a master journal file name */
57191     do {
57192       u32 iRandom;
57193       sqlite3DbFree(db, zMaster);
57194       sqlite3_randomness(sizeof(iRandom), &iRandom);
57195       zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
57196       if( !zMaster ){
57197         return SQLITE_NOMEM;
57198       }
57199       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
57200     }while( rc==SQLITE_OK && res );
57201     if( rc==SQLITE_OK ){
57202       /* Open the master journal. */
57203       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
57204           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
57205           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
57206       );
57207     }
57208     if( rc!=SQLITE_OK ){
57209       sqlite3DbFree(db, zMaster);
57210       return rc;
57211     }
57212  
57213     /* Write the name of each database file in the transaction into the new
57214     ** master journal file. If an error occurs at this point close
57215     ** and delete the master journal file. All the individual journal files
57216     ** still have 'null' as the master journal pointer, so they will roll
57217     ** back independently if a failure occurs.
57218     */
57219     for(i=0; i<db->nDb; i++){
57220       Btree *pBt = db->aDb[i].pBt;
57221       if( sqlite3BtreeIsInTrans(pBt) ){
57222         char const *zFile = sqlite3BtreeGetJournalname(pBt);
57223         if( zFile==0 ){
57224           continue;  /* Ignore TEMP and :memory: databases */
57225         }
57226         assert( zFile[0]!=0 );
57227         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
57228           needSync = 1;
57229         }
57230         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
57231         offset += sqlite3Strlen30(zFile)+1;
57232         if( rc!=SQLITE_OK ){
57233           sqlite3OsCloseFree(pMaster);
57234           sqlite3OsDelete(pVfs, zMaster, 0);
57235           sqlite3DbFree(db, zMaster);
57236           return rc;
57237         }
57238       }
57239     }
57240
57241     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
57242     ** flag is set this is not required.
57243     */
57244     if( needSync 
57245      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
57246      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
57247     ){
57248       sqlite3OsCloseFree(pMaster);
57249       sqlite3OsDelete(pVfs, zMaster, 0);
57250       sqlite3DbFree(db, zMaster);
57251       return rc;
57252     }
57253
57254     /* Sync all the db files involved in the transaction. The same call
57255     ** sets the master journal pointer in each individual journal. If
57256     ** an error occurs here, do not delete the master journal file.
57257     **
57258     ** If the error occurs during the first call to
57259     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
57260     ** master journal file will be orphaned. But we cannot delete it,
57261     ** in case the master journal file name was written into the journal
57262     ** file before the failure occurred.
57263     */
57264     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
57265       Btree *pBt = db->aDb[i].pBt;
57266       if( pBt ){
57267         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
57268       }
57269     }
57270     sqlite3OsCloseFree(pMaster);
57271     assert( rc!=SQLITE_BUSY );
57272     if( rc!=SQLITE_OK ){
57273       sqlite3DbFree(db, zMaster);
57274       return rc;
57275     }
57276
57277     /* Delete the master journal file. This commits the transaction. After
57278     ** doing this the directory is synced again before any individual
57279     ** transaction files are deleted.
57280     */
57281     rc = sqlite3OsDelete(pVfs, zMaster, 1);
57282     sqlite3DbFree(db, zMaster);
57283     zMaster = 0;
57284     if( rc ){
57285       return rc;
57286     }
57287
57288     /* All files and directories have already been synced, so the following
57289     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
57290     ** deleting or truncating journals. If something goes wrong while
57291     ** this is happening we don't really care. The integrity of the
57292     ** transaction is already guaranteed, but some stray 'cold' journals
57293     ** may be lying around. Returning an error code won't help matters.
57294     */
57295     disable_simulated_io_errors();
57296     sqlite3BeginBenignMalloc();
57297     for(i=0; i<db->nDb; i++){ 
57298       Btree *pBt = db->aDb[i].pBt;
57299       if( pBt ){
57300         sqlite3BtreeCommitPhaseTwo(pBt);
57301       }
57302     }
57303     sqlite3EndBenignMalloc();
57304     enable_simulated_io_errors();
57305
57306     sqlite3VtabCommit(db);
57307   }
57308 #endif
57309
57310   return rc;
57311 }
57312
57313 /* 
57314 ** This routine checks that the sqlite3.activeVdbeCnt count variable
57315 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
57316 ** currently active. An assertion fails if the two counts do not match.
57317 ** This is an internal self-check only - it is not an essential processing
57318 ** step.
57319 **
57320 ** This is a no-op if NDEBUG is defined.
57321 */
57322 #ifndef NDEBUG
57323 static void checkActiveVdbeCnt(sqlite3 *db){
57324   Vdbe *p;
57325   int cnt = 0;
57326   int nWrite = 0;
57327   p = db->pVdbe;
57328   while( p ){
57329     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
57330       cnt++;
57331       if( p->readOnly==0 ) nWrite++;
57332     }
57333     p = p->pNext;
57334   }
57335   assert( cnt==db->activeVdbeCnt );
57336   assert( nWrite==db->writeVdbeCnt );
57337 }
57338 #else
57339 #define checkActiveVdbeCnt(x)
57340 #endif
57341
57342 /*
57343 ** For every Btree that in database connection db which 
57344 ** has been modified, "trip" or invalidate each cursor in
57345 ** that Btree might have been modified so that the cursor
57346 ** can never be used again.  This happens when a rollback
57347 *** occurs.  We have to trip all the other cursors, even
57348 ** cursor from other VMs in different database connections,
57349 ** so that none of them try to use the data at which they
57350 ** were pointing and which now may have been changed due
57351 ** to the rollback.
57352 **
57353 ** Remember that a rollback can delete tables complete and
57354 ** reorder rootpages.  So it is not sufficient just to save
57355 ** the state of the cursor.  We have to invalidate the cursor
57356 ** so that it is never used again.
57357 */
57358 static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
57359   int i;
57360   for(i=0; i<db->nDb; i++){
57361     Btree *p = db->aDb[i].pBt;
57362     if( p && sqlite3BtreeIsInTrans(p) ){
57363       sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
57364     }
57365   }
57366 }
57367
57368 /*
57369 ** If the Vdbe passed as the first argument opened a statement-transaction,
57370 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
57371 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
57372 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the 
57373 ** statement transaction is commtted.
57374 **
57375 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. 
57376 ** Otherwise SQLITE_OK.
57377 */
57378 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
57379   sqlite3 *const db = p->db;
57380   int rc = SQLITE_OK;
57381
57382   /* If p->iStatement is greater than zero, then this Vdbe opened a 
57383   ** statement transaction that should be closed here. The only exception
57384   ** is that an IO error may have occured, causing an emergency rollback.
57385   ** In this case (db->nStatement==0), and there is nothing to do.
57386   */
57387   if( db->nStatement && p->iStatement ){
57388     int i;
57389     const int iSavepoint = p->iStatement-1;
57390
57391     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
57392     assert( db->nStatement>0 );
57393     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
57394
57395     for(i=0; i<db->nDb; i++){ 
57396       int rc2 = SQLITE_OK;
57397       Btree *pBt = db->aDb[i].pBt;
57398       if( pBt ){
57399         if( eOp==SAVEPOINT_ROLLBACK ){
57400           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
57401         }
57402         if( rc2==SQLITE_OK ){
57403           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
57404         }
57405         if( rc==SQLITE_OK ){
57406           rc = rc2;
57407         }
57408       }
57409     }
57410     db->nStatement--;
57411     p->iStatement = 0;
57412
57413     /* If the statement transaction is being rolled back, also restore the 
57414     ** database handles deferred constraint counter to the value it had when 
57415     ** the statement transaction was opened.  */
57416     if( eOp==SAVEPOINT_ROLLBACK ){
57417       db->nDeferredCons = p->nStmtDefCons;
57418     }
57419   }
57420   return rc;
57421 }
57422
57423 /*
57424 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
57425 ** this routine obtains the mutex associated with each BtShared structure
57426 ** that may be accessed by the VM passed as an argument. In doing so it
57427 ** sets the BtShared.db member of each of the BtShared structures, ensuring
57428 ** that the correct busy-handler callback is invoked if required.
57429 **
57430 ** If SQLite is not threadsafe but does support shared-cache mode, then
57431 ** sqlite3BtreeEnterAll() is invoked to set the BtShared.db variables
57432 ** of all of BtShared structures accessible via the database handle 
57433 ** associated with the VM. Of course only a subset of these structures
57434 ** will be accessed by the VM, and we could use Vdbe.btreeMask to figure
57435 ** that subset out, but there is no advantage to doing so.
57436 **
57437 ** If SQLite is not threadsafe and does not support shared-cache mode, this
57438 ** function is a no-op.
57439 */
57440 #ifndef SQLITE_OMIT_SHARED_CACHE
57441 SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p){
57442 #if SQLITE_THREADSAFE
57443   sqlite3BtreeMutexArrayEnter(&p->aMutex);
57444 #else
57445   sqlite3BtreeEnterAll(p->db);
57446 #endif
57447 }
57448 #endif
57449
57450 /*
57451 ** This function is called when a transaction opened by the database 
57452 ** handle associated with the VM passed as an argument is about to be 
57453 ** committed. If there are outstanding deferred foreign key constraint
57454 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
57455 **
57456 ** If there are outstanding FK violations and this function returns 
57457 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
57458 ** an error message to it. Then return SQLITE_ERROR.
57459 */
57460 #ifndef SQLITE_OMIT_FOREIGN_KEY
57461 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
57462   sqlite3 *db = p->db;
57463   if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
57464     p->rc = SQLITE_CONSTRAINT;
57465     p->errorAction = OE_Abort;
57466     sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
57467     return SQLITE_ERROR;
57468   }
57469   return SQLITE_OK;
57470 }
57471 #endif
57472
57473 /*
57474 ** This routine is called the when a VDBE tries to halt.  If the VDBE
57475 ** has made changes and is in autocommit mode, then commit those
57476 ** changes.  If a rollback is needed, then do the rollback.
57477 **
57478 ** This routine is the only way to move the state of a VM from
57479 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
57480 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
57481 **
57482 ** Return an error code.  If the commit could not complete because of
57483 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
57484 ** means the close did not happen and needs to be repeated.
57485 */
57486 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
57487   int rc;                         /* Used to store transient return codes */
57488   sqlite3 *db = p->db;
57489
57490   /* This function contains the logic that determines if a statement or
57491   ** transaction will be committed or rolled back as a result of the
57492   ** execution of this virtual machine. 
57493   **
57494   ** If any of the following errors occur:
57495   **
57496   **     SQLITE_NOMEM
57497   **     SQLITE_IOERR
57498   **     SQLITE_FULL
57499   **     SQLITE_INTERRUPT
57500   **
57501   ** Then the internal cache might have been left in an inconsistent
57502   ** state.  We need to rollback the statement transaction, if there is
57503   ** one, or the complete transaction if there is no statement transaction.
57504   */
57505
57506   if( p->db->mallocFailed ){
57507     p->rc = SQLITE_NOMEM;
57508   }
57509   closeAllCursors(p);
57510   if( p->magic!=VDBE_MAGIC_RUN ){
57511     return SQLITE_OK;
57512   }
57513   checkActiveVdbeCnt(db);
57514
57515   /* No commit or rollback needed if the program never started */
57516   if( p->pc>=0 ){
57517     int mrc;   /* Primary error code from p->rc */
57518     int eStatementOp = 0;
57519     int isSpecialError;            /* Set to true if a 'special' error */
57520
57521     /* Lock all btrees used by the statement */
57522     sqlite3VdbeMutexArrayEnter(p);
57523
57524     /* Check for one of the special errors */
57525     mrc = p->rc & 0xff;
57526     assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
57527     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
57528                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
57529     if( isSpecialError ){
57530       /* If the query was read-only and the error code is SQLITE_INTERRUPT, 
57531       ** no rollback is necessary. Otherwise, at least a savepoint 
57532       ** transaction must be rolled back to restore the database to a 
57533       ** consistent state.
57534       **
57535       ** Even if the statement is read-only, it is important to perform
57536       ** a statement or transaction rollback operation. If the error 
57537       ** occured while writing to the journal, sub-journal or database
57538       ** file as part of an effort to free up cache space (see function
57539       ** pagerStress() in pager.c), the rollback is required to restore 
57540       ** the pager to a consistent state.
57541       */
57542       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
57543         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
57544           eStatementOp = SAVEPOINT_ROLLBACK;
57545         }else{
57546           /* We are forced to roll back the active transaction. Before doing
57547           ** so, abort any other statements this handle currently has active.
57548           */
57549           invalidateCursorsOnModifiedBtrees(db);
57550           sqlite3RollbackAll(db);
57551           sqlite3CloseSavepoints(db);
57552           db->autoCommit = 1;
57553         }
57554       }
57555     }
57556
57557     /* Check for immediate foreign key violations. */
57558     if( p->rc==SQLITE_OK ){
57559       sqlite3VdbeCheckFk(p, 0);
57560     }
57561   
57562     /* If the auto-commit flag is set and this is the only active writer 
57563     ** VM, then we do either a commit or rollback of the current transaction. 
57564     **
57565     ** Note: This block also runs if one of the special errors handled 
57566     ** above has occurred. 
57567     */
57568     if( !sqlite3VtabInSync(db) 
57569      && db->autoCommit 
57570      && db->writeVdbeCnt==(p->readOnly==0) 
57571     ){
57572       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
57573         if( sqlite3VdbeCheckFk(p, 1) ){
57574           sqlite3BtreeMutexArrayLeave(&p->aMutex);
57575           return SQLITE_ERROR;
57576         }
57577         /* The auto-commit flag is true, the vdbe program was successful 
57578         ** or hit an 'OR FAIL' constraint and there are no deferred foreign
57579         ** key constraints to hold up the transaction. This means a commit 
57580         ** is required.  */
57581         rc = vdbeCommit(db, p);
57582         if( rc==SQLITE_BUSY ){
57583           sqlite3BtreeMutexArrayLeave(&p->aMutex);
57584           return SQLITE_BUSY;
57585         }else if( rc!=SQLITE_OK ){
57586           p->rc = rc;
57587           sqlite3RollbackAll(db);
57588         }else{
57589           db->nDeferredCons = 0;
57590           sqlite3CommitInternalChanges(db);
57591         }
57592       }else{
57593         sqlite3RollbackAll(db);
57594       }
57595       db->nStatement = 0;
57596     }else if( eStatementOp==0 ){
57597       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
57598         eStatementOp = SAVEPOINT_RELEASE;
57599       }else if( p->errorAction==OE_Abort ){
57600         eStatementOp = SAVEPOINT_ROLLBACK;
57601       }else{
57602         invalidateCursorsOnModifiedBtrees(db);
57603         sqlite3RollbackAll(db);
57604         sqlite3CloseSavepoints(db);
57605         db->autoCommit = 1;
57606       }
57607     }
57608   
57609     /* If eStatementOp is non-zero, then a statement transaction needs to
57610     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
57611     ** do so. If this operation returns an error, and the current statement
57612     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
57613     ** current statement error code.
57614     **
57615     ** Note that sqlite3VdbeCloseStatement() can only fail if eStatementOp
57616     ** is SAVEPOINT_ROLLBACK.  But if p->rc==SQLITE_OK then eStatementOp
57617     ** must be SAVEPOINT_RELEASE.  Hence the NEVER(p->rc==SQLITE_OK) in 
57618     ** the following code.
57619     */
57620     if( eStatementOp ){
57621       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
57622       if( rc ){
57623         assert( eStatementOp==SAVEPOINT_ROLLBACK );
57624         if( NEVER(p->rc==SQLITE_OK) || p->rc==SQLITE_CONSTRAINT ){
57625           p->rc = rc;
57626           sqlite3DbFree(db, p->zErrMsg);
57627           p->zErrMsg = 0;
57628         }
57629         invalidateCursorsOnModifiedBtrees(db);
57630         sqlite3RollbackAll(db);
57631         sqlite3CloseSavepoints(db);
57632         db->autoCommit = 1;
57633       }
57634     }
57635   
57636     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
57637     ** has been rolled back, update the database connection change-counter. 
57638     */
57639     if( p->changeCntOn ){
57640       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
57641         sqlite3VdbeSetChanges(db, p->nChange);
57642       }else{
57643         sqlite3VdbeSetChanges(db, 0);
57644       }
57645       p->nChange = 0;
57646     }
57647   
57648     /* Rollback or commit any schema changes that occurred. */
57649     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
57650       sqlite3ResetInternalSchema(db, 0);
57651       db->flags = (db->flags | SQLITE_InternChanges);
57652     }
57653
57654     /* Release the locks */
57655     sqlite3BtreeMutexArrayLeave(&p->aMutex);
57656   }
57657
57658   /* We have successfully halted and closed the VM.  Record this fact. */
57659   if( p->pc>=0 ){
57660     db->activeVdbeCnt--;
57661     if( !p->readOnly ){
57662       db->writeVdbeCnt--;
57663     }
57664     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
57665   }
57666   p->magic = VDBE_MAGIC_HALT;
57667   checkActiveVdbeCnt(db);
57668   if( p->db->mallocFailed ){
57669     p->rc = SQLITE_NOMEM;
57670   }
57671
57672   /* If the auto-commit flag is set to true, then any locks that were held
57673   ** by connection db have now been released. Call sqlite3ConnectionUnlocked() 
57674   ** to invoke any required unlock-notify callbacks.
57675   */
57676   if( db->autoCommit ){
57677     sqlite3ConnectionUnlocked(db);
57678   }
57679
57680   assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
57681   return SQLITE_OK;
57682 }
57683
57684
57685 /*
57686 ** Each VDBE holds the result of the most recent sqlite3_step() call
57687 ** in p->rc.  This routine sets that result back to SQLITE_OK.
57688 */
57689 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
57690   p->rc = SQLITE_OK;
57691 }
57692
57693 /*
57694 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
57695 ** Write any error messages into *pzErrMsg.  Return the result code.
57696 **
57697 ** After this routine is run, the VDBE should be ready to be executed
57698 ** again.
57699 **
57700 ** To look at it another way, this routine resets the state of the
57701 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
57702 ** VDBE_MAGIC_INIT.
57703 */
57704 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
57705   sqlite3 *db;
57706   db = p->db;
57707
57708   /* If the VM did not run to completion or if it encountered an
57709   ** error, then it might not have been halted properly.  So halt
57710   ** it now.
57711   */
57712   sqlite3VdbeHalt(p);
57713
57714   /* If the VDBE has be run even partially, then transfer the error code
57715   ** and error message from the VDBE into the main database structure.  But
57716   ** if the VDBE has just been set to run but has not actually executed any
57717   ** instructions yet, leave the main database error information unchanged.
57718   */
57719   if( p->pc>=0 ){
57720     if( p->zErrMsg ){
57721       sqlite3BeginBenignMalloc();
57722       sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
57723       sqlite3EndBenignMalloc();
57724       db->errCode = p->rc;
57725       sqlite3DbFree(db, p->zErrMsg);
57726       p->zErrMsg = 0;
57727     }else if( p->rc ){
57728       sqlite3Error(db, p->rc, 0);
57729     }else{
57730       sqlite3Error(db, SQLITE_OK, 0);
57731     }
57732     if( p->runOnlyOnce ) p->expired = 1;
57733   }else if( p->rc && p->expired ){
57734     /* The expired flag was set on the VDBE before the first call
57735     ** to sqlite3_step(). For consistency (since sqlite3_step() was
57736     ** called), set the database error in this case as well.
57737     */
57738     sqlite3Error(db, p->rc, 0);
57739     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
57740     sqlite3DbFree(db, p->zErrMsg);
57741     p->zErrMsg = 0;
57742   }
57743
57744   /* Reclaim all memory used by the VDBE
57745   */
57746   Cleanup(p);
57747
57748   /* Save profiling information from this VDBE run.
57749   */
57750 #ifdef VDBE_PROFILE
57751   {
57752     FILE *out = fopen("vdbe_profile.out", "a");
57753     if( out ){
57754       int i;
57755       fprintf(out, "---- ");
57756       for(i=0; i<p->nOp; i++){
57757         fprintf(out, "%02x", p->aOp[i].opcode);
57758       }
57759       fprintf(out, "\n");
57760       for(i=0; i<p->nOp; i++){
57761         fprintf(out, "%6d %10lld %8lld ",
57762            p->aOp[i].cnt,
57763            p->aOp[i].cycles,
57764            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
57765         );
57766         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
57767       }
57768       fclose(out);
57769     }
57770   }
57771 #endif
57772   p->magic = VDBE_MAGIC_INIT;
57773   return p->rc & db->errMask;
57774 }
57775  
57776 /*
57777 ** Clean up and delete a VDBE after execution.  Return an integer which is
57778 ** the result code.  Write any error message text into *pzErrMsg.
57779 */
57780 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
57781   int rc = SQLITE_OK;
57782   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
57783     rc = sqlite3VdbeReset(p);
57784     assert( (rc & p->db->errMask)==rc );
57785   }
57786   sqlite3VdbeDelete(p);
57787   return rc;
57788 }
57789
57790 /*
57791 ** Call the destructor for each auxdata entry in pVdbeFunc for which
57792 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
57793 ** are always destroyed.  To destroy all auxdata entries, call this
57794 ** routine with mask==0.
57795 */
57796 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
57797   int i;
57798   for(i=0; i<pVdbeFunc->nAux; i++){
57799     struct AuxData *pAux = &pVdbeFunc->apAux[i];
57800     if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
57801       if( pAux->xDelete ){
57802         pAux->xDelete(pAux->pAux);
57803       }
57804       pAux->pAux = 0;
57805     }
57806   }
57807 }
57808
57809 /*
57810 ** Free all memory associated with the Vdbe passed as the second argument.
57811 ** The difference between this function and sqlite3VdbeDelete() is that
57812 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
57813 ** the database connection.
57814 */
57815 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3 *db, Vdbe *p){
57816   SubProgram *pSub, *pNext;
57817   assert( p->db==0 || p->db==db );
57818   releaseMemArray(p->aVar, p->nVar);
57819   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
57820   for(pSub=p->pProgram; pSub; pSub=pNext){
57821     pNext = pSub->pNext;
57822     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
57823     sqlite3DbFree(db, pSub);
57824   }
57825   vdbeFreeOpArray(db, p->aOp, p->nOp);
57826   sqlite3DbFree(db, p->aLabel);
57827   sqlite3DbFree(db, p->aColName);
57828   sqlite3DbFree(db, p->zSql);
57829   sqlite3DbFree(db, p->pFree);
57830   sqlite3DbFree(db, p);
57831 }
57832
57833 /*
57834 ** Delete an entire VDBE.
57835 */
57836 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
57837   sqlite3 *db;
57838
57839   if( NEVER(p==0) ) return;
57840   db = p->db;
57841   if( p->pPrev ){
57842     p->pPrev->pNext = p->pNext;
57843   }else{
57844     assert( db->pVdbe==p );
57845     db->pVdbe = p->pNext;
57846   }
57847   if( p->pNext ){
57848     p->pNext->pPrev = p->pPrev;
57849   }
57850   p->magic = VDBE_MAGIC_DEAD;
57851   p->db = 0;
57852   sqlite3VdbeDeleteObject(db, p);
57853 }
57854
57855 /*
57856 ** Make sure the cursor p is ready to read or write the row to which it
57857 ** was last positioned.  Return an error code if an OOM fault or I/O error
57858 ** prevents us from positioning the cursor to its correct position.
57859 **
57860 ** If a MoveTo operation is pending on the given cursor, then do that
57861 ** MoveTo now.  If no move is pending, check to see if the row has been
57862 ** deleted out from under the cursor and if it has, mark the row as
57863 ** a NULL row.
57864 **
57865 ** If the cursor is already pointing to the correct row and that row has
57866 ** not been deleted out from under the cursor, then this routine is a no-op.
57867 */
57868 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
57869   if( p->deferredMoveto ){
57870     int res, rc;
57871 #ifdef SQLITE_TEST
57872     extern int sqlite3_search_count;
57873 #endif
57874     assert( p->isTable );
57875     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
57876     if( rc ) return rc;
57877     p->lastRowid = p->movetoTarget;
57878     if( res!=0 ) return SQLITE_CORRUPT_BKPT;
57879     p->rowidIsValid = 1;
57880 #ifdef SQLITE_TEST
57881     sqlite3_search_count++;
57882 #endif
57883     p->deferredMoveto = 0;
57884     p->cacheStatus = CACHE_STALE;
57885   }else if( ALWAYS(p->pCursor) ){
57886     int hasMoved;
57887     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
57888     if( rc ) return rc;
57889     if( hasMoved ){
57890       p->cacheStatus = CACHE_STALE;
57891       p->nullRow = 1;
57892     }
57893   }
57894   return SQLITE_OK;
57895 }
57896
57897 /*
57898 ** The following functions:
57899 **
57900 ** sqlite3VdbeSerialType()
57901 ** sqlite3VdbeSerialTypeLen()
57902 ** sqlite3VdbeSerialLen()
57903 ** sqlite3VdbeSerialPut()
57904 ** sqlite3VdbeSerialGet()
57905 **
57906 ** encapsulate the code that serializes values for storage in SQLite
57907 ** data and index records. Each serialized value consists of a
57908 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
57909 ** integer, stored as a varint.
57910 **
57911 ** In an SQLite index record, the serial type is stored directly before
57912 ** the blob of data that it corresponds to. In a table record, all serial
57913 ** types are stored at the start of the record, and the blobs of data at
57914 ** the end. Hence these functions allow the caller to handle the
57915 ** serial-type and data blob seperately.
57916 **
57917 ** The following table describes the various storage classes for data:
57918 **
57919 **   serial type        bytes of data      type
57920 **   --------------     ---------------    ---------------
57921 **      0                     0            NULL
57922 **      1                     1            signed integer
57923 **      2                     2            signed integer
57924 **      3                     3            signed integer
57925 **      4                     4            signed integer
57926 **      5                     6            signed integer
57927 **      6                     8            signed integer
57928 **      7                     8            IEEE float
57929 **      8                     0            Integer constant 0
57930 **      9                     0            Integer constant 1
57931 **     10,11                               reserved for expansion
57932 **    N>=12 and even       (N-12)/2        BLOB
57933 **    N>=13 and odd        (N-13)/2        text
57934 **
57935 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
57936 ** of SQLite will not understand those serial types.
57937 */
57938
57939 /*
57940 ** Return the serial-type for the value stored in pMem.
57941 */
57942 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
57943   int flags = pMem->flags;
57944   int n;
57945
57946   if( flags&MEM_Null ){
57947     return 0;
57948   }
57949   if( flags&MEM_Int ){
57950     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
57951 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
57952     i64 i = pMem->u.i;
57953     u64 u;
57954     if( file_format>=4 && (i&1)==i ){
57955       return 8+(u32)i;
57956     }
57957     u = i<0 ? -i : i;
57958     if( u<=127 ) return 1;
57959     if( u<=32767 ) return 2;
57960     if( u<=8388607 ) return 3;
57961     if( u<=2147483647 ) return 4;
57962     if( u<=MAX_6BYTE ) return 5;
57963     return 6;
57964   }
57965   if( flags&MEM_Real ){
57966     return 7;
57967   }
57968   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
57969   n = pMem->n;
57970   if( flags & MEM_Zero ){
57971     n += pMem->u.nZero;
57972   }
57973   assert( n>=0 );
57974   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
57975 }
57976
57977 /*
57978 ** Return the length of the data corresponding to the supplied serial-type.
57979 */
57980 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
57981   if( serial_type>=12 ){
57982     return (serial_type-12)/2;
57983   }else{
57984     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
57985     return aSize[serial_type];
57986   }
57987 }
57988
57989 /*
57990 ** If we are on an architecture with mixed-endian floating 
57991 ** points (ex: ARM7) then swap the lower 4 bytes with the 
57992 ** upper 4 bytes.  Return the result.
57993 **
57994 ** For most architectures, this is a no-op.
57995 **
57996 ** (later):  It is reported to me that the mixed-endian problem
57997 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
57998 ** that early versions of GCC stored the two words of a 64-bit
57999 ** float in the wrong order.  And that error has been propagated
58000 ** ever since.  The blame is not necessarily with GCC, though.
58001 ** GCC might have just copying the problem from a prior compiler.
58002 ** I am also told that newer versions of GCC that follow a different
58003 ** ABI get the byte order right.
58004 **
58005 ** Developers using SQLite on an ARM7 should compile and run their
58006 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
58007 ** enabled, some asserts below will ensure that the byte order of
58008 ** floating point values is correct.
58009 **
58010 ** (2007-08-30)  Frank van Vugt has studied this problem closely
58011 ** and has send his findings to the SQLite developers.  Frank
58012 ** writes that some Linux kernels offer floating point hardware
58013 ** emulation that uses only 32-bit mantissas instead of a full 
58014 ** 48-bits as required by the IEEE standard.  (This is the
58015 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
58016 ** byte swapping becomes very complicated.  To avoid problems,
58017 ** the necessary byte swapping is carried out using a 64-bit integer
58018 ** rather than a 64-bit float.  Frank assures us that the code here
58019 ** works for him.  We, the developers, have no way to independently
58020 ** verify this, but Frank seems to know what he is talking about
58021 ** so we trust him.
58022 */
58023 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
58024 static u64 floatSwap(u64 in){
58025   union {
58026     u64 r;
58027     u32 i[2];
58028   } u;
58029   u32 t;
58030
58031   u.r = in;
58032   t = u.i[0];
58033   u.i[0] = u.i[1];
58034   u.i[1] = t;
58035   return u.r;
58036 }
58037 # define swapMixedEndianFloat(X)  X = floatSwap(X)
58038 #else
58039 # define swapMixedEndianFloat(X)
58040 #endif
58041
58042 /*
58043 ** Write the serialized data blob for the value stored in pMem into 
58044 ** buf. It is assumed that the caller has allocated sufficient space.
58045 ** Return the number of bytes written.
58046 **
58047 ** nBuf is the amount of space left in buf[].  nBuf must always be
58048 ** large enough to hold the entire field.  Except, if the field is
58049 ** a blob with a zero-filled tail, then buf[] might be just the right
58050 ** size to hold everything except for the zero-filled tail.  If buf[]
58051 ** is only big enough to hold the non-zero prefix, then only write that
58052 ** prefix into buf[].  But if buf[] is large enough to hold both the
58053 ** prefix and the tail then write the prefix and set the tail to all
58054 ** zeros.
58055 **
58056 ** Return the number of bytes actually written into buf[].  The number
58057 ** of bytes in the zero-filled tail is included in the return value only
58058 ** if those bytes were zeroed in buf[].
58059 */ 
58060 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
58061   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
58062   u32 len;
58063
58064   /* Integer and Real */
58065   if( serial_type<=7 && serial_type>0 ){
58066     u64 v;
58067     u32 i;
58068     if( serial_type==7 ){
58069       assert( sizeof(v)==sizeof(pMem->r) );
58070       memcpy(&v, &pMem->r, sizeof(v));
58071       swapMixedEndianFloat(v);
58072     }else{
58073       v = pMem->u.i;
58074     }
58075     len = i = sqlite3VdbeSerialTypeLen(serial_type);
58076     assert( len<=(u32)nBuf );
58077     while( i-- ){
58078       buf[i] = (u8)(v&0xFF);
58079       v >>= 8;
58080     }
58081     return len;
58082   }
58083
58084   /* String or blob */
58085   if( serial_type>=12 ){
58086     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
58087              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
58088     assert( pMem->n<=nBuf );
58089     len = pMem->n;
58090     memcpy(buf, pMem->z, len);
58091     if( pMem->flags & MEM_Zero ){
58092       len += pMem->u.nZero;
58093       assert( nBuf>=0 );
58094       if( len > (u32)nBuf ){
58095         len = (u32)nBuf;
58096       }
58097       memset(&buf[pMem->n], 0, len-pMem->n);
58098     }
58099     return len;
58100   }
58101
58102   /* NULL or constants 0 or 1 */
58103   return 0;
58104 }
58105
58106 /*
58107 ** Deserialize the data blob pointed to by buf as serial type serial_type
58108 ** and store the result in pMem.  Return the number of bytes read.
58109 */ 
58110 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
58111   const unsigned char *buf,     /* Buffer to deserialize from */
58112   u32 serial_type,              /* Serial type to deserialize */
58113   Mem *pMem                     /* Memory cell to write value into */
58114 ){
58115   switch( serial_type ){
58116     case 10:   /* Reserved for future use */
58117     case 11:   /* Reserved for future use */
58118     case 0: {  /* NULL */
58119       pMem->flags = MEM_Null;
58120       break;
58121     }
58122     case 1: { /* 1-byte signed integer */
58123       pMem->u.i = (signed char)buf[0];
58124       pMem->flags = MEM_Int;
58125       return 1;
58126     }
58127     case 2: { /* 2-byte signed integer */
58128       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
58129       pMem->flags = MEM_Int;
58130       return 2;
58131     }
58132     case 3: { /* 3-byte signed integer */
58133       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
58134       pMem->flags = MEM_Int;
58135       return 3;
58136     }
58137     case 4: { /* 4-byte signed integer */
58138       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
58139       pMem->flags = MEM_Int;
58140       return 4;
58141     }
58142     case 5: { /* 6-byte signed integer */
58143       u64 x = (((signed char)buf[0])<<8) | buf[1];
58144       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
58145       x = (x<<32) | y;
58146       pMem->u.i = *(i64*)&x;
58147       pMem->flags = MEM_Int;
58148       return 6;
58149     }
58150     case 6:   /* 8-byte signed integer */
58151     case 7: { /* IEEE floating point */
58152       u64 x;
58153       u32 y;
58154 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
58155       /* Verify that integers and floating point values use the same
58156       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
58157       ** defined that 64-bit floating point values really are mixed
58158       ** endian.
58159       */
58160       static const u64 t1 = ((u64)0x3ff00000)<<32;
58161       static const double r1 = 1.0;
58162       u64 t2 = t1;
58163       swapMixedEndianFloat(t2);
58164       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
58165 #endif
58166
58167       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
58168       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
58169       x = (x<<32) | y;
58170       if( serial_type==6 ){
58171         pMem->u.i = *(i64*)&x;
58172         pMem->flags = MEM_Int;
58173       }else{
58174         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
58175         swapMixedEndianFloat(x);
58176         memcpy(&pMem->r, &x, sizeof(x));
58177         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
58178       }
58179       return 8;
58180     }
58181     case 8:    /* Integer 0 */
58182     case 9: {  /* Integer 1 */
58183       pMem->u.i = serial_type-8;
58184       pMem->flags = MEM_Int;
58185       return 0;
58186     }
58187     default: {
58188       u32 len = (serial_type-12)/2;
58189       pMem->z = (char *)buf;
58190       pMem->n = len;
58191       pMem->xDel = 0;
58192       if( serial_type&0x01 ){
58193         pMem->flags = MEM_Str | MEM_Ephem;
58194       }else{
58195         pMem->flags = MEM_Blob | MEM_Ephem;
58196       }
58197       return len;
58198     }
58199   }
58200   return 0;
58201 }
58202
58203
58204 /*
58205 ** Given the nKey-byte encoding of a record in pKey[], parse the
58206 ** record into a UnpackedRecord structure.  Return a pointer to
58207 ** that structure.
58208 **
58209 ** The calling function might provide szSpace bytes of memory
58210 ** space at pSpace.  This space can be used to hold the returned
58211 ** VDbeParsedRecord structure if it is large enough.  If it is
58212 ** not big enough, space is obtained from sqlite3_malloc().
58213 **
58214 ** The returned structure should be closed by a call to
58215 ** sqlite3VdbeDeleteUnpackedRecord().
58216 */ 
58217 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
58218   KeyInfo *pKeyInfo,     /* Information about the record format */
58219   int nKey,              /* Size of the binary record */
58220   const void *pKey,      /* The binary record */
58221   char *pSpace,          /* Unaligned space available to hold the object */
58222   int szSpace            /* Size of pSpace[] in bytes */
58223 ){
58224   const unsigned char *aKey = (const unsigned char *)pKey;
58225   UnpackedRecord *p;  /* The unpacked record that we will return */
58226   int nByte;          /* Memory space needed to hold p, in bytes */
58227   int d;
58228   u32 idx;
58229   u16 u;              /* Unsigned loop counter */
58230   u32 szHdr;
58231   Mem *pMem;
58232   int nOff;           /* Increase pSpace by this much to 8-byte align it */
58233   
58234   /*
58235   ** We want to shift the pointer pSpace up such that it is 8-byte aligned.
58236   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift 
58237   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
58238   */
58239   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
58240   pSpace += nOff;
58241   szSpace -= nOff;
58242   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
58243   if( nByte>szSpace ){
58244     p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
58245     if( p==0 ) return 0;
58246     p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
58247   }else{
58248     p = (UnpackedRecord*)pSpace;
58249     p->flags = UNPACKED_NEED_DESTROY;
58250   }
58251   p->pKeyInfo = pKeyInfo;
58252   p->nField = pKeyInfo->nField + 1;
58253   p->aMem = pMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
58254   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58255   idx = getVarint32(aKey, szHdr);
58256   d = szHdr;
58257   u = 0;
58258   while( idx<szHdr && u<p->nField && d<=nKey ){
58259     u32 serial_type;
58260
58261     idx += getVarint32(&aKey[idx], serial_type);
58262     pMem->enc = pKeyInfo->enc;
58263     pMem->db = pKeyInfo->db;
58264     pMem->flags = 0;
58265     pMem->zMalloc = 0;
58266     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
58267     pMem++;
58268     u++;
58269   }
58270   assert( u<=pKeyInfo->nField + 1 );
58271   p->nField = u;
58272   return (void*)p;
58273 }
58274
58275 /*
58276 ** This routine destroys a UnpackedRecord object.
58277 */
58278 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
58279   int i;
58280   Mem *pMem;
58281
58282   assert( p!=0 );
58283   assert( p->flags & UNPACKED_NEED_DESTROY );
58284   for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
58285     /* The unpacked record is always constructed by the
58286     ** sqlite3VdbeUnpackRecord() function above, which makes all
58287     ** strings and blobs static.  And none of the elements are
58288     ** ever transformed, so there is never anything to delete.
58289     */
58290     if( NEVER(pMem->zMalloc) ) sqlite3VdbeMemRelease(pMem);
58291   }
58292   if( p->flags & UNPACKED_NEED_FREE ){
58293     sqlite3DbFree(p->pKeyInfo->db, p);
58294   }
58295 }
58296
58297 /*
58298 ** This function compares the two table rows or index records
58299 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
58300 ** or positive integer if key1 is less than, equal to or 
58301 ** greater than key2.  The {nKey1, pKey1} key must be a blob
58302 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
58303 ** key must be a parsed key such as obtained from
58304 ** sqlite3VdbeParseRecord.
58305 **
58306 ** Key1 and Key2 do not have to contain the same number of fields.
58307 ** The key with fewer fields is usually compares less than the 
58308 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
58309 ** and the common prefixes are equal, then key1 is less than key2.
58310 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
58311 ** equal, then the keys are considered to be equal and
58312 ** the parts beyond the common prefix are ignored.
58313 **
58314 ** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
58315 ** the header of pKey1 is ignored.  It is assumed that pKey1 is
58316 ** an index key, and thus ends with a rowid value.  The last byte
58317 ** of the header will therefore be the serial type of the rowid:
58318 ** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
58319 ** The serial type of the final rowid will always be a single byte.
58320 ** By ignoring this last byte of the header, we force the comparison
58321 ** to ignore the rowid at the end of key1.
58322 */
58323 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
58324   int nKey1, const void *pKey1, /* Left key */
58325   UnpackedRecord *pPKey2        /* Right key */
58326 ){
58327   int d1;            /* Offset into aKey[] of next data element */
58328   u32 idx1;          /* Offset into aKey[] of next header element */
58329   u32 szHdr1;        /* Number of bytes in header */
58330   int i = 0;
58331   int nField;
58332   int rc = 0;
58333   const unsigned char *aKey1 = (const unsigned char *)pKey1;
58334   KeyInfo *pKeyInfo;
58335   Mem mem1;
58336
58337   pKeyInfo = pPKey2->pKeyInfo;
58338   mem1.enc = pKeyInfo->enc;
58339   mem1.db = pKeyInfo->db;
58340   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
58341   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
58342
58343   /* Compilers may complain that mem1.u.i is potentially uninitialized.
58344   ** We could initialize it, as shown here, to silence those complaints.
58345   ** But in fact, mem1.u.i will never actually be used initialized, and doing 
58346   ** the unnecessary initialization has a measurable negative performance
58347   ** impact, since this routine is a very high runner.  And so, we choose
58348   ** to ignore the compiler warnings and leave this variable uninitialized.
58349   */
58350   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
58351   
58352   idx1 = getVarint32(aKey1, szHdr1);
58353   d1 = szHdr1;
58354   if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
58355     szHdr1--;
58356   }
58357   nField = pKeyInfo->nField;
58358   while( idx1<szHdr1 && i<pPKey2->nField ){
58359     u32 serial_type1;
58360
58361     /* Read the serial types for the next element in each key. */
58362     idx1 += getVarint32( aKey1+idx1, serial_type1 );
58363     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
58364
58365     /* Extract the values to be compared.
58366     */
58367     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
58368
58369     /* Do the comparison
58370     */
58371     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
58372                            i<nField ? pKeyInfo->aColl[i] : 0);
58373     if( rc!=0 ){
58374       assert( mem1.zMalloc==0 );  /* See comment below */
58375
58376       /* Invert the result if we are using DESC sort order. */
58377       if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
58378         rc = -rc;
58379       }
58380     
58381       /* If the PREFIX_SEARCH flag is set and all fields except the final
58382       ** rowid field were equal, then clear the PREFIX_SEARCH flag and set 
58383       ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
58384       ** This is used by the OP_IsUnique opcode.
58385       */
58386       if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
58387         assert( idx1==szHdr1 && rc );
58388         assert( mem1.flags & MEM_Int );
58389         pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
58390         pPKey2->rowid = mem1.u.i;
58391       }
58392     
58393       return rc;
58394     }
58395     i++;
58396   }
58397
58398   /* No memory allocation is ever used on mem1.  Prove this using
58399   ** the following assert().  If the assert() fails, it indicates a
58400   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
58401   */
58402   assert( mem1.zMalloc==0 );
58403
58404   /* rc==0 here means that one of the keys ran out of fields and
58405   ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
58406   ** flag is set, then break the tie by treating key2 as larger.
58407   ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
58408   ** are considered to be equal.  Otherwise, the longer key is the 
58409   ** larger.  As it happens, the pPKey2 will always be the longer
58410   ** if there is a difference.
58411   */
58412   assert( rc==0 );
58413   if( pPKey2->flags & UNPACKED_INCRKEY ){
58414     rc = -1;
58415   }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
58416     /* Leave rc==0 */
58417   }else if( idx1<szHdr1 ){
58418     rc = 1;
58419   }
58420   return rc;
58421 }
58422  
58423
58424 /*
58425 ** pCur points at an index entry created using the OP_MakeRecord opcode.
58426 ** Read the rowid (the last field in the record) and store it in *rowid.
58427 ** Return SQLITE_OK if everything works, or an error code otherwise.
58428 **
58429 ** pCur might be pointing to text obtained from a corrupt database file.
58430 ** So the content cannot be trusted.  Do appropriate checks on the content.
58431 */
58432 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
58433   i64 nCellKey = 0;
58434   int rc;
58435   u32 szHdr;        /* Size of the header */
58436   u32 typeRowid;    /* Serial type of the rowid */
58437   u32 lenRowid;     /* Size of the rowid */
58438   Mem m, v;
58439
58440   UNUSED_PARAMETER(db);
58441
58442   /* Get the size of the index entry.  Only indices entries of less
58443   ** than 2GiB are support - anything large must be database corruption.
58444   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
58445   ** this code can safely assume that nCellKey is 32-bits  
58446   */
58447   assert( sqlite3BtreeCursorIsValid(pCur) );
58448   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
58449   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
58450   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
58451
58452   /* Read in the complete content of the index entry */
58453   memset(&m, 0, sizeof(m));
58454   rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
58455   if( rc ){
58456     return rc;
58457   }
58458
58459   /* The index entry must begin with a header size */
58460   (void)getVarint32((u8*)m.z, szHdr);
58461   testcase( szHdr==3 );
58462   testcase( szHdr==m.n );
58463   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
58464     goto idx_rowid_corruption;
58465   }
58466
58467   /* The last field of the index should be an integer - the ROWID.
58468   ** Verify that the last entry really is an integer. */
58469   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
58470   testcase( typeRowid==1 );
58471   testcase( typeRowid==2 );
58472   testcase( typeRowid==3 );
58473   testcase( typeRowid==4 );
58474   testcase( typeRowid==5 );
58475   testcase( typeRowid==6 );
58476   testcase( typeRowid==8 );
58477   testcase( typeRowid==9 );
58478   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
58479     goto idx_rowid_corruption;
58480   }
58481   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
58482   testcase( (u32)m.n==szHdr+lenRowid );
58483   if( unlikely((u32)m.n<szHdr+lenRowid) ){
58484     goto idx_rowid_corruption;
58485   }
58486
58487   /* Fetch the integer off the end of the index record */
58488   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
58489   *rowid = v.u.i;
58490   sqlite3VdbeMemRelease(&m);
58491   return SQLITE_OK;
58492
58493   /* Jump here if database corruption is detected after m has been
58494   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
58495 idx_rowid_corruption:
58496   testcase( m.zMalloc!=0 );
58497   sqlite3VdbeMemRelease(&m);
58498   return SQLITE_CORRUPT_BKPT;
58499 }
58500
58501 /*
58502 ** Compare the key of the index entry that cursor pC is pointing to against
58503 ** the key string in pUnpacked.  Write into *pRes a number
58504 ** that is negative, zero, or positive if pC is less than, equal to,
58505 ** or greater than pUnpacked.  Return SQLITE_OK on success.
58506 **
58507 ** pUnpacked is either created without a rowid or is truncated so that it
58508 ** omits the rowid at the end.  The rowid at the end of the index entry
58509 ** is ignored as well.  Hence, this routine only compares the prefixes 
58510 ** of the keys prior to the final rowid, not the entire key.
58511 */
58512 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
58513   VdbeCursor *pC,             /* The cursor to compare against */
58514   UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
58515   int *res                    /* Write the comparison result here */
58516 ){
58517   i64 nCellKey = 0;
58518   int rc;
58519   BtCursor *pCur = pC->pCursor;
58520   Mem m;
58521
58522   assert( sqlite3BtreeCursorIsValid(pCur) );
58523   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
58524   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
58525   /* nCellKey will always be between 0 and 0xffffffff because of the say
58526   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
58527   if( nCellKey<=0 || nCellKey>0x7fffffff ){
58528     *res = 0;
58529     return SQLITE_CORRUPT_BKPT;
58530   }
58531   memset(&m, 0, sizeof(m));
58532   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
58533   if( rc ){
58534     return rc;
58535   }
58536   assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
58537   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
58538   sqlite3VdbeMemRelease(&m);
58539   return SQLITE_OK;
58540 }
58541
58542 /*
58543 ** This routine sets the value to be returned by subsequent calls to
58544 ** sqlite3_changes() on the database handle 'db'. 
58545 */
58546 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
58547   assert( sqlite3_mutex_held(db->mutex) );
58548   db->nChange = nChange;
58549   db->nTotalChange += nChange;
58550 }
58551
58552 /*
58553 ** Set a flag in the vdbe to update the change counter when it is finalised
58554 ** or reset.
58555 */
58556 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
58557   v->changeCntOn = 1;
58558 }
58559
58560 /*
58561 ** Mark every prepared statement associated with a database connection
58562 ** as expired.
58563 **
58564 ** An expired statement means that recompilation of the statement is
58565 ** recommend.  Statements expire when things happen that make their
58566 ** programs obsolete.  Removing user-defined functions or collating
58567 ** sequences, or changing an authorization function are the types of
58568 ** things that make prepared statements obsolete.
58569 */
58570 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
58571   Vdbe *p;
58572   for(p = db->pVdbe; p; p=p->pNext){
58573     p->expired = 1;
58574   }
58575 }
58576
58577 /*
58578 ** Return the database associated with the Vdbe.
58579 */
58580 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
58581   return v->db;
58582 }
58583
58584 /*
58585 ** Return a pointer to an sqlite3_value structure containing the value bound
58586 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return 
58587 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
58588 ** constants) to the value before returning it.
58589 **
58590 ** The returned value must be freed by the caller using sqlite3ValueFree().
58591 */
58592 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
58593   assert( iVar>0 );
58594   if( v ){
58595     Mem *pMem = &v->aVar[iVar-1];
58596     if( 0==(pMem->flags & MEM_Null) ){
58597       sqlite3_value *pRet = sqlite3ValueNew(v->db);
58598       if( pRet ){
58599         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
58600         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
58601         sqlite3VdbeMemStoreType((Mem *)pRet);
58602       }
58603       return pRet;
58604     }
58605   }
58606   return 0;
58607 }
58608
58609 /*
58610 ** Configure SQL variable iVar so that binding a new value to it signals
58611 ** to sqlite3_reoptimize() that re-preparing the statement may result
58612 ** in a better query plan.
58613 */
58614 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
58615   assert( iVar>0 );
58616   if( iVar>32 ){
58617     v->expmask = 0xffffffff;
58618   }else{
58619     v->expmask |= ((u32)1 << (iVar-1));
58620   }
58621 }
58622
58623 /************** End of vdbeaux.c *********************************************/
58624 /************** Begin file vdbeapi.c *****************************************/
58625 /*
58626 ** 2004 May 26
58627 **
58628 ** The author disclaims copyright to this source code.  In place of
58629 ** a legal notice, here is a blessing:
58630 **
58631 **    May you do good and not evil.
58632 **    May you find forgiveness for yourself and forgive others.
58633 **    May you share freely, never taking more than you give.
58634 **
58635 *************************************************************************
58636 **
58637 ** This file contains code use to implement APIs that are part of the
58638 ** VDBE.
58639 */
58640
58641 #ifndef SQLITE_OMIT_DEPRECATED
58642 /*
58643 ** Return TRUE (non-zero) of the statement supplied as an argument needs
58644 ** to be recompiled.  A statement needs to be recompiled whenever the
58645 ** execution environment changes in a way that would alter the program
58646 ** that sqlite3_prepare() generates.  For example, if new functions or
58647 ** collating sequences are registered or if an authorizer function is
58648 ** added or changed.
58649 */
58650 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
58651   Vdbe *p = (Vdbe*)pStmt;
58652   return p==0 || p->expired;
58653 }
58654 #endif
58655
58656 /*
58657 ** Check on a Vdbe to make sure it has not been finalized.  Log
58658 ** an error and return true if it has been finalized (or is otherwise
58659 ** invalid).  Return false if it is ok.
58660 */
58661 static int vdbeSafety(Vdbe *p){
58662   if( p->db==0 ){
58663     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
58664     return 1;
58665   }else{
58666     return 0;
58667   }
58668 }
58669 static int vdbeSafetyNotNull(Vdbe *p){
58670   if( p==0 ){
58671     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
58672     return 1;
58673   }else{
58674     return vdbeSafety(p);
58675   }
58676 }
58677
58678 /*
58679 ** The following routine destroys a virtual machine that is created by
58680 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
58681 ** success/failure code that describes the result of executing the virtual
58682 ** machine.
58683 **
58684 ** This routine sets the error code and string returned by
58685 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
58686 */
58687 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
58688   int rc;
58689   if( pStmt==0 ){
58690     /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
58691     ** pointer is a harmless no-op. */
58692     rc = SQLITE_OK;
58693   }else{
58694     Vdbe *v = (Vdbe*)pStmt;
58695     sqlite3 *db = v->db;
58696 #if SQLITE_THREADSAFE
58697     sqlite3_mutex *mutex;
58698 #endif
58699     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
58700 #if SQLITE_THREADSAFE
58701     mutex = v->db->mutex;
58702 #endif
58703     sqlite3_mutex_enter(mutex);
58704     rc = sqlite3VdbeFinalize(v);
58705     rc = sqlite3ApiExit(db, rc);
58706     sqlite3_mutex_leave(mutex);
58707   }
58708   return rc;
58709 }
58710
58711 /*
58712 ** Terminate the current execution of an SQL statement and reset it
58713 ** back to its starting state so that it can be reused. A success code from
58714 ** the prior execution is returned.
58715 **
58716 ** This routine sets the error code and string returned by
58717 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
58718 */
58719 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
58720   int rc;
58721   if( pStmt==0 ){
58722     rc = SQLITE_OK;
58723   }else{
58724     Vdbe *v = (Vdbe*)pStmt;
58725     sqlite3_mutex_enter(v->db->mutex);
58726     rc = sqlite3VdbeReset(v);
58727     sqlite3VdbeMakeReady(v, -1, 0, 0, 0, 0, 0);
58728     assert( (rc & (v->db->errMask))==rc );
58729     rc = sqlite3ApiExit(v->db, rc);
58730     sqlite3_mutex_leave(v->db->mutex);
58731   }
58732   return rc;
58733 }
58734
58735 /*
58736 ** Set all the parameters in the compiled SQL statement to NULL.
58737 */
58738 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
58739   int i;
58740   int rc = SQLITE_OK;
58741   Vdbe *p = (Vdbe*)pStmt;
58742 #if SQLITE_THREADSAFE
58743   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
58744 #endif
58745   sqlite3_mutex_enter(mutex);
58746   for(i=0; i<p->nVar; i++){
58747     sqlite3VdbeMemRelease(&p->aVar[i]);
58748     p->aVar[i].flags = MEM_Null;
58749   }
58750   if( p->isPrepareV2 && p->expmask ){
58751     p->expired = 1;
58752   }
58753   sqlite3_mutex_leave(mutex);
58754   return rc;
58755 }
58756
58757
58758 /**************************** sqlite3_value_  *******************************
58759 ** The following routines extract information from a Mem or sqlite3_value
58760 ** structure.
58761 */
58762 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
58763   Mem *p = (Mem*)pVal;
58764   if( p->flags & (MEM_Blob|MEM_Str) ){
58765     sqlite3VdbeMemExpandBlob(p);
58766     p->flags &= ~MEM_Str;
58767     p->flags |= MEM_Blob;
58768     return p->n ? p->z : 0;
58769   }else{
58770     return sqlite3_value_text(pVal);
58771   }
58772 }
58773 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
58774   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
58775 }
58776 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
58777   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
58778 }
58779 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
58780   return sqlite3VdbeRealValue((Mem*)pVal);
58781 }
58782 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
58783   return (int)sqlite3VdbeIntValue((Mem*)pVal);
58784 }
58785 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
58786   return sqlite3VdbeIntValue((Mem*)pVal);
58787 }
58788 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
58789   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
58790 }
58791 #ifndef SQLITE_OMIT_UTF16
58792 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
58793   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
58794 }
58795 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
58796   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
58797 }
58798 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
58799   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
58800 }
58801 #endif /* SQLITE_OMIT_UTF16 */
58802 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
58803   return pVal->type;
58804 }
58805
58806 /**************************** sqlite3_result_  *******************************
58807 ** The following routines are used by user-defined functions to specify
58808 ** the function result.
58809 **
58810 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
58811 ** result as a string or blob but if the string or blob is too large, it
58812 ** then sets the error code to SQLITE_TOOBIG
58813 */
58814 static void setResultStrOrError(
58815   sqlite3_context *pCtx,  /* Function context */
58816   const char *z,          /* String pointer */
58817   int n,                  /* Bytes in string, or negative */
58818   u8 enc,                 /* Encoding of z.  0 for BLOBs */
58819   void (*xDel)(void*)     /* Destructor function */
58820 ){
58821   if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
58822     sqlite3_result_error_toobig(pCtx);
58823   }
58824 }
58825 SQLITE_API void sqlite3_result_blob(
58826   sqlite3_context *pCtx, 
58827   const void *z, 
58828   int n, 
58829   void (*xDel)(void *)
58830 ){
58831   assert( n>=0 );
58832   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58833   setResultStrOrError(pCtx, z, n, 0, xDel);
58834 }
58835 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
58836   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58837   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
58838 }
58839 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
58840   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58841   pCtx->isError = SQLITE_ERROR;
58842   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
58843 }
58844 #ifndef SQLITE_OMIT_UTF16
58845 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
58846   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58847   pCtx->isError = SQLITE_ERROR;
58848   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
58849 }
58850 #endif
58851 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
58852   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58853   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
58854 }
58855 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
58856   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58857   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
58858 }
58859 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
58860   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58861   sqlite3VdbeMemSetNull(&pCtx->s);
58862 }
58863 SQLITE_API void sqlite3_result_text(
58864   sqlite3_context *pCtx, 
58865   const char *z, 
58866   int n,
58867   void (*xDel)(void *)
58868 ){
58869   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58870   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
58871 }
58872 #ifndef SQLITE_OMIT_UTF16
58873 SQLITE_API void sqlite3_result_text16(
58874   sqlite3_context *pCtx, 
58875   const void *z, 
58876   int n, 
58877   void (*xDel)(void *)
58878 ){
58879   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58880   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
58881 }
58882 SQLITE_API void sqlite3_result_text16be(
58883   sqlite3_context *pCtx, 
58884   const void *z, 
58885   int n, 
58886   void (*xDel)(void *)
58887 ){
58888   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58889   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
58890 }
58891 SQLITE_API void sqlite3_result_text16le(
58892   sqlite3_context *pCtx, 
58893   const void *z, 
58894   int n, 
58895   void (*xDel)(void *)
58896 ){
58897   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58898   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
58899 }
58900 #endif /* SQLITE_OMIT_UTF16 */
58901 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
58902   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58903   sqlite3VdbeMemCopy(&pCtx->s, pValue);
58904 }
58905 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
58906   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58907   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
58908 }
58909 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
58910   pCtx->isError = errCode;
58911   if( pCtx->s.flags & MEM_Null ){
58912     sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1, 
58913                          SQLITE_UTF8, SQLITE_STATIC);
58914   }
58915 }
58916
58917 /* Force an SQLITE_TOOBIG error. */
58918 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
58919   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58920   pCtx->isError = SQLITE_TOOBIG;
58921   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, 
58922                        SQLITE_UTF8, SQLITE_STATIC);
58923 }
58924
58925 /* An SQLITE_NOMEM error. */
58926 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
58927   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58928   sqlite3VdbeMemSetNull(&pCtx->s);
58929   pCtx->isError = SQLITE_NOMEM;
58930   pCtx->s.db->mallocFailed = 1;
58931 }
58932
58933 /*
58934 ** This function is called after a transaction has been committed. It 
58935 ** invokes callbacks registered with sqlite3_wal_hook() as required.
58936 */
58937 static int doWalCallbacks(sqlite3 *db){
58938   int rc = SQLITE_OK;
58939 #ifndef SQLITE_OMIT_WAL
58940   int i;
58941   for(i=0; i<db->nDb; i++){
58942     Btree *pBt = db->aDb[i].pBt;
58943     if( pBt ){
58944       int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
58945       if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
58946         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
58947       }
58948     }
58949   }
58950 #endif
58951   return rc;
58952 }
58953
58954 /*
58955 ** Execute the statement pStmt, either until a row of data is ready, the
58956 ** statement is completely executed or an error occurs.
58957 **
58958 ** This routine implements the bulk of the logic behind the sqlite_step()
58959 ** API.  The only thing omitted is the automatic recompile if a 
58960 ** schema change has occurred.  That detail is handled by the
58961 ** outer sqlite3_step() wrapper procedure.
58962 */
58963 static int sqlite3Step(Vdbe *p){
58964   sqlite3 *db;
58965   int rc;
58966
58967   assert(p);
58968   if( p->magic!=VDBE_MAGIC_RUN ){
58969     /* We used to require that sqlite3_reset() be called before retrying
58970     ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
58971     ** with version 3.7.0, we changed this so that sqlite3_reset() would
58972     ** be called automatically instead of throwing the SQLITE_MISUSE error.
58973     ** This "automatic-reset" change is not technically an incompatibility, 
58974     ** since any application that receives an SQLITE_MISUSE is broken by
58975     ** definition.
58976     **
58977     ** Nevertheless, some published applications that were originally written
58978     ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE 
58979     ** returns, and the so were broken by the automatic-reset change.  As a
58980     ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
58981     ** legacy behavior of returning SQLITE_MISUSE for cases where the 
58982     ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
58983     ** or SQLITE_BUSY error.
58984     */
58985 #ifdef SQLITE_OMIT_AUTORESET
58986     if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
58987       sqlite3_reset((sqlite3_stmt*)p);
58988     }else{
58989       return SQLITE_MISUSE_BKPT;
58990     }
58991 #else
58992     sqlite3_reset((sqlite3_stmt*)p);
58993 #endif
58994   }
58995
58996   /* Check that malloc() has not failed. If it has, return early. */
58997   db = p->db;
58998   if( db->mallocFailed ){
58999     p->rc = SQLITE_NOMEM;
59000     return SQLITE_NOMEM;
59001   }
59002
59003   if( p->pc<=0 && p->expired ){
59004     p->rc = SQLITE_SCHEMA;
59005     rc = SQLITE_ERROR;
59006     goto end_of_step;
59007   }
59008   if( p->pc<0 ){
59009     /* If there are no other statements currently running, then
59010     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
59011     ** from interrupting a statement that has not yet started.
59012     */
59013     if( db->activeVdbeCnt==0 ){
59014       db->u1.isInterrupted = 0;
59015     }
59016
59017     assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
59018
59019 #ifndef SQLITE_OMIT_TRACE
59020     if( db->xProfile && !db->init.busy ){
59021       sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
59022     }
59023 #endif
59024
59025     db->activeVdbeCnt++;
59026     if( p->readOnly==0 ) db->writeVdbeCnt++;
59027     p->pc = 0;
59028   }
59029 #ifndef SQLITE_OMIT_EXPLAIN
59030   if( p->explain ){
59031     rc = sqlite3VdbeList(p);
59032   }else
59033 #endif /* SQLITE_OMIT_EXPLAIN */
59034   {
59035     db->vdbeExecCnt++;
59036     rc = sqlite3VdbeExec(p);
59037     db->vdbeExecCnt--;
59038   }
59039
59040 #ifndef SQLITE_OMIT_TRACE
59041   /* Invoke the profile callback if there is one
59042   */
59043   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
59044     sqlite3_int64 iNow;
59045     sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
59046     db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
59047   }
59048 #endif
59049
59050   if( rc==SQLITE_DONE ){
59051     assert( p->rc==SQLITE_OK );
59052     p->rc = doWalCallbacks(db);
59053     if( p->rc!=SQLITE_OK ){
59054       rc = SQLITE_ERROR;
59055     }
59056   }
59057
59058   db->errCode = rc;
59059   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
59060     p->rc = SQLITE_NOMEM;
59061   }
59062 end_of_step:
59063   /* At this point local variable rc holds the value that should be 
59064   ** returned if this statement was compiled using the legacy 
59065   ** sqlite3_prepare() interface. According to the docs, this can only
59066   ** be one of the values in the first assert() below. Variable p->rc 
59067   ** contains the value that would be returned if sqlite3_finalize() 
59068   ** were called on statement p.
59069   */
59070   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR 
59071        || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
59072   );
59073   assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
59074   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
59075     /* If this statement was prepared using sqlite3_prepare_v2(), and an
59076     ** error has occured, then return the error code in p->rc to the
59077     ** caller. Set the error code in the database handle to the same value.
59078     */ 
59079     rc = db->errCode = p->rc;
59080   }
59081   return (rc&db->errMask);
59082 }
59083
59084 /*
59085 ** This is the top-level implementation of sqlite3_step().  Call
59086 ** sqlite3Step() to do most of the work.  If a schema error occurs,
59087 ** call sqlite3Reprepare() and try again.
59088 */
59089 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
59090   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
59091   int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
59092   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
59093   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
59094   sqlite3 *db;             /* The database connection */
59095
59096   if( vdbeSafetyNotNull(v) ){
59097     return SQLITE_MISUSE_BKPT;
59098   }
59099   db = v->db;
59100   sqlite3_mutex_enter(db->mutex);
59101   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
59102          && cnt++ < 5
59103          && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
59104     sqlite3_reset(pStmt);
59105     v->expired = 0;
59106   }
59107   if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
59108     /* This case occurs after failing to recompile an sql statement. 
59109     ** The error message from the SQL compiler has already been loaded 
59110     ** into the database handle. This block copies the error message 
59111     ** from the database handle into the statement and sets the statement
59112     ** program counter to 0 to ensure that when the statement is 
59113     ** finalized or reset the parser error message is available via
59114     ** sqlite3_errmsg() and sqlite3_errcode().
59115     */
59116     const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
59117     sqlite3DbFree(db, v->zErrMsg);
59118     if( !db->mallocFailed ){
59119       v->zErrMsg = sqlite3DbStrDup(db, zErr);
59120       v->rc = rc2;
59121     } else {
59122       v->zErrMsg = 0;
59123       v->rc = rc = SQLITE_NOMEM;
59124     }
59125   }
59126   rc = sqlite3ApiExit(db, rc);
59127   sqlite3_mutex_leave(db->mutex);
59128   return rc;
59129 }
59130
59131 /*
59132 ** Extract the user data from a sqlite3_context structure and return a
59133 ** pointer to it.
59134 */
59135 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
59136   assert( p && p->pFunc );
59137   return p->pFunc->pUserData;
59138 }
59139
59140 /*
59141 ** Extract the user data from a sqlite3_context structure and return a
59142 ** pointer to it.
59143 **
59144 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
59145 ** returns a copy of the pointer to the database connection (the 1st
59146 ** parameter) of the sqlite3_create_function() and
59147 ** sqlite3_create_function16() routines that originally registered the
59148 ** application defined function.
59149 */
59150 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
59151   assert( p && p->pFunc );
59152   return p->s.db;
59153 }
59154
59155 /*
59156 ** The following is the implementation of an SQL function that always
59157 ** fails with an error message stating that the function is used in the
59158 ** wrong context.  The sqlite3_overload_function() API might construct
59159 ** SQL function that use this routine so that the functions will exist
59160 ** for name resolution but are actually overloaded by the xFindFunction
59161 ** method of virtual tables.
59162 */
59163 SQLITE_PRIVATE void sqlite3InvalidFunction(
59164   sqlite3_context *context,  /* The function calling context */
59165   int NotUsed,               /* Number of arguments to the function */
59166   sqlite3_value **NotUsed2   /* Value of each argument */
59167 ){
59168   const char *zName = context->pFunc->zName;
59169   char *zErr;
59170   UNUSED_PARAMETER2(NotUsed, NotUsed2);
59171   zErr = sqlite3_mprintf(
59172       "unable to use function %s in the requested context", zName);
59173   sqlite3_result_error(context, zErr, -1);
59174   sqlite3_free(zErr);
59175 }
59176
59177 /*
59178 ** Allocate or return the aggregate context for a user function.  A new
59179 ** context is allocated on the first call.  Subsequent calls return the
59180 ** same context that was returned on prior calls.
59181 */
59182 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
59183   Mem *pMem;
59184   assert( p && p->pFunc && p->pFunc->xStep );
59185   assert( sqlite3_mutex_held(p->s.db->mutex) );
59186   pMem = p->pMem;
59187   testcase( nByte<0 );
59188   if( (pMem->flags & MEM_Agg)==0 ){
59189     if( nByte<=0 ){
59190       sqlite3VdbeMemReleaseExternal(pMem);
59191       pMem->flags = MEM_Null;
59192       pMem->z = 0;
59193     }else{
59194       sqlite3VdbeMemGrow(pMem, nByte, 0);
59195       pMem->flags = MEM_Agg;
59196       pMem->u.pDef = p->pFunc;
59197       if( pMem->z ){
59198         memset(pMem->z, 0, nByte);
59199       }
59200     }
59201   }
59202   return (void*)pMem->z;
59203 }
59204
59205 /*
59206 ** Return the auxilary data pointer, if any, for the iArg'th argument to
59207 ** the user-function defined by pCtx.
59208 */
59209 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
59210   VdbeFunc *pVdbeFunc;
59211
59212   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
59213   pVdbeFunc = pCtx->pVdbeFunc;
59214   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
59215     return 0;
59216   }
59217   return pVdbeFunc->apAux[iArg].pAux;
59218 }
59219
59220 /*
59221 ** Set the auxilary data pointer and delete function, for the iArg'th
59222 ** argument to the user-function defined by pCtx. Any previous value is
59223 ** deleted by calling the delete function specified when it was set.
59224 */
59225 SQLITE_API void sqlite3_set_auxdata(
59226   sqlite3_context *pCtx, 
59227   int iArg, 
59228   void *pAux, 
59229   void (*xDelete)(void*)
59230 ){
59231   struct AuxData *pAuxData;
59232   VdbeFunc *pVdbeFunc;
59233   if( iArg<0 ) goto failed;
59234
59235   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
59236   pVdbeFunc = pCtx->pVdbeFunc;
59237   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
59238     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
59239     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
59240     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
59241     if( !pVdbeFunc ){
59242       goto failed;
59243     }
59244     pCtx->pVdbeFunc = pVdbeFunc;
59245     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
59246     pVdbeFunc->nAux = iArg+1;
59247     pVdbeFunc->pFunc = pCtx->pFunc;
59248   }
59249
59250   pAuxData = &pVdbeFunc->apAux[iArg];
59251   if( pAuxData->pAux && pAuxData->xDelete ){
59252     pAuxData->xDelete(pAuxData->pAux);
59253   }
59254   pAuxData->pAux = pAux;
59255   pAuxData->xDelete = xDelete;
59256   return;
59257
59258 failed:
59259   if( xDelete ){
59260     xDelete(pAux);
59261   }
59262 }
59263
59264 #ifndef SQLITE_OMIT_DEPRECATED
59265 /*
59266 ** Return the number of times the Step function of a aggregate has been 
59267 ** called.
59268 **
59269 ** This function is deprecated.  Do not use it for new code.  It is
59270 ** provide only to avoid breaking legacy code.  New aggregate function
59271 ** implementations should keep their own counts within their aggregate
59272 ** context.
59273 */
59274 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
59275   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
59276   return p->pMem->n;
59277 }
59278 #endif
59279
59280 /*
59281 ** Return the number of columns in the result set for the statement pStmt.
59282 */
59283 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
59284   Vdbe *pVm = (Vdbe *)pStmt;
59285   return pVm ? pVm->nResColumn : 0;
59286 }
59287
59288 /*
59289 ** Return the number of values available from the current row of the
59290 ** currently executing statement pStmt.
59291 */
59292 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
59293   Vdbe *pVm = (Vdbe *)pStmt;
59294   if( pVm==0 || pVm->pResultSet==0 ) return 0;
59295   return pVm->nResColumn;
59296 }
59297
59298
59299 /*
59300 ** Check to see if column iCol of the given statement is valid.  If
59301 ** it is, return a pointer to the Mem for the value of that column.
59302 ** If iCol is not valid, return a pointer to a Mem which has a value
59303 ** of NULL.
59304 */
59305 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
59306   Vdbe *pVm;
59307   int vals;
59308   Mem *pOut;
59309
59310   pVm = (Vdbe *)pStmt;
59311   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
59312     sqlite3_mutex_enter(pVm->db->mutex);
59313     vals = sqlite3_data_count(pStmt);
59314     pOut = &pVm->pResultSet[i];
59315   }else{
59316     /* If the value passed as the second argument is out of range, return
59317     ** a pointer to the following static Mem object which contains the
59318     ** value SQL NULL. Even though the Mem structure contains an element
59319     ** of type i64, on certain architecture (x86) with certain compiler
59320     ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
59321     ** instead of an 8-byte one. This all works fine, except that when
59322     ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
59323     ** that a Mem structure is located on an 8-byte boundary. To prevent
59324     ** this assert() from failing, when building with SQLITE_DEBUG defined
59325     ** using gcc, force nullMem to be 8-byte aligned using the magical
59326     ** __attribute__((aligned(8))) macro.  */
59327     static const Mem nullMem 
59328 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
59329       __attribute__((aligned(8))) 
59330 #endif
59331       = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0, 0, 0 };
59332
59333     if( pVm && ALWAYS(pVm->db) ){
59334       sqlite3_mutex_enter(pVm->db->mutex);
59335       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
59336     }
59337     pOut = (Mem*)&nullMem;
59338   }
59339   return pOut;
59340 }
59341
59342 /*
59343 ** This function is called after invoking an sqlite3_value_XXX function on a 
59344 ** column value (i.e. a value returned by evaluating an SQL expression in the
59345 ** select list of a SELECT statement) that may cause a malloc() failure. If 
59346 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
59347 ** code of statement pStmt set to SQLITE_NOMEM.
59348 **
59349 ** Specifically, this is called from within:
59350 **
59351 **     sqlite3_column_int()
59352 **     sqlite3_column_int64()
59353 **     sqlite3_column_text()
59354 **     sqlite3_column_text16()
59355 **     sqlite3_column_real()
59356 **     sqlite3_column_bytes()
59357 **     sqlite3_column_bytes16()
59358 **     sqiite3_column_blob()
59359 */
59360 static void columnMallocFailure(sqlite3_stmt *pStmt)
59361 {
59362   /* If malloc() failed during an encoding conversion within an
59363   ** sqlite3_column_XXX API, then set the return code of the statement to
59364   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
59365   ** and _finalize() will return NOMEM.
59366   */
59367   Vdbe *p = (Vdbe *)pStmt;
59368   if( p ){
59369     p->rc = sqlite3ApiExit(p->db, p->rc);
59370     sqlite3_mutex_leave(p->db->mutex);
59371   }
59372 }
59373
59374 /**************************** sqlite3_column_  *******************************
59375 ** The following routines are used to access elements of the current row
59376 ** in the result set.
59377 */
59378 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
59379   const void *val;
59380   val = sqlite3_value_blob( columnMem(pStmt,i) );
59381   /* Even though there is no encoding conversion, value_blob() might
59382   ** need to call malloc() to expand the result of a zeroblob() 
59383   ** expression. 
59384   */
59385   columnMallocFailure(pStmt);
59386   return val;
59387 }
59388 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
59389   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
59390   columnMallocFailure(pStmt);
59391   return val;
59392 }
59393 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
59394   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
59395   columnMallocFailure(pStmt);
59396   return val;
59397 }
59398 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
59399   double val = sqlite3_value_double( columnMem(pStmt,i) );
59400   columnMallocFailure(pStmt);
59401   return val;
59402 }
59403 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
59404   int val = sqlite3_value_int( columnMem(pStmt,i) );
59405   columnMallocFailure(pStmt);
59406   return val;
59407 }
59408 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
59409   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
59410   columnMallocFailure(pStmt);
59411   return val;
59412 }
59413 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
59414   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
59415   columnMallocFailure(pStmt);
59416   return val;
59417 }
59418 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
59419   Mem *pOut = columnMem(pStmt, i);
59420   if( pOut->flags&MEM_Static ){
59421     pOut->flags &= ~MEM_Static;
59422     pOut->flags |= MEM_Ephem;
59423   }
59424   columnMallocFailure(pStmt);
59425   return (sqlite3_value *)pOut;
59426 }
59427 #ifndef SQLITE_OMIT_UTF16
59428 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
59429   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
59430   columnMallocFailure(pStmt);
59431   return val;
59432 }
59433 #endif /* SQLITE_OMIT_UTF16 */
59434 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
59435   int iType = sqlite3_value_type( columnMem(pStmt,i) );
59436   columnMallocFailure(pStmt);
59437   return iType;
59438 }
59439
59440 /* The following function is experimental and subject to change or
59441 ** removal */
59442 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
59443 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
59444 **}
59445 */
59446
59447 /*
59448 ** Convert the N-th element of pStmt->pColName[] into a string using
59449 ** xFunc() then return that string.  If N is out of range, return 0.
59450 **
59451 ** There are up to 5 names for each column.  useType determines which
59452 ** name is returned.  Here are the names:
59453 **
59454 **    0      The column name as it should be displayed for output
59455 **    1      The datatype name for the column
59456 **    2      The name of the database that the column derives from
59457 **    3      The name of the table that the column derives from
59458 **    4      The name of the table column that the result column derives from
59459 **
59460 ** If the result is not a simple column reference (if it is an expression
59461 ** or a constant) then useTypes 2, 3, and 4 return NULL.
59462 */
59463 static const void *columnName(
59464   sqlite3_stmt *pStmt,
59465   int N,
59466   const void *(*xFunc)(Mem*),
59467   int useType
59468 ){
59469   const void *ret = 0;
59470   Vdbe *p = (Vdbe *)pStmt;
59471   int n;
59472   sqlite3 *db = p->db;
59473   
59474   assert( db!=0 );
59475   n = sqlite3_column_count(pStmt);
59476   if( N<n && N>=0 ){
59477     N += useType*n;
59478     sqlite3_mutex_enter(db->mutex);
59479     assert( db->mallocFailed==0 );
59480     ret = xFunc(&p->aColName[N]);
59481      /* A malloc may have failed inside of the xFunc() call. If this
59482     ** is the case, clear the mallocFailed flag and return NULL.
59483     */
59484     if( db->mallocFailed ){
59485       db->mallocFailed = 0;
59486       ret = 0;
59487     }
59488     sqlite3_mutex_leave(db->mutex);
59489   }
59490   return ret;
59491 }
59492
59493 /*
59494 ** Return the name of the Nth column of the result set returned by SQL
59495 ** statement pStmt.
59496 */
59497 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
59498   return columnName(
59499       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
59500 }
59501 #ifndef SQLITE_OMIT_UTF16
59502 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
59503   return columnName(
59504       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
59505 }
59506 #endif
59507
59508 /*
59509 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
59510 ** not define OMIT_DECLTYPE.
59511 */
59512 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
59513 # error "Must not define both SQLITE_OMIT_DECLTYPE \
59514          and SQLITE_ENABLE_COLUMN_METADATA"
59515 #endif
59516
59517 #ifndef SQLITE_OMIT_DECLTYPE
59518 /*
59519 ** Return the column declaration type (if applicable) of the 'i'th column
59520 ** of the result set of SQL statement pStmt.
59521 */
59522 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
59523   return columnName(
59524       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
59525 }
59526 #ifndef SQLITE_OMIT_UTF16
59527 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
59528   return columnName(
59529       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
59530 }
59531 #endif /* SQLITE_OMIT_UTF16 */
59532 #endif /* SQLITE_OMIT_DECLTYPE */
59533
59534 #ifdef SQLITE_ENABLE_COLUMN_METADATA
59535 /*
59536 ** Return the name of the database from which a result column derives.
59537 ** NULL is returned if the result column is an expression or constant or
59538 ** anything else which is not an unabiguous reference to a database column.
59539 */
59540 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
59541   return columnName(
59542       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
59543 }
59544 #ifndef SQLITE_OMIT_UTF16
59545 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
59546   return columnName(
59547       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
59548 }
59549 #endif /* SQLITE_OMIT_UTF16 */
59550
59551 /*
59552 ** Return the name of the table from which a result column derives.
59553 ** NULL is returned if the result column is an expression or constant or
59554 ** anything else which is not an unabiguous reference to a database column.
59555 */
59556 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
59557   return columnName(
59558       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
59559 }
59560 #ifndef SQLITE_OMIT_UTF16
59561 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
59562   return columnName(
59563       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
59564 }
59565 #endif /* SQLITE_OMIT_UTF16 */
59566
59567 /*
59568 ** Return the name of the table column from which a result column derives.
59569 ** NULL is returned if the result column is an expression or constant or
59570 ** anything else which is not an unabiguous reference to a database column.
59571 */
59572 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
59573   return columnName(
59574       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
59575 }
59576 #ifndef SQLITE_OMIT_UTF16
59577 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
59578   return columnName(
59579       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
59580 }
59581 #endif /* SQLITE_OMIT_UTF16 */
59582 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
59583
59584
59585 /******************************* sqlite3_bind_  ***************************
59586 ** 
59587 ** Routines used to attach values to wildcards in a compiled SQL statement.
59588 */
59589 /*
59590 ** Unbind the value bound to variable i in virtual machine p. This is the 
59591 ** the same as binding a NULL value to the column. If the "i" parameter is
59592 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
59593 **
59594 ** A successful evaluation of this routine acquires the mutex on p.
59595 ** the mutex is released if any kind of error occurs.
59596 **
59597 ** The error code stored in database p->db is overwritten with the return
59598 ** value in any case.
59599 */
59600 static int vdbeUnbind(Vdbe *p, int i){
59601   Mem *pVar;
59602   if( vdbeSafetyNotNull(p) ){
59603     return SQLITE_MISUSE_BKPT;
59604   }
59605   sqlite3_mutex_enter(p->db->mutex);
59606   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
59607     sqlite3Error(p->db, SQLITE_MISUSE, 0);
59608     sqlite3_mutex_leave(p->db->mutex);
59609     sqlite3_log(SQLITE_MISUSE, 
59610         "bind on a busy prepared statement: [%s]", p->zSql);
59611     return SQLITE_MISUSE_BKPT;
59612   }
59613   if( i<1 || i>p->nVar ){
59614     sqlite3Error(p->db, SQLITE_RANGE, 0);
59615     sqlite3_mutex_leave(p->db->mutex);
59616     return SQLITE_RANGE;
59617   }
59618   i--;
59619   pVar = &p->aVar[i];
59620   sqlite3VdbeMemRelease(pVar);
59621   pVar->flags = MEM_Null;
59622   sqlite3Error(p->db, SQLITE_OK, 0);
59623
59624   /* If the bit corresponding to this variable in Vdbe.expmask is set, then 
59625   ** binding a new value to this variable invalidates the current query plan.
59626   **
59627   ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
59628   ** parameter in the WHERE clause might influence the choice of query plan
59629   ** for a statement, then the statement will be automatically recompiled,
59630   ** as if there had been a schema change, on the first sqlite3_step() call
59631   ** following any change to the bindings of that parameter.
59632   */
59633   if( p->isPrepareV2 &&
59634      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
59635   ){
59636     p->expired = 1;
59637   }
59638   return SQLITE_OK;
59639 }
59640
59641 /*
59642 ** Bind a text or BLOB value.
59643 */
59644 static int bindText(
59645   sqlite3_stmt *pStmt,   /* The statement to bind against */
59646   int i,                 /* Index of the parameter to bind */
59647   const void *zData,     /* Pointer to the data to be bound */
59648   int nData,             /* Number of bytes of data to be bound */
59649   void (*xDel)(void*),   /* Destructor for the data */
59650   u8 encoding            /* Encoding for the data */
59651 ){
59652   Vdbe *p = (Vdbe *)pStmt;
59653   Mem *pVar;
59654   int rc;
59655
59656   rc = vdbeUnbind(p, i);
59657   if( rc==SQLITE_OK ){
59658     if( zData!=0 ){
59659       pVar = &p->aVar[i-1];
59660       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
59661       if( rc==SQLITE_OK && encoding!=0 ){
59662         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
59663       }
59664       sqlite3Error(p->db, rc, 0);
59665       rc = sqlite3ApiExit(p->db, rc);
59666     }
59667     sqlite3_mutex_leave(p->db->mutex);
59668   }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
59669     xDel((void*)zData);
59670   }
59671   return rc;
59672 }
59673
59674
59675 /*
59676 ** Bind a blob value to an SQL statement variable.
59677 */
59678 SQLITE_API int sqlite3_bind_blob(
59679   sqlite3_stmt *pStmt, 
59680   int i, 
59681   const void *zData, 
59682   int nData, 
59683   void (*xDel)(void*)
59684 ){
59685   return bindText(pStmt, i, zData, nData, xDel, 0);
59686 }
59687 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
59688   int rc;
59689   Vdbe *p = (Vdbe *)pStmt;
59690   rc = vdbeUnbind(p, i);
59691   if( rc==SQLITE_OK ){
59692     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
59693     sqlite3_mutex_leave(p->db->mutex);
59694   }
59695   return rc;
59696 }
59697 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
59698   return sqlite3_bind_int64(p, i, (i64)iValue);
59699 }
59700 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
59701   int rc;
59702   Vdbe *p = (Vdbe *)pStmt;
59703   rc = vdbeUnbind(p, i);
59704   if( rc==SQLITE_OK ){
59705     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
59706     sqlite3_mutex_leave(p->db->mutex);
59707   }
59708   return rc;
59709 }
59710 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
59711   int rc;
59712   Vdbe *p = (Vdbe*)pStmt;
59713   rc = vdbeUnbind(p, i);
59714   if( rc==SQLITE_OK ){
59715     sqlite3_mutex_leave(p->db->mutex);
59716   }
59717   return rc;
59718 }
59719 SQLITE_API int sqlite3_bind_text( 
59720   sqlite3_stmt *pStmt, 
59721   int i, 
59722   const char *zData, 
59723   int nData, 
59724   void (*xDel)(void*)
59725 ){
59726   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
59727 }
59728 #ifndef SQLITE_OMIT_UTF16
59729 SQLITE_API int sqlite3_bind_text16(
59730   sqlite3_stmt *pStmt, 
59731   int i, 
59732   const void *zData, 
59733   int nData, 
59734   void (*xDel)(void*)
59735 ){
59736   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
59737 }
59738 #endif /* SQLITE_OMIT_UTF16 */
59739 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
59740   int rc;
59741   switch( pValue->type ){
59742     case SQLITE_INTEGER: {
59743       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
59744       break;
59745     }
59746     case SQLITE_FLOAT: {
59747       rc = sqlite3_bind_double(pStmt, i, pValue->r);
59748       break;
59749     }
59750     case SQLITE_BLOB: {
59751       if( pValue->flags & MEM_Zero ){
59752         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
59753       }else{
59754         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
59755       }
59756       break;
59757     }
59758     case SQLITE_TEXT: {
59759       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
59760                               pValue->enc);
59761       break;
59762     }
59763     default: {
59764       rc = sqlite3_bind_null(pStmt, i);
59765       break;
59766     }
59767   }
59768   return rc;
59769 }
59770 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
59771   int rc;
59772   Vdbe *p = (Vdbe *)pStmt;
59773   rc = vdbeUnbind(p, i);
59774   if( rc==SQLITE_OK ){
59775     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
59776     sqlite3_mutex_leave(p->db->mutex);
59777   }
59778   return rc;
59779 }
59780
59781 /*
59782 ** Return the number of wildcards that can be potentially bound to.
59783 ** This routine is added to support DBD::SQLite.  
59784 */
59785 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
59786   Vdbe *p = (Vdbe*)pStmt;
59787   return p ? p->nVar : 0;
59788 }
59789
59790 /*
59791 ** Create a mapping from variable numbers to variable names
59792 ** in the Vdbe.azVar[] array, if such a mapping does not already
59793 ** exist.
59794 */
59795 static void createVarMap(Vdbe *p){
59796   if( !p->okVar ){
59797     int j;
59798     Op *pOp;
59799     sqlite3_mutex_enter(p->db->mutex);
59800     /* The race condition here is harmless.  If two threads call this
59801     ** routine on the same Vdbe at the same time, they both might end
59802     ** up initializing the Vdbe.azVar[] array.  That is a little extra
59803     ** work but it results in the same answer.
59804     */
59805     for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
59806       if( pOp->opcode==OP_Variable ){
59807         assert( pOp->p1>0 && pOp->p1<=p->nVar );
59808         p->azVar[pOp->p1-1] = pOp->p4.z;
59809       }
59810     }
59811     p->okVar = 1;
59812     sqlite3_mutex_leave(p->db->mutex);
59813   }
59814 }
59815
59816 /*
59817 ** Return the name of a wildcard parameter.  Return NULL if the index
59818 ** is out of range or if the wildcard is unnamed.
59819 **
59820 ** The result is always UTF-8.
59821 */
59822 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
59823   Vdbe *p = (Vdbe*)pStmt;
59824   if( p==0 || i<1 || i>p->nVar ){
59825     return 0;
59826   }
59827   createVarMap(p);
59828   return p->azVar[i-1];
59829 }
59830
59831 /*
59832 ** Given a wildcard parameter name, return the index of the variable
59833 ** with that name.  If there is no variable with the given name,
59834 ** return 0.
59835 */
59836 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
59837   int i;
59838   if( p==0 ){
59839     return 0;
59840   }
59841   createVarMap(p); 
59842   if( zName ){
59843     for(i=0; i<p->nVar; i++){
59844       const char *z = p->azVar[i];
59845       if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
59846         return i+1;
59847       }
59848     }
59849   }
59850   return 0;
59851 }
59852 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
59853   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
59854 }
59855
59856 /*
59857 ** Transfer all bindings from the first statement over to the second.
59858 */
59859 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
59860   Vdbe *pFrom = (Vdbe*)pFromStmt;
59861   Vdbe *pTo = (Vdbe*)pToStmt;
59862   int i;
59863   assert( pTo->db==pFrom->db );
59864   assert( pTo->nVar==pFrom->nVar );
59865   sqlite3_mutex_enter(pTo->db->mutex);
59866   for(i=0; i<pFrom->nVar; i++){
59867     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
59868   }
59869   sqlite3_mutex_leave(pTo->db->mutex);
59870   return SQLITE_OK;
59871 }
59872
59873 #ifndef SQLITE_OMIT_DEPRECATED
59874 /*
59875 ** Deprecated external interface.  Internal/core SQLite code
59876 ** should call sqlite3TransferBindings.
59877 **
59878 ** Is is misuse to call this routine with statements from different
59879 ** database connections.  But as this is a deprecated interface, we
59880 ** will not bother to check for that condition.
59881 **
59882 ** If the two statements contain a different number of bindings, then
59883 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
59884 ** SQLITE_OK is returned.
59885 */
59886 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
59887   Vdbe *pFrom = (Vdbe*)pFromStmt;
59888   Vdbe *pTo = (Vdbe*)pToStmt;
59889   if( pFrom->nVar!=pTo->nVar ){
59890     return SQLITE_ERROR;
59891   }
59892   if( pTo->isPrepareV2 && pTo->expmask ){
59893     pTo->expired = 1;
59894   }
59895   if( pFrom->isPrepareV2 && pFrom->expmask ){
59896     pFrom->expired = 1;
59897   }
59898   return sqlite3TransferBindings(pFromStmt, pToStmt);
59899 }
59900 #endif
59901
59902 /*
59903 ** Return the sqlite3* database handle to which the prepared statement given
59904 ** in the argument belongs.  This is the same database handle that was
59905 ** the first argument to the sqlite3_prepare() that was used to create
59906 ** the statement in the first place.
59907 */
59908 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
59909   return pStmt ? ((Vdbe*)pStmt)->db : 0;
59910 }
59911
59912 /*
59913 ** Return true if the prepared statement is guaranteed to not modify the
59914 ** database.
59915 */
59916 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
59917   return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
59918 }
59919
59920 /*
59921 ** Return a pointer to the next prepared statement after pStmt associated
59922 ** with database connection pDb.  If pStmt is NULL, return the first
59923 ** prepared statement for the database connection.  Return NULL if there
59924 ** are no more.
59925 */
59926 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
59927   sqlite3_stmt *pNext;
59928   sqlite3_mutex_enter(pDb->mutex);
59929   if( pStmt==0 ){
59930     pNext = (sqlite3_stmt*)pDb->pVdbe;
59931   }else{
59932     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
59933   }
59934   sqlite3_mutex_leave(pDb->mutex);
59935   return pNext;
59936 }
59937
59938 /*
59939 ** Return the value of a status counter for a prepared statement
59940 */
59941 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
59942   Vdbe *pVdbe = (Vdbe*)pStmt;
59943   int v = pVdbe->aCounter[op-1];
59944   if( resetFlag ) pVdbe->aCounter[op-1] = 0;
59945   return v;
59946 }
59947
59948 /************** End of vdbeapi.c *********************************************/
59949 /************** Begin file vdbetrace.c ***************************************/
59950 /*
59951 ** 2009 November 25
59952 **
59953 ** The author disclaims copyright to this source code.  In place of
59954 ** a legal notice, here is a blessing:
59955 **
59956 **    May you do good and not evil.
59957 **    May you find forgiveness for yourself and forgive others.
59958 **    May you share freely, never taking more than you give.
59959 **
59960 *************************************************************************
59961 **
59962 ** This file contains code used to insert the values of host parameters
59963 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
59964 */
59965
59966 #ifndef SQLITE_OMIT_TRACE
59967
59968 /*
59969 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
59970 ** bytes in this text up to but excluding the first character in
59971 ** a host parameter.  If the text contains no host parameters, return
59972 ** the total number of bytes in the text.
59973 */
59974 static int findNextHostParameter(const char *zSql, int *pnToken){
59975   int tokenType;
59976   int nTotal = 0;
59977   int n;
59978
59979   *pnToken = 0;
59980   while( zSql[0] ){
59981     n = sqlite3GetToken((u8*)zSql, &tokenType);
59982     assert( n>0 && tokenType!=TK_ILLEGAL );
59983     if( tokenType==TK_VARIABLE ){
59984       *pnToken = n;
59985       break;
59986     }
59987     nTotal += n;
59988     zSql += n;
59989   }
59990   return nTotal;
59991 }
59992
59993 /*
59994 ** This function returns a pointer to a nul-terminated string in memory
59995 ** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the
59996 ** string contains a copy of zRawSql but with host parameters expanded to 
59997 ** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1, 
59998 ** then the returned string holds a copy of zRawSql with "-- " prepended
59999 ** to each line of text.
60000 **
60001 ** The calling function is responsible for making sure the memory returned
60002 ** is eventually freed.
60003 **
60004 ** ALGORITHM:  Scan the input string looking for host parameters in any of
60005 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
60006 ** string literals, quoted identifier names, and comments.  For text forms,
60007 ** the host parameter index is found by scanning the perpared
60008 ** statement for the corresponding OP_Variable opcode.  Once the host
60009 ** parameter index is known, locate the value in p->aVar[].  Then render
60010 ** the value as a literal in place of the host parameter name.
60011 */
60012 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
60013   Vdbe *p,                 /* The prepared statement being evaluated */
60014   const char *zRawSql      /* Raw text of the SQL statement */
60015 ){
60016   sqlite3 *db;             /* The database connection */
60017   int idx = 0;             /* Index of a host parameter */
60018   int nextIndex = 1;       /* Index of next ? host parameter */
60019   int n;                   /* Length of a token prefix */
60020   int nToken;              /* Length of the parameter token */
60021   int i;                   /* Loop counter */
60022   Mem *pVar;               /* Value of a host parameter */
60023   StrAccum out;            /* Accumulate the output here */
60024   char zBase[100];         /* Initial working space */
60025
60026   db = p->db;
60027   sqlite3StrAccumInit(&out, zBase, sizeof(zBase), 
60028                       db->aLimit[SQLITE_LIMIT_LENGTH]);
60029   out.db = db;
60030   if( db->vdbeExecCnt>1 ){
60031     while( *zRawSql ){
60032       const char *zStart = zRawSql;
60033       while( *(zRawSql++)!='\n' && *zRawSql );
60034       sqlite3StrAccumAppend(&out, "-- ", 3);
60035       sqlite3StrAccumAppend(&out, zStart, zRawSql-zStart);
60036     }
60037   }else{
60038     while( zRawSql[0] ){
60039       n = findNextHostParameter(zRawSql, &nToken);
60040       assert( n>0 );
60041       sqlite3StrAccumAppend(&out, zRawSql, n);
60042       zRawSql += n;
60043       assert( zRawSql[0] || nToken==0 );
60044       if( nToken==0 ) break;
60045       if( zRawSql[0]=='?' ){
60046         if( nToken>1 ){
60047           assert( sqlite3Isdigit(zRawSql[1]) );
60048           sqlite3GetInt32(&zRawSql[1], &idx);
60049         }else{
60050           idx = nextIndex;
60051         }
60052       }else{
60053         assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
60054         testcase( zRawSql[0]==':' );
60055         testcase( zRawSql[0]=='$' );
60056         testcase( zRawSql[0]=='@' );
60057         idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
60058         assert( idx>0 );
60059       }
60060       zRawSql += nToken;
60061       nextIndex = idx + 1;
60062       assert( idx>0 && idx<=p->nVar );
60063       pVar = &p->aVar[idx-1];
60064       if( pVar->flags & MEM_Null ){
60065         sqlite3StrAccumAppend(&out, "NULL", 4);
60066       }else if( pVar->flags & MEM_Int ){
60067         sqlite3XPrintf(&out, "%lld", pVar->u.i);
60068       }else if( pVar->flags & MEM_Real ){
60069         sqlite3XPrintf(&out, "%!.15g", pVar->r);
60070       }else if( pVar->flags & MEM_Str ){
60071 #ifndef SQLITE_OMIT_UTF16
60072         u8 enc = ENC(db);
60073         if( enc!=SQLITE_UTF8 ){
60074           Mem utf8;
60075           memset(&utf8, 0, sizeof(utf8));
60076           utf8.db = db;
60077           sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
60078           sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
60079           sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
60080           sqlite3VdbeMemRelease(&utf8);
60081         }else
60082 #endif
60083         {
60084           sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
60085         }
60086       }else if( pVar->flags & MEM_Zero ){
60087         sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
60088       }else{
60089         assert( pVar->flags & MEM_Blob );
60090         sqlite3StrAccumAppend(&out, "x'", 2);
60091         for(i=0; i<pVar->n; i++){
60092           sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
60093         }
60094         sqlite3StrAccumAppend(&out, "'", 1);
60095       }
60096     }
60097   }
60098   return sqlite3StrAccumFinish(&out);
60099 }
60100
60101 #endif /* #ifndef SQLITE_OMIT_TRACE */
60102
60103 /************** End of vdbetrace.c *******************************************/
60104 /************** Begin file vdbe.c ********************************************/
60105 /*
60106 ** 2001 September 15
60107 **
60108 ** The author disclaims copyright to this source code.  In place of
60109 ** a legal notice, here is a blessing:
60110 **
60111 **    May you do good and not evil.
60112 **    May you find forgiveness for yourself and forgive others.
60113 **    May you share freely, never taking more than you give.
60114 **
60115 *************************************************************************
60116 ** The code in this file implements execution method of the 
60117 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
60118 ** handles housekeeping details such as creating and deleting
60119 ** VDBE instances.  This file is solely interested in executing
60120 ** the VDBE program.
60121 **
60122 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
60123 ** to a VDBE.
60124 **
60125 ** The SQL parser generates a program which is then executed by
60126 ** the VDBE to do the work of the SQL statement.  VDBE programs are 
60127 ** similar in form to assembly language.  The program consists of
60128 ** a linear sequence of operations.  Each operation has an opcode 
60129 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4 
60130 ** is a null-terminated string.  Operand P5 is an unsigned character.
60131 ** Few opcodes use all 5 operands.
60132 **
60133 ** Computation results are stored on a set of registers numbered beginning
60134 ** with 1 and going up to Vdbe.nMem.  Each register can store
60135 ** either an integer, a null-terminated string, a floating point
60136 ** number, or the SQL "NULL" value.  An implicit conversion from one
60137 ** type to the other occurs as necessary.
60138 ** 
60139 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
60140 ** function which does the work of interpreting a VDBE program.
60141 ** But other routines are also provided to help in building up
60142 ** a program instruction by instruction.
60143 **
60144 ** Various scripts scan this source file in order to generate HTML
60145 ** documentation, headers files, or other derived files.  The formatting
60146 ** of the code in this file is, therefore, important.  See other comments
60147 ** in this file for details.  If in doubt, do not deviate from existing
60148 ** commenting and indentation practices when changing or adding code.
60149 */
60150
60151 /*
60152 ** Invoke this macro on memory cells just prior to changing the
60153 ** value of the cell.  This macro verifies that shallow copies are
60154 ** not misused.
60155 */
60156 #ifdef SQLITE_DEBUG
60157 # define memAboutToChange(P,M) sqlite3VdbeMemPrepareToChange(P,M)
60158 #else
60159 # define memAboutToChange(P,M)
60160 #endif
60161
60162 /*
60163 ** The following global variable is incremented every time a cursor
60164 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
60165 ** procedures use this information to make sure that indices are
60166 ** working correctly.  This variable has no function other than to
60167 ** help verify the correct operation of the library.
60168 */
60169 #ifdef SQLITE_TEST
60170 SQLITE_API int sqlite3_search_count = 0;
60171 #endif
60172
60173 /*
60174 ** When this global variable is positive, it gets decremented once before
60175 ** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
60176 ** field of the sqlite3 structure is set in order to simulate and interrupt.
60177 **
60178 ** This facility is used for testing purposes only.  It does not function
60179 ** in an ordinary build.
60180 */
60181 #ifdef SQLITE_TEST
60182 SQLITE_API int sqlite3_interrupt_count = 0;
60183 #endif
60184
60185 /*
60186 ** The next global variable is incremented each type the OP_Sort opcode
60187 ** is executed.  The test procedures use this information to make sure that
60188 ** sorting is occurring or not occurring at appropriate times.   This variable
60189 ** has no function other than to help verify the correct operation of the
60190 ** library.
60191 */
60192 #ifdef SQLITE_TEST
60193 SQLITE_API int sqlite3_sort_count = 0;
60194 #endif
60195
60196 /*
60197 ** The next global variable records the size of the largest MEM_Blob
60198 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
60199 ** use this information to make sure that the zero-blob functionality
60200 ** is working correctly.   This variable has no function other than to
60201 ** help verify the correct operation of the library.
60202 */
60203 #ifdef SQLITE_TEST
60204 SQLITE_API int sqlite3_max_blobsize = 0;
60205 static void updateMaxBlobsize(Mem *p){
60206   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
60207     sqlite3_max_blobsize = p->n;
60208   }
60209 }
60210 #endif
60211
60212 /*
60213 ** The next global variable is incremented each type the OP_Found opcode
60214 ** is executed. This is used to test whether or not the foreign key
60215 ** operation implemented using OP_FkIsZero is working. This variable
60216 ** has no function other than to help verify the correct operation of the
60217 ** library.
60218 */
60219 #ifdef SQLITE_TEST
60220 SQLITE_API int sqlite3_found_count = 0;
60221 #endif
60222
60223 /*
60224 ** Test a register to see if it exceeds the current maximum blob size.
60225 ** If it does, record the new maximum blob size.
60226 */
60227 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
60228 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
60229 #else
60230 # define UPDATE_MAX_BLOBSIZE(P)
60231 #endif
60232
60233 /*
60234 ** Convert the given register into a string if it isn't one
60235 ** already. Return non-zero if a malloc() fails.
60236 */
60237 #define Stringify(P, enc) \
60238    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
60239      { goto no_mem; }
60240
60241 /*
60242 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
60243 ** a pointer to a dynamically allocated string where some other entity
60244 ** is responsible for deallocating that string.  Because the register
60245 ** does not control the string, it might be deleted without the register
60246 ** knowing it.
60247 **
60248 ** This routine converts an ephemeral string into a dynamically allocated
60249 ** string that the register itself controls.  In other words, it
60250 ** converts an MEM_Ephem string into an MEM_Dyn string.
60251 */
60252 #define Deephemeralize(P) \
60253    if( ((P)->flags&MEM_Ephem)!=0 \
60254        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
60255
60256 /*
60257 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
60258 ** P if required.
60259 */
60260 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
60261
60262 /*
60263 ** Argument pMem points at a register that will be passed to a
60264 ** user-defined function or returned to the user as the result of a query.
60265 ** This routine sets the pMem->type variable used by the sqlite3_value_*() 
60266 ** routines.
60267 */
60268 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
60269   int flags = pMem->flags;
60270   if( flags & MEM_Null ){
60271     pMem->type = SQLITE_NULL;
60272   }
60273   else if( flags & MEM_Int ){
60274     pMem->type = SQLITE_INTEGER;
60275   }
60276   else if( flags & MEM_Real ){
60277     pMem->type = SQLITE_FLOAT;
60278   }
60279   else if( flags & MEM_Str ){
60280     pMem->type = SQLITE_TEXT;
60281   }else{
60282     pMem->type = SQLITE_BLOB;
60283   }
60284 }
60285
60286 /*
60287 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
60288 ** if we run out of memory.
60289 */
60290 static VdbeCursor *allocateCursor(
60291   Vdbe *p,              /* The virtual machine */
60292   int iCur,             /* Index of the new VdbeCursor */
60293   int nField,           /* Number of fields in the table or index */
60294   int iDb,              /* When database the cursor belongs to, or -1 */
60295   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
60296 ){
60297   /* Find the memory cell that will be used to store the blob of memory
60298   ** required for this VdbeCursor structure. It is convenient to use a 
60299   ** vdbe memory cell to manage the memory allocation required for a
60300   ** VdbeCursor structure for the following reasons:
60301   **
60302   **   * Sometimes cursor numbers are used for a couple of different
60303   **     purposes in a vdbe program. The different uses might require
60304   **     different sized allocations. Memory cells provide growable
60305   **     allocations.
60306   **
60307   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
60308   **     be freed lazily via the sqlite3_release_memory() API. This
60309   **     minimizes the number of malloc calls made by the system.
60310   **
60311   ** Memory cells for cursors are allocated at the top of the address
60312   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
60313   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
60314   */
60315   Mem *pMem = &p->aMem[p->nMem-iCur];
60316
60317   int nByte;
60318   VdbeCursor *pCx = 0;
60319   nByte = 
60320       ROUND8(sizeof(VdbeCursor)) + 
60321       (isBtreeCursor?sqlite3BtreeCursorSize():0) + 
60322       2*nField*sizeof(u32);
60323
60324   assert( iCur<p->nCursor );
60325   if( p->apCsr[iCur] ){
60326     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
60327     p->apCsr[iCur] = 0;
60328   }
60329   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
60330     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
60331     memset(pCx, 0, sizeof(VdbeCursor));
60332     pCx->iDb = iDb;
60333     pCx->nField = nField;
60334     if( nField ){
60335       pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
60336     }
60337     if( isBtreeCursor ){
60338       pCx->pCursor = (BtCursor*)
60339           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
60340       sqlite3BtreeCursorZero(pCx->pCursor);
60341     }
60342   }
60343   return pCx;
60344 }
60345
60346 /*
60347 ** Try to convert a value into a numeric representation if we can
60348 ** do so without loss of information.  In other words, if the string
60349 ** looks like a number, convert it into a number.  If it does not
60350 ** look like a number, leave it alone.
60351 */
60352 static void applyNumericAffinity(Mem *pRec){
60353   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
60354     double rValue;
60355     i64 iValue;
60356     u8 enc = pRec->enc;
60357     if( (pRec->flags&MEM_Str)==0 ) return;
60358     if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
60359     if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
60360       pRec->u.i = iValue;
60361       pRec->flags |= MEM_Int;
60362     }else{
60363       pRec->r = rValue;
60364       pRec->flags |= MEM_Real;
60365     }
60366   }
60367 }
60368
60369 /*
60370 ** Processing is determine by the affinity parameter:
60371 **
60372 ** SQLITE_AFF_INTEGER:
60373 ** SQLITE_AFF_REAL:
60374 ** SQLITE_AFF_NUMERIC:
60375 **    Try to convert pRec to an integer representation or a 
60376 **    floating-point representation if an integer representation
60377 **    is not possible.  Note that the integer representation is
60378 **    always preferred, even if the affinity is REAL, because
60379 **    an integer representation is more space efficient on disk.
60380 **
60381 ** SQLITE_AFF_TEXT:
60382 **    Convert pRec to a text representation.
60383 **
60384 ** SQLITE_AFF_NONE:
60385 **    No-op.  pRec is unchanged.
60386 */
60387 static void applyAffinity(
60388   Mem *pRec,          /* The value to apply affinity to */
60389   char affinity,      /* The affinity to be applied */
60390   u8 enc              /* Use this text encoding */
60391 ){
60392   if( affinity==SQLITE_AFF_TEXT ){
60393     /* Only attempt the conversion to TEXT if there is an integer or real
60394     ** representation (blob and NULL do not get converted) but no string
60395     ** representation.
60396     */
60397     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
60398       sqlite3VdbeMemStringify(pRec, enc);
60399     }
60400     pRec->flags &= ~(MEM_Real|MEM_Int);
60401   }else if( affinity!=SQLITE_AFF_NONE ){
60402     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
60403              || affinity==SQLITE_AFF_NUMERIC );
60404     applyNumericAffinity(pRec);
60405     if( pRec->flags & MEM_Real ){
60406       sqlite3VdbeIntegerAffinity(pRec);
60407     }
60408   }
60409 }
60410
60411 /*
60412 ** Try to convert the type of a function argument or a result column
60413 ** into a numeric representation.  Use either INTEGER or REAL whichever
60414 ** is appropriate.  But only do the conversion if it is possible without
60415 ** loss of information and return the revised type of the argument.
60416 */
60417 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
60418   Mem *pMem = (Mem*)pVal;
60419   if( pMem->type==SQLITE_TEXT ){
60420     applyNumericAffinity(pMem);
60421     sqlite3VdbeMemStoreType(pMem);
60422   }
60423   return pMem->type;
60424 }
60425
60426 /*
60427 ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
60428 ** not the internal Mem* type.
60429 */
60430 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
60431   sqlite3_value *pVal, 
60432   u8 affinity, 
60433   u8 enc
60434 ){
60435   applyAffinity((Mem *)pVal, affinity, enc);
60436 }
60437
60438 #ifdef SQLITE_DEBUG
60439 /*
60440 ** Write a nice string representation of the contents of cell pMem
60441 ** into buffer zBuf, length nBuf.
60442 */
60443 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
60444   char *zCsr = zBuf;
60445   int f = pMem->flags;
60446
60447   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
60448
60449   if( f&MEM_Blob ){
60450     int i;
60451     char c;
60452     if( f & MEM_Dyn ){
60453       c = 'z';
60454       assert( (f & (MEM_Static|MEM_Ephem))==0 );
60455     }else if( f & MEM_Static ){
60456       c = 't';
60457       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
60458     }else if( f & MEM_Ephem ){
60459       c = 'e';
60460       assert( (f & (MEM_Static|MEM_Dyn))==0 );
60461     }else{
60462       c = 's';
60463     }
60464
60465     sqlite3_snprintf(100, zCsr, "%c", c);
60466     zCsr += sqlite3Strlen30(zCsr);
60467     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
60468     zCsr += sqlite3Strlen30(zCsr);
60469     for(i=0; i<16 && i<pMem->n; i++){
60470       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
60471       zCsr += sqlite3Strlen30(zCsr);
60472     }
60473     for(i=0; i<16 && i<pMem->n; i++){
60474       char z = pMem->z[i];
60475       if( z<32 || z>126 ) *zCsr++ = '.';
60476       else *zCsr++ = z;
60477     }
60478
60479     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
60480     zCsr += sqlite3Strlen30(zCsr);
60481     if( f & MEM_Zero ){
60482       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
60483       zCsr += sqlite3Strlen30(zCsr);
60484     }
60485     *zCsr = '\0';
60486   }else if( f & MEM_Str ){
60487     int j, k;
60488     zBuf[0] = ' ';
60489     if( f & MEM_Dyn ){
60490       zBuf[1] = 'z';
60491       assert( (f & (MEM_Static|MEM_Ephem))==0 );
60492     }else if( f & MEM_Static ){
60493       zBuf[1] = 't';
60494       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
60495     }else if( f & MEM_Ephem ){
60496       zBuf[1] = 'e';
60497       assert( (f & (MEM_Static|MEM_Dyn))==0 );
60498     }else{
60499       zBuf[1] = 's';
60500     }
60501     k = 2;
60502     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
60503     k += sqlite3Strlen30(&zBuf[k]);
60504     zBuf[k++] = '[';
60505     for(j=0; j<15 && j<pMem->n; j++){
60506       u8 c = pMem->z[j];
60507       if( c>=0x20 && c<0x7f ){
60508         zBuf[k++] = c;
60509       }else{
60510         zBuf[k++] = '.';
60511       }
60512     }
60513     zBuf[k++] = ']';
60514     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
60515     k += sqlite3Strlen30(&zBuf[k]);
60516     zBuf[k++] = 0;
60517   }
60518 }
60519 #endif
60520
60521 #ifdef SQLITE_DEBUG
60522 /*
60523 ** Print the value of a register for tracing purposes:
60524 */
60525 static void memTracePrint(FILE *out, Mem *p){
60526   if( p->flags & MEM_Null ){
60527     fprintf(out, " NULL");
60528   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
60529     fprintf(out, " si:%lld", p->u.i);
60530   }else if( p->flags & MEM_Int ){
60531     fprintf(out, " i:%lld", p->u.i);
60532 #ifndef SQLITE_OMIT_FLOATING_POINT
60533   }else if( p->flags & MEM_Real ){
60534     fprintf(out, " r:%g", p->r);
60535 #endif
60536   }else if( p->flags & MEM_RowSet ){
60537     fprintf(out, " (rowset)");
60538   }else{
60539     char zBuf[200];
60540     sqlite3VdbeMemPrettyPrint(p, zBuf);
60541     fprintf(out, " ");
60542     fprintf(out, "%s", zBuf);
60543   }
60544 }
60545 static void registerTrace(FILE *out, int iReg, Mem *p){
60546   fprintf(out, "REG[%d] = ", iReg);
60547   memTracePrint(out, p);
60548   fprintf(out, "\n");
60549 }
60550 #endif
60551
60552 #ifdef SQLITE_DEBUG
60553 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
60554 #else
60555 #  define REGISTER_TRACE(R,M)
60556 #endif
60557
60558
60559 #ifdef VDBE_PROFILE
60560
60561 /* 
60562 ** hwtime.h contains inline assembler code for implementing 
60563 ** high-performance timing routines.
60564 */
60565 /************** Include hwtime.h in the middle of vdbe.c *********************/
60566 /************** Begin file hwtime.h ******************************************/
60567 /*
60568 ** 2008 May 27
60569 **
60570 ** The author disclaims copyright to this source code.  In place of
60571 ** a legal notice, here is a blessing:
60572 **
60573 **    May you do good and not evil.
60574 **    May you find forgiveness for yourself and forgive others.
60575 **    May you share freely, never taking more than you give.
60576 **
60577 ******************************************************************************
60578 **
60579 ** This file contains inline asm code for retrieving "high-performance"
60580 ** counters for x86 class CPUs.
60581 */
60582 #ifndef _HWTIME_H_
60583 #define _HWTIME_H_
60584
60585 /*
60586 ** The following routine only works on pentium-class (or newer) processors.
60587 ** It uses the RDTSC opcode to read the cycle count value out of the
60588 ** processor and returns that value.  This can be used for high-res
60589 ** profiling.
60590 */
60591 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
60592       (defined(i386) || defined(__i386__) || defined(_M_IX86))
60593
60594   #if defined(__GNUC__)
60595
60596   __inline__ sqlite_uint64 sqlite3Hwtime(void){
60597      unsigned int lo, hi;
60598      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
60599      return (sqlite_uint64)hi << 32 | lo;
60600   }
60601
60602   #elif defined(_MSC_VER)
60603
60604   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
60605      __asm {
60606         rdtsc
60607         ret       ; return value at EDX:EAX
60608      }
60609   }
60610
60611   #endif
60612
60613 #elif (defined(__GNUC__) && defined(__x86_64__))
60614
60615   __inline__ sqlite_uint64 sqlite3Hwtime(void){
60616       unsigned long val;
60617       __asm__ __volatile__ ("rdtsc" : "=A" (val));
60618       return val;
60619   }
60620  
60621 #elif (defined(__GNUC__) && defined(__ppc__))
60622
60623   __inline__ sqlite_uint64 sqlite3Hwtime(void){
60624       unsigned long long retval;
60625       unsigned long junk;
60626       __asm__ __volatile__ ("\n\
60627           1:      mftbu   %1\n\
60628                   mftb    %L0\n\
60629                   mftbu   %0\n\
60630                   cmpw    %0,%1\n\
60631                   bne     1b"
60632                   : "=r" (retval), "=r" (junk));
60633       return retval;
60634   }
60635
60636 #else
60637
60638   #error Need implementation of sqlite3Hwtime() for your platform.
60639
60640   /*
60641   ** To compile without implementing sqlite3Hwtime() for your platform,
60642   ** you can remove the above #error and use the following
60643   ** stub function.  You will lose timing support for many
60644   ** of the debugging and testing utilities, but it should at
60645   ** least compile and run.
60646   */
60647 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
60648
60649 #endif
60650
60651 #endif /* !defined(_HWTIME_H_) */
60652
60653 /************** End of hwtime.h **********************************************/
60654 /************** Continuing where we left off in vdbe.c ***********************/
60655
60656 #endif
60657
60658 /*
60659 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
60660 ** sqlite3_interrupt() routine has been called.  If it has been, then
60661 ** processing of the VDBE program is interrupted.
60662 **
60663 ** This macro added to every instruction that does a jump in order to
60664 ** implement a loop.  This test used to be on every single instruction,
60665 ** but that meant we more testing that we needed.  By only testing the
60666 ** flag on jump instructions, we get a (small) speed improvement.
60667 */
60668 #define CHECK_FOR_INTERRUPT \
60669    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
60670
60671
60672 #ifndef NDEBUG
60673 /*
60674 ** This function is only called from within an assert() expression. It
60675 ** checks that the sqlite3.nTransaction variable is correctly set to
60676 ** the number of non-transaction savepoints currently in the 
60677 ** linked list starting at sqlite3.pSavepoint.
60678 ** 
60679 ** Usage:
60680 **
60681 **     assert( checkSavepointCount(db) );
60682 */
60683 static int checkSavepointCount(sqlite3 *db){
60684   int n = 0;
60685   Savepoint *p;
60686   for(p=db->pSavepoint; p; p=p->pNext) n++;
60687   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
60688   return 1;
60689 }
60690 #endif
60691
60692 /*
60693 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
60694 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
60695 ** in memory obtained from sqlite3DbMalloc).
60696 */
60697 static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
60698   sqlite3 *db = p->db;
60699   sqlite3DbFree(db, p->zErrMsg);
60700   p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
60701   sqlite3_free(pVtab->zErrMsg);
60702   pVtab->zErrMsg = 0;
60703 }
60704
60705
60706 /*
60707 ** Execute as much of a VDBE program as we can then return.
60708 **
60709 ** sqlite3VdbeMakeReady() must be called before this routine in order to
60710 ** close the program with a final OP_Halt and to set up the callbacks
60711 ** and the error message pointer.
60712 **
60713 ** Whenever a row or result data is available, this routine will either
60714 ** invoke the result callback (if there is one) or return with
60715 ** SQLITE_ROW.
60716 **
60717 ** If an attempt is made to open a locked database, then this routine
60718 ** will either invoke the busy callback (if there is one) or it will
60719 ** return SQLITE_BUSY.
60720 **
60721 ** If an error occurs, an error message is written to memory obtained
60722 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
60723 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
60724 **
60725 ** If the callback ever returns non-zero, then the program exits
60726 ** immediately.  There will be no error message but the p->rc field is
60727 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
60728 **
60729 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
60730 ** routine to return SQLITE_ERROR.
60731 **
60732 ** Other fatal errors return SQLITE_ERROR.
60733 **
60734 ** After this routine has finished, sqlite3VdbeFinalize() should be
60735 ** used to clean up the mess that was left behind.
60736 */
60737 SQLITE_PRIVATE int sqlite3VdbeExec(
60738   Vdbe *p                    /* The VDBE */
60739 ){
60740   int pc=0;                  /* The program counter */
60741   Op *aOp = p->aOp;          /* Copy of p->aOp */
60742   Op *pOp;                   /* Current operation */
60743   int rc = SQLITE_OK;        /* Value to return */
60744   sqlite3 *db = p->db;       /* The database */
60745   u8 resetSchemaOnFault = 0; /* Reset schema after an error if true */
60746   u8 encoding = ENC(db);     /* The database encoding */
60747 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
60748   int checkProgress;         /* True if progress callbacks are enabled */
60749   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
60750 #endif
60751   Mem *aMem = p->aMem;       /* Copy of p->aMem */
60752   Mem *pIn1 = 0;             /* 1st input operand */
60753   Mem *pIn2 = 0;             /* 2nd input operand */
60754   Mem *pIn3 = 0;             /* 3rd input operand */
60755   Mem *pOut = 0;             /* Output operand */
60756   int iCompare = 0;          /* Result of last OP_Compare operation */
60757   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
60758 #ifdef VDBE_PROFILE
60759   u64 start;                 /* CPU clock count at start of opcode */
60760   int origPc;                /* Program counter at start of opcode */
60761 #endif
60762   /********************************************************************
60763   ** Automatically generated code
60764   **
60765   ** The following union is automatically generated by the
60766   ** vdbe-compress.tcl script.  The purpose of this union is to
60767   ** reduce the amount of stack space required by this function.
60768   ** See comments in the vdbe-compress.tcl script for details.
60769   */
60770   union vdbeExecUnion {
60771     struct OP_Yield_stack_vars {
60772       int pcDest;
60773     } aa;
60774     struct OP_Variable_stack_vars {
60775       Mem *pVar;       /* Value being transferred */
60776     } ab;
60777     struct OP_Move_stack_vars {
60778       char *zMalloc;   /* Holding variable for allocated memory */
60779       int n;           /* Number of registers left to copy */
60780       int p1;          /* Register to copy from */
60781       int p2;          /* Register to copy to */
60782     } ac;
60783     struct OP_ResultRow_stack_vars {
60784       Mem *pMem;
60785       int i;
60786     } ad;
60787     struct OP_Concat_stack_vars {
60788       i64 nByte;
60789     } ae;
60790     struct OP_Remainder_stack_vars {
60791       int flags;      /* Combined MEM_* flags from both inputs */
60792       i64 iA;         /* Integer value of left operand */
60793       i64 iB;         /* Integer value of right operand */
60794       double rA;      /* Real value of left operand */
60795       double rB;      /* Real value of right operand */
60796     } af;
60797     struct OP_Function_stack_vars {
60798       int i;
60799       Mem *pArg;
60800       sqlite3_context ctx;
60801       sqlite3_value **apVal;
60802       int n;
60803     } ag;
60804     struct OP_ShiftRight_stack_vars {
60805       i64 a;
60806       i64 b;
60807     } ah;
60808     struct OP_Ge_stack_vars {
60809       int res;            /* Result of the comparison of pIn1 against pIn3 */
60810       char affinity;      /* Affinity to use for comparison */
60811       u16 flags1;         /* Copy of initial value of pIn1->flags */
60812       u16 flags3;         /* Copy of initial value of pIn3->flags */
60813     } ai;
60814     struct OP_Compare_stack_vars {
60815       int n;
60816       int i;
60817       int p1;
60818       int p2;
60819       const KeyInfo *pKeyInfo;
60820       int idx;
60821       CollSeq *pColl;    /* Collating sequence to use on this term */
60822       int bRev;          /* True for DESCENDING sort order */
60823     } aj;
60824     struct OP_Or_stack_vars {
60825       int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
60826       int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
60827     } ak;
60828     struct OP_IfNot_stack_vars {
60829       int c;
60830     } al;
60831     struct OP_Column_stack_vars {
60832       u32 payloadSize;   /* Number of bytes in the record */
60833       i64 payloadSize64; /* Number of bytes in the record */
60834       int p1;            /* P1 value of the opcode */
60835       int p2;            /* column number to retrieve */
60836       VdbeCursor *pC;    /* The VDBE cursor */
60837       char *zRec;        /* Pointer to complete record-data */
60838       BtCursor *pCrsr;   /* The BTree cursor */
60839       u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
60840       u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
60841       int nField;        /* number of fields in the record */
60842       int len;           /* The length of the serialized data for the column */
60843       int i;             /* Loop counter */
60844       char *zData;       /* Part of the record being decoded */
60845       Mem *pDest;        /* Where to write the extracted value */
60846       Mem sMem;          /* For storing the record being decoded */
60847       u8 *zIdx;          /* Index into header */
60848       u8 *zEndHdr;       /* Pointer to first byte after the header */
60849       u32 offset;        /* Offset into the data */
60850       u32 szField;       /* Number of bytes in the content of a field */
60851       int szHdr;         /* Size of the header size field at start of record */
60852       int avail;         /* Number of bytes of available data */
60853       Mem *pReg;         /* PseudoTable input register */
60854     } am;
60855     struct OP_Affinity_stack_vars {
60856       const char *zAffinity;   /* The affinity to be applied */
60857       char cAff;               /* A single character of affinity */
60858     } an;
60859     struct OP_MakeRecord_stack_vars {
60860       u8 *zNewRecord;        /* A buffer to hold the data for the new record */
60861       Mem *pRec;             /* The new record */
60862       u64 nData;             /* Number of bytes of data space */
60863       int nHdr;              /* Number of bytes of header space */
60864       i64 nByte;             /* Data space required for this record */
60865       int nZero;             /* Number of zero bytes at the end of the record */
60866       int nVarint;           /* Number of bytes in a varint */
60867       u32 serial_type;       /* Type field */
60868       Mem *pData0;           /* First field to be combined into the record */
60869       Mem *pLast;            /* Last field of the record */
60870       int nField;            /* Number of fields in the record */
60871       char *zAffinity;       /* The affinity string for the record */
60872       int file_format;       /* File format to use for encoding */
60873       int i;                 /* Space used in zNewRecord[] */
60874       int len;               /* Length of a field */
60875     } ao;
60876     struct OP_Count_stack_vars {
60877       i64 nEntry;
60878       BtCursor *pCrsr;
60879     } ap;
60880     struct OP_Savepoint_stack_vars {
60881       int p1;                         /* Value of P1 operand */
60882       char *zName;                    /* Name of savepoint */
60883       int nName;
60884       Savepoint *pNew;
60885       Savepoint *pSavepoint;
60886       Savepoint *pTmp;
60887       int iSavepoint;
60888       int ii;
60889     } aq;
60890     struct OP_AutoCommit_stack_vars {
60891       int desiredAutoCommit;
60892       int iRollback;
60893       int turnOnAC;
60894     } ar;
60895     struct OP_Transaction_stack_vars {
60896       Btree *pBt;
60897     } as;
60898     struct OP_ReadCookie_stack_vars {
60899       int iMeta;
60900       int iDb;
60901       int iCookie;
60902     } at;
60903     struct OP_SetCookie_stack_vars {
60904       Db *pDb;
60905     } au;
60906     struct OP_VerifyCookie_stack_vars {
60907       int iMeta;
60908       Btree *pBt;
60909     } av;
60910     struct OP_OpenWrite_stack_vars {
60911       int nField;
60912       KeyInfo *pKeyInfo;
60913       int p2;
60914       int iDb;
60915       int wrFlag;
60916       Btree *pX;
60917       VdbeCursor *pCur;
60918       Db *pDb;
60919     } aw;
60920     struct OP_OpenEphemeral_stack_vars {
60921       VdbeCursor *pCx;
60922     } ax;
60923     struct OP_OpenPseudo_stack_vars {
60924       VdbeCursor *pCx;
60925     } ay;
60926     struct OP_SeekGt_stack_vars {
60927       int res;
60928       int oc;
60929       VdbeCursor *pC;
60930       UnpackedRecord r;
60931       int nField;
60932       i64 iKey;      /* The rowid we are to seek to */
60933     } az;
60934     struct OP_Seek_stack_vars {
60935       VdbeCursor *pC;
60936     } ba;
60937     struct OP_Found_stack_vars {
60938       int alreadyExists;
60939       VdbeCursor *pC;
60940       int res;
60941       UnpackedRecord *pIdxKey;
60942       UnpackedRecord r;
60943       char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
60944     } bb;
60945     struct OP_IsUnique_stack_vars {
60946       u16 ii;
60947       VdbeCursor *pCx;
60948       BtCursor *pCrsr;
60949       u16 nField;
60950       Mem *aMx;
60951       UnpackedRecord r;                  /* B-Tree index search key */
60952       i64 R;                             /* Rowid stored in register P3 */
60953     } bc;
60954     struct OP_NotExists_stack_vars {
60955       VdbeCursor *pC;
60956       BtCursor *pCrsr;
60957       int res;
60958       u64 iKey;
60959     } bd;
60960     struct OP_NewRowid_stack_vars {
60961       i64 v;                 /* The new rowid */
60962       VdbeCursor *pC;        /* Cursor of table to get the new rowid */
60963       int res;               /* Result of an sqlite3BtreeLast() */
60964       int cnt;               /* Counter to limit the number of searches */
60965       Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
60966       VdbeFrame *pFrame;     /* Root frame of VDBE */
60967     } be;
60968     struct OP_InsertInt_stack_vars {
60969       Mem *pData;       /* MEM cell holding data for the record to be inserted */
60970       Mem *pKey;        /* MEM cell holding key  for the record */
60971       i64 iKey;         /* The integer ROWID or key for the record to be inserted */
60972       VdbeCursor *pC;   /* Cursor to table into which insert is written */
60973       int nZero;        /* Number of zero-bytes to append */
60974       int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
60975       const char *zDb;  /* database name - used by the update hook */
60976       const char *zTbl; /* Table name - used by the opdate hook */
60977       int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
60978     } bf;
60979     struct OP_Delete_stack_vars {
60980       i64 iKey;
60981       VdbeCursor *pC;
60982     } bg;
60983     struct OP_RowData_stack_vars {
60984       VdbeCursor *pC;
60985       BtCursor *pCrsr;
60986       u32 n;
60987       i64 n64;
60988     } bh;
60989     struct OP_Rowid_stack_vars {
60990       VdbeCursor *pC;
60991       i64 v;
60992       sqlite3_vtab *pVtab;
60993       const sqlite3_module *pModule;
60994     } bi;
60995     struct OP_NullRow_stack_vars {
60996       VdbeCursor *pC;
60997     } bj;
60998     struct OP_Last_stack_vars {
60999       VdbeCursor *pC;
61000       BtCursor *pCrsr;
61001       int res;
61002     } bk;
61003     struct OP_Rewind_stack_vars {
61004       VdbeCursor *pC;
61005       BtCursor *pCrsr;
61006       int res;
61007     } bl;
61008     struct OP_Next_stack_vars {
61009       VdbeCursor *pC;
61010       BtCursor *pCrsr;
61011       int res;
61012     } bm;
61013     struct OP_IdxInsert_stack_vars {
61014       VdbeCursor *pC;
61015       BtCursor *pCrsr;
61016       int nKey;
61017       const char *zKey;
61018     } bn;
61019     struct OP_IdxDelete_stack_vars {
61020       VdbeCursor *pC;
61021       BtCursor *pCrsr;
61022       int res;
61023       UnpackedRecord r;
61024     } bo;
61025     struct OP_IdxRowid_stack_vars {
61026       BtCursor *pCrsr;
61027       VdbeCursor *pC;
61028       i64 rowid;
61029     } bp;
61030     struct OP_IdxGE_stack_vars {
61031       VdbeCursor *pC;
61032       int res;
61033       UnpackedRecord r;
61034     } bq;
61035     struct OP_Destroy_stack_vars {
61036       int iMoved;
61037       int iCnt;
61038       Vdbe *pVdbe;
61039       int iDb;
61040     } br;
61041     struct OP_Clear_stack_vars {
61042       int nChange;
61043     } bs;
61044     struct OP_CreateTable_stack_vars {
61045       int pgno;
61046       int flags;
61047       Db *pDb;
61048     } bt;
61049     struct OP_ParseSchema_stack_vars {
61050       int iDb;
61051       const char *zMaster;
61052       char *zSql;
61053       InitData initData;
61054     } bu;
61055     struct OP_IntegrityCk_stack_vars {
61056       int nRoot;      /* Number of tables to check.  (Number of root pages.) */
61057       int *aRoot;     /* Array of rootpage numbers for tables to be checked */
61058       int j;          /* Loop counter */
61059       int nErr;       /* Number of errors reported */
61060       char *z;        /* Text of the error report */
61061       Mem *pnErr;     /* Register keeping track of errors remaining */
61062     } bv;
61063     struct OP_RowSetRead_stack_vars {
61064       i64 val;
61065     } bw;
61066     struct OP_RowSetTest_stack_vars {
61067       int iSet;
61068       int exists;
61069     } bx;
61070     struct OP_Program_stack_vars {
61071       int nMem;               /* Number of memory registers for sub-program */
61072       int nByte;              /* Bytes of runtime space required for sub-program */
61073       Mem *pRt;               /* Register to allocate runtime space */
61074       Mem *pMem;              /* Used to iterate through memory cells */
61075       Mem *pEnd;              /* Last memory cell in new array */
61076       VdbeFrame *pFrame;      /* New vdbe frame to execute in */
61077       SubProgram *pProgram;   /* Sub-program to execute */
61078       void *t;                /* Token identifying trigger */
61079     } by;
61080     struct OP_Param_stack_vars {
61081       VdbeFrame *pFrame;
61082       Mem *pIn;
61083     } bz;
61084     struct OP_MemMax_stack_vars {
61085       Mem *pIn1;
61086       VdbeFrame *pFrame;
61087     } ca;
61088     struct OP_AggStep_stack_vars {
61089       int n;
61090       int i;
61091       Mem *pMem;
61092       Mem *pRec;
61093       sqlite3_context ctx;
61094       sqlite3_value **apVal;
61095     } cb;
61096     struct OP_AggFinal_stack_vars {
61097       Mem *pMem;
61098     } cc;
61099     struct OP_JournalMode_stack_vars {
61100       Btree *pBt;                     /* Btree to change journal mode of */
61101       Pager *pPager;                  /* Pager associated with pBt */
61102       int eNew;                       /* New journal mode */
61103       int eOld;                       /* The old journal mode */
61104       const char *zFilename;          /* Name of database file for pPager */
61105     } cd;
61106     struct OP_IncrVacuum_stack_vars {
61107       Btree *pBt;
61108     } ce;
61109     struct OP_VBegin_stack_vars {
61110       VTable *pVTab;
61111     } cf;
61112     struct OP_VOpen_stack_vars {
61113       VdbeCursor *pCur;
61114       sqlite3_vtab_cursor *pVtabCursor;
61115       sqlite3_vtab *pVtab;
61116       sqlite3_module *pModule;
61117     } cg;
61118     struct OP_VFilter_stack_vars {
61119       int nArg;
61120       int iQuery;
61121       const sqlite3_module *pModule;
61122       Mem *pQuery;
61123       Mem *pArgc;
61124       sqlite3_vtab_cursor *pVtabCursor;
61125       sqlite3_vtab *pVtab;
61126       VdbeCursor *pCur;
61127       int res;
61128       int i;
61129       Mem **apArg;
61130     } ch;
61131     struct OP_VColumn_stack_vars {
61132       sqlite3_vtab *pVtab;
61133       const sqlite3_module *pModule;
61134       Mem *pDest;
61135       sqlite3_context sContext;
61136     } ci;
61137     struct OP_VNext_stack_vars {
61138       sqlite3_vtab *pVtab;
61139       const sqlite3_module *pModule;
61140       int res;
61141       VdbeCursor *pCur;
61142     } cj;
61143     struct OP_VRename_stack_vars {
61144       sqlite3_vtab *pVtab;
61145       Mem *pName;
61146     } ck;
61147     struct OP_VUpdate_stack_vars {
61148       sqlite3_vtab *pVtab;
61149       sqlite3_module *pModule;
61150       int nArg;
61151       int i;
61152       sqlite_int64 rowid;
61153       Mem **apArg;
61154       Mem *pX;
61155     } cl;
61156     struct OP_Trace_stack_vars {
61157       char *zTrace;
61158     } cm;
61159   } u;
61160   /* End automatically generated code
61161   ********************************************************************/
61162
61163   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
61164   sqlite3VdbeMutexArrayEnter(p);
61165   if( p->rc==SQLITE_NOMEM ){
61166     /* This happens if a malloc() inside a call to sqlite3_column_text() or
61167     ** sqlite3_column_text16() failed.  */
61168     goto no_mem;
61169   }
61170   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
61171   p->rc = SQLITE_OK;
61172   assert( p->explain==0 );
61173   p->pResultSet = 0;
61174   db->busyHandler.nBusy = 0;
61175   CHECK_FOR_INTERRUPT;
61176   sqlite3VdbeIOTraceSql(p);
61177 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
61178   checkProgress = db->xProgress!=0;
61179 #endif
61180 #ifdef SQLITE_DEBUG
61181   sqlite3BeginBenignMalloc();
61182   if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
61183     int i;
61184     printf("VDBE Program Listing:\n");
61185     sqlite3VdbePrintSql(p);
61186     for(i=0; i<p->nOp; i++){
61187       sqlite3VdbePrintOp(stdout, i, &aOp[i]);
61188     }
61189   }
61190   sqlite3EndBenignMalloc();
61191 #endif
61192   for(pc=p->pc; rc==SQLITE_OK; pc++){
61193     assert( pc>=0 && pc<p->nOp );
61194     if( db->mallocFailed ) goto no_mem;
61195 #ifdef VDBE_PROFILE
61196     origPc = pc;
61197     start = sqlite3Hwtime();
61198 #endif
61199     pOp = &aOp[pc];
61200
61201     /* Only allow tracing if SQLITE_DEBUG is defined.
61202     */
61203 #ifdef SQLITE_DEBUG
61204     if( p->trace ){
61205       if( pc==0 ){
61206         printf("VDBE Execution Trace:\n");
61207         sqlite3VdbePrintSql(p);
61208       }
61209       sqlite3VdbePrintOp(p->trace, pc, pOp);
61210     }
61211 #endif
61212       
61213
61214     /* Check to see if we need to simulate an interrupt.  This only happens
61215     ** if we have a special test build.
61216     */
61217 #ifdef SQLITE_TEST
61218     if( sqlite3_interrupt_count>0 ){
61219       sqlite3_interrupt_count--;
61220       if( sqlite3_interrupt_count==0 ){
61221         sqlite3_interrupt(db);
61222       }
61223     }
61224 #endif
61225
61226 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
61227     /* Call the progress callback if it is configured and the required number
61228     ** of VDBE ops have been executed (either since this invocation of
61229     ** sqlite3VdbeExec() or since last time the progress callback was called).
61230     ** If the progress callback returns non-zero, exit the virtual machine with
61231     ** a return code SQLITE_ABORT.
61232     */
61233     if( checkProgress ){
61234       if( db->nProgressOps==nProgressOps ){
61235         int prc;
61236         prc = db->xProgress(db->pProgressArg);
61237         if( prc!=0 ){
61238           rc = SQLITE_INTERRUPT;
61239           goto vdbe_error_halt;
61240         }
61241         nProgressOps = 0;
61242       }
61243       nProgressOps++;
61244     }
61245 #endif
61246
61247     /* On any opcode with the "out2-prerelase" tag, free any
61248     ** external allocations out of mem[p2] and set mem[p2] to be
61249     ** an undefined integer.  Opcodes will either fill in the integer
61250     ** value or convert mem[p2] to a different type.
61251     */
61252     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
61253     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
61254       assert( pOp->p2>0 );
61255       assert( pOp->p2<=p->nMem );
61256       pOut = &aMem[pOp->p2];
61257       memAboutToChange(p, pOut);
61258       sqlite3VdbeMemReleaseExternal(pOut);
61259       pOut->flags = MEM_Int;
61260     }
61261
61262     /* Sanity checking on other operands */
61263 #ifdef SQLITE_DEBUG
61264     if( (pOp->opflags & OPFLG_IN1)!=0 ){
61265       assert( pOp->p1>0 );
61266       assert( pOp->p1<=p->nMem );
61267       assert( memIsValid(&aMem[pOp->p1]) );
61268       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
61269     }
61270     if( (pOp->opflags & OPFLG_IN2)!=0 ){
61271       assert( pOp->p2>0 );
61272       assert( pOp->p2<=p->nMem );
61273       assert( memIsValid(&aMem[pOp->p2]) );
61274       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
61275     }
61276     if( (pOp->opflags & OPFLG_IN3)!=0 ){
61277       assert( pOp->p3>0 );
61278       assert( pOp->p3<=p->nMem );
61279       assert( memIsValid(&aMem[pOp->p3]) );
61280       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
61281     }
61282     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
61283       assert( pOp->p2>0 );
61284       assert( pOp->p2<=p->nMem );
61285       memAboutToChange(p, &aMem[pOp->p2]);
61286     }
61287     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
61288       assert( pOp->p3>0 );
61289       assert( pOp->p3<=p->nMem );
61290       memAboutToChange(p, &aMem[pOp->p3]);
61291     }
61292 #endif
61293   
61294     switch( pOp->opcode ){
61295
61296 /*****************************************************************************
61297 ** What follows is a massive switch statement where each case implements a
61298 ** separate instruction in the virtual machine.  If we follow the usual
61299 ** indentation conventions, each case should be indented by 6 spaces.  But
61300 ** that is a lot of wasted space on the left margin.  So the code within
61301 ** the switch statement will break with convention and be flush-left. Another
61302 ** big comment (similar to this one) will mark the point in the code where
61303 ** we transition back to normal indentation.
61304 **
61305 ** The formatting of each case is important.  The makefile for SQLite
61306 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
61307 ** file looking for lines that begin with "case OP_".  The opcodes.h files
61308 ** will be filled with #defines that give unique integer values to each
61309 ** opcode and the opcodes.c file is filled with an array of strings where
61310 ** each string is the symbolic name for the corresponding opcode.  If the
61311 ** case statement is followed by a comment of the form "/# same as ... #/"
61312 ** that comment is used to determine the particular value of the opcode.
61313 **
61314 ** Other keywords in the comment that follows each case are used to
61315 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
61316 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
61317 ** the mkopcodeh.awk script for additional information.
61318 **
61319 ** Documentation about VDBE opcodes is generated by scanning this file
61320 ** for lines of that contain "Opcode:".  That line and all subsequent
61321 ** comment lines are used in the generation of the opcode.html documentation
61322 ** file.
61323 **
61324 ** SUMMARY:
61325 **
61326 **     Formatting is important to scripts that scan this file.
61327 **     Do not deviate from the formatting style currently in use.
61328 **
61329 *****************************************************************************/
61330
61331 /* Opcode:  Goto * P2 * * *
61332 **
61333 ** An unconditional jump to address P2.
61334 ** The next instruction executed will be 
61335 ** the one at index P2 from the beginning of
61336 ** the program.
61337 */
61338 case OP_Goto: {             /* jump */
61339   CHECK_FOR_INTERRUPT;
61340   pc = pOp->p2 - 1;
61341   break;
61342 }
61343
61344 /* Opcode:  Gosub P1 P2 * * *
61345 **
61346 ** Write the current address onto register P1
61347 ** and then jump to address P2.
61348 */
61349 case OP_Gosub: {            /* jump, in1 */
61350   pIn1 = &aMem[pOp->p1];
61351   assert( (pIn1->flags & MEM_Dyn)==0 );
61352   memAboutToChange(p, pIn1);
61353   pIn1->flags = MEM_Int;
61354   pIn1->u.i = pc;
61355   REGISTER_TRACE(pOp->p1, pIn1);
61356   pc = pOp->p2 - 1;
61357   break;
61358 }
61359
61360 /* Opcode:  Return P1 * * * *
61361 **
61362 ** Jump to the next instruction after the address in register P1.
61363 */
61364 case OP_Return: {           /* in1 */
61365   pIn1 = &aMem[pOp->p1];
61366   assert( pIn1->flags & MEM_Int );
61367   pc = (int)pIn1->u.i;
61368   break;
61369 }
61370
61371 /* Opcode:  Yield P1 * * * *
61372 **
61373 ** Swap the program counter with the value in register P1.
61374 */
61375 case OP_Yield: {            /* in1 */
61376 #if 0  /* local variables moved into u.aa */
61377   int pcDest;
61378 #endif /* local variables moved into u.aa */
61379   pIn1 = &aMem[pOp->p1];
61380   assert( (pIn1->flags & MEM_Dyn)==0 );
61381   pIn1->flags = MEM_Int;
61382   u.aa.pcDest = (int)pIn1->u.i;
61383   pIn1->u.i = pc;
61384   REGISTER_TRACE(pOp->p1, pIn1);
61385   pc = u.aa.pcDest;
61386   break;
61387 }
61388
61389 /* Opcode:  HaltIfNull  P1 P2 P3 P4 *
61390 **
61391 ** Check the value in register P3.  If is is NULL then Halt using
61392 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
61393 ** value in register P3 is not NULL, then this routine is a no-op.
61394 */
61395 case OP_HaltIfNull: {      /* in3 */
61396   pIn3 = &aMem[pOp->p3];
61397   if( (pIn3->flags & MEM_Null)==0 ) break;
61398   /* Fall through into OP_Halt */
61399 }
61400
61401 /* Opcode:  Halt P1 P2 * P4 *
61402 **
61403 ** Exit immediately.  All open cursors, etc are closed
61404 ** automatically.
61405 **
61406 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
61407 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
61408 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
61409 ** whether or not to rollback the current transaction.  Do not rollback
61410 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
61411 ** then back out all changes that have occurred during this execution of the
61412 ** VDBE, but do not rollback the transaction. 
61413 **
61414 ** If P4 is not null then it is an error message string.
61415 **
61416 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
61417 ** every program.  So a jump past the last instruction of the program
61418 ** is the same as executing Halt.
61419 */
61420 case OP_Halt: {
61421   if( pOp->p1==SQLITE_OK && p->pFrame ){
61422     /* Halt the sub-program. Return control to the parent frame. */
61423     VdbeFrame *pFrame = p->pFrame;
61424     p->pFrame = pFrame->pParent;
61425     p->nFrame--;
61426     sqlite3VdbeSetChanges(db, p->nChange);
61427     pc = sqlite3VdbeFrameRestore(pFrame);
61428     if( pOp->p2==OE_Ignore ){
61429       /* Instruction pc is the OP_Program that invoked the sub-program 
61430       ** currently being halted. If the p2 instruction of this OP_Halt
61431       ** instruction is set to OE_Ignore, then the sub-program is throwing
61432       ** an IGNORE exception. In this case jump to the address specified
61433       ** as the p2 of the calling OP_Program.  */
61434       pc = p->aOp[pc].p2-1;
61435     }
61436     aOp = p->aOp;
61437     aMem = p->aMem;
61438     break;
61439   }
61440
61441   p->rc = pOp->p1;
61442   p->errorAction = (u8)pOp->p2;
61443   p->pc = pc;
61444   if( pOp->p4.z ){
61445     assert( p->rc!=SQLITE_OK );
61446     sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
61447     testcase( sqlite3GlobalConfig.xLog!=0 );
61448     sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
61449   }else if( p->rc ){
61450     testcase( sqlite3GlobalConfig.xLog!=0 );
61451     sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
61452   }
61453   rc = sqlite3VdbeHalt(p);
61454   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
61455   if( rc==SQLITE_BUSY ){
61456     p->rc = rc = SQLITE_BUSY;
61457   }else{
61458     assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
61459     assert( rc==SQLITE_OK || db->nDeferredCons>0 );
61460     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
61461   }
61462   goto vdbe_return;
61463 }
61464
61465 /* Opcode: Integer P1 P2 * * *
61466 **
61467 ** The 32-bit integer value P1 is written into register P2.
61468 */
61469 case OP_Integer: {         /* out2-prerelease */
61470   pOut->u.i = pOp->p1;
61471   break;
61472 }
61473
61474 /* Opcode: Int64 * P2 * P4 *
61475 **
61476 ** P4 is a pointer to a 64-bit integer value.
61477 ** Write that value into register P2.
61478 */
61479 case OP_Int64: {           /* out2-prerelease */
61480   assert( pOp->p4.pI64!=0 );
61481   pOut->u.i = *pOp->p4.pI64;
61482   break;
61483 }
61484
61485 #ifndef SQLITE_OMIT_FLOATING_POINT
61486 /* Opcode: Real * P2 * P4 *
61487 **
61488 ** P4 is a pointer to a 64-bit floating point value.
61489 ** Write that value into register P2.
61490 */
61491 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
61492   pOut->flags = MEM_Real;
61493   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
61494   pOut->r = *pOp->p4.pReal;
61495   break;
61496 }
61497 #endif
61498
61499 /* Opcode: String8 * P2 * P4 *
61500 **
61501 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
61502 ** into an OP_String before it is executed for the first time.
61503 */
61504 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
61505   assert( pOp->p4.z!=0 );
61506   pOp->opcode = OP_String;
61507   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
61508
61509 #ifndef SQLITE_OMIT_UTF16
61510   if( encoding!=SQLITE_UTF8 ){
61511     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
61512     if( rc==SQLITE_TOOBIG ) goto too_big;
61513     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
61514     assert( pOut->zMalloc==pOut->z );
61515     assert( pOut->flags & MEM_Dyn );
61516     pOut->zMalloc = 0;
61517     pOut->flags |= MEM_Static;
61518     pOut->flags &= ~MEM_Dyn;
61519     if( pOp->p4type==P4_DYNAMIC ){
61520       sqlite3DbFree(db, pOp->p4.z);
61521     }
61522     pOp->p4type = P4_DYNAMIC;
61523     pOp->p4.z = pOut->z;
61524     pOp->p1 = pOut->n;
61525   }
61526 #endif
61527   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
61528     goto too_big;
61529   }
61530   /* Fall through to the next case, OP_String */
61531 }
61532   
61533 /* Opcode: String P1 P2 * P4 *
61534 **
61535 ** The string value P4 of length P1 (bytes) is stored in register P2.
61536 */
61537 case OP_String: {          /* out2-prerelease */
61538   assert( pOp->p4.z!=0 );
61539   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
61540   pOut->z = pOp->p4.z;
61541   pOut->n = pOp->p1;
61542   pOut->enc = encoding;
61543   UPDATE_MAX_BLOBSIZE(pOut);
61544   break;
61545 }
61546
61547 /* Opcode: Null * P2 * * *
61548 **
61549 ** Write a NULL into register P2.
61550 */
61551 case OP_Null: {           /* out2-prerelease */
61552   pOut->flags = MEM_Null;
61553   break;
61554 }
61555
61556
61557 /* Opcode: Blob P1 P2 * P4
61558 **
61559 ** P4 points to a blob of data P1 bytes long.  Store this
61560 ** blob in register P2.
61561 */
61562 case OP_Blob: {                /* out2-prerelease */
61563   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
61564   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
61565   pOut->enc = encoding;
61566   UPDATE_MAX_BLOBSIZE(pOut);
61567   break;
61568 }
61569
61570 /* Opcode: Variable P1 P2 * P4 *
61571 **
61572 ** Transfer the values of bound parameter P1 into register P2
61573 **
61574 ** If the parameter is named, then its name appears in P4 and P3==1.
61575 ** The P4 value is used by sqlite3_bind_parameter_name().
61576 */
61577 case OP_Variable: {            /* out2-prerelease */
61578 #if 0  /* local variables moved into u.ab */
61579   Mem *pVar;       /* Value being transferred */
61580 #endif /* local variables moved into u.ab */
61581
61582   assert( pOp->p1>0 && pOp->p1<=p->nVar );
61583   u.ab.pVar = &p->aVar[pOp->p1 - 1];
61584   if( sqlite3VdbeMemTooBig(u.ab.pVar) ){
61585     goto too_big;
61586   }
61587   sqlite3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
61588   UPDATE_MAX_BLOBSIZE(pOut);
61589   break;
61590 }
61591
61592 /* Opcode: Move P1 P2 P3 * *
61593 **
61594 ** Move the values in register P1..P1+P3-1 over into
61595 ** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
61596 ** left holding a NULL.  It is an error for register ranges
61597 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
61598 */
61599 case OP_Move: {
61600 #if 0  /* local variables moved into u.ac */
61601   char *zMalloc;   /* Holding variable for allocated memory */
61602   int n;           /* Number of registers left to copy */
61603   int p1;          /* Register to copy from */
61604   int p2;          /* Register to copy to */
61605 #endif /* local variables moved into u.ac */
61606
61607   u.ac.n = pOp->p3;
61608   u.ac.p1 = pOp->p1;
61609   u.ac.p2 = pOp->p2;
61610   assert( u.ac.n>0 && u.ac.p1>0 && u.ac.p2>0 );
61611   assert( u.ac.p1+u.ac.n<=u.ac.p2 || u.ac.p2+u.ac.n<=u.ac.p1 );
61612
61613   pIn1 = &aMem[u.ac.p1];
61614   pOut = &aMem[u.ac.p2];
61615   while( u.ac.n-- ){
61616     assert( pOut<=&aMem[p->nMem] );
61617     assert( pIn1<=&aMem[p->nMem] );
61618     assert( memIsValid(pIn1) );
61619     memAboutToChange(p, pOut);
61620     u.ac.zMalloc = pOut->zMalloc;
61621     pOut->zMalloc = 0;
61622     sqlite3VdbeMemMove(pOut, pIn1);
61623     pIn1->zMalloc = u.ac.zMalloc;
61624     REGISTER_TRACE(u.ac.p2++, pOut);
61625     pIn1++;
61626     pOut++;
61627   }
61628   break;
61629 }
61630
61631 /* Opcode: Copy P1 P2 * * *
61632 **
61633 ** Make a copy of register P1 into register P2.
61634 **
61635 ** This instruction makes a deep copy of the value.  A duplicate
61636 ** is made of any string or blob constant.  See also OP_SCopy.
61637 */
61638 case OP_Copy: {             /* in1, out2 */
61639   pIn1 = &aMem[pOp->p1];
61640   pOut = &aMem[pOp->p2];
61641   assert( pOut!=pIn1 );
61642   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
61643   Deephemeralize(pOut);
61644   REGISTER_TRACE(pOp->p2, pOut);
61645   break;
61646 }
61647
61648 /* Opcode: SCopy P1 P2 * * *
61649 **
61650 ** Make a shallow copy of register P1 into register P2.
61651 **
61652 ** This instruction makes a shallow copy of the value.  If the value
61653 ** is a string or blob, then the copy is only a pointer to the
61654 ** original and hence if the original changes so will the copy.
61655 ** Worse, if the original is deallocated, the copy becomes invalid.
61656 ** Thus the program must guarantee that the original will not change
61657 ** during the lifetime of the copy.  Use OP_Copy to make a complete
61658 ** copy.
61659 */
61660 case OP_SCopy: {            /* in1, out2 */
61661   pIn1 = &aMem[pOp->p1];
61662   pOut = &aMem[pOp->p2];
61663   assert( pOut!=pIn1 );
61664   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
61665 #ifdef SQLITE_DEBUG
61666   if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
61667 #endif
61668   REGISTER_TRACE(pOp->p2, pOut);
61669   break;
61670 }
61671
61672 /* Opcode: ResultRow P1 P2 * * *
61673 **
61674 ** The registers P1 through P1+P2-1 contain a single row of
61675 ** results. This opcode causes the sqlite3_step() call to terminate
61676 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
61677 ** structure to provide access to the top P1 values as the result
61678 ** row.
61679 */
61680 case OP_ResultRow: {
61681 #if 0  /* local variables moved into u.ad */
61682   Mem *pMem;
61683   int i;
61684 #endif /* local variables moved into u.ad */
61685   assert( p->nResColumn==pOp->p2 );
61686   assert( pOp->p1>0 );
61687   assert( pOp->p1+pOp->p2<=p->nMem+1 );
61688
61689   /* If this statement has violated immediate foreign key constraints, do
61690   ** not return the number of rows modified. And do not RELEASE the statement
61691   ** transaction. It needs to be rolled back.  */
61692   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
61693     assert( db->flags&SQLITE_CountRows );
61694     assert( p->usesStmtJournal );
61695     break;
61696   }
61697
61698   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
61699   ** DML statements invoke this opcode to return the number of rows
61700   ** modified to the user. This is the only way that a VM that
61701   ** opens a statement transaction may invoke this opcode.
61702   **
61703   ** In case this is such a statement, close any statement transaction
61704   ** opened by this VM before returning control to the user. This is to
61705   ** ensure that statement-transactions are always nested, not overlapping.
61706   ** If the open statement-transaction is not closed here, then the user
61707   ** may step another VM that opens its own statement transaction. This
61708   ** may lead to overlapping statement transactions.
61709   **
61710   ** The statement transaction is never a top-level transaction.  Hence
61711   ** the RELEASE call below can never fail.
61712   */
61713   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
61714   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
61715   if( NEVER(rc!=SQLITE_OK) ){
61716     break;
61717   }
61718
61719   /* Invalidate all ephemeral cursor row caches */
61720   p->cacheCtr = (p->cacheCtr + 2)|1;
61721
61722   /* Make sure the results of the current row are \000 terminated
61723   ** and have an assigned type.  The results are de-ephemeralized as
61724   ** as side effect.
61725   */
61726   u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
61727   for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
61728     assert( memIsValid(&u.ad.pMem[u.ad.i]) );
61729     Deephemeralize(&u.ad.pMem[u.ad.i]);
61730     assert( (u.ad.pMem[u.ad.i].flags & MEM_Ephem)==0
61731             || (u.ad.pMem[u.ad.i].flags & (MEM_Str|MEM_Blob))==0 );
61732     sqlite3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
61733     sqlite3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
61734     REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
61735   }
61736   if( db->mallocFailed ) goto no_mem;
61737
61738   /* Return SQLITE_ROW
61739   */
61740   p->pc = pc + 1;
61741   rc = SQLITE_ROW;
61742   goto vdbe_return;
61743 }
61744
61745 /* Opcode: Concat P1 P2 P3 * *
61746 **
61747 ** Add the text in register P1 onto the end of the text in
61748 ** register P2 and store the result in register P3.
61749 ** If either the P1 or P2 text are NULL then store NULL in P3.
61750 **
61751 **   P3 = P2 || P1
61752 **
61753 ** It is illegal for P1 and P3 to be the same register. Sometimes,
61754 ** if P3 is the same register as P2, the implementation is able
61755 ** to avoid a memcpy().
61756 */
61757 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
61758 #if 0  /* local variables moved into u.ae */
61759   i64 nByte;
61760 #endif /* local variables moved into u.ae */
61761
61762   pIn1 = &aMem[pOp->p1];
61763   pIn2 = &aMem[pOp->p2];
61764   pOut = &aMem[pOp->p3];
61765   assert( pIn1!=pOut );
61766   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
61767     sqlite3VdbeMemSetNull(pOut);
61768     break;
61769   }
61770   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
61771   Stringify(pIn1, encoding);
61772   Stringify(pIn2, encoding);
61773   u.ae.nByte = pIn1->n + pIn2->n;
61774   if( u.ae.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
61775     goto too_big;
61776   }
61777   MemSetTypeFlag(pOut, MEM_Str);
61778   if( sqlite3VdbeMemGrow(pOut, (int)u.ae.nByte+2, pOut==pIn2) ){
61779     goto no_mem;
61780   }
61781   if( pOut!=pIn2 ){
61782     memcpy(pOut->z, pIn2->z, pIn2->n);
61783   }
61784   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
61785   pOut->z[u.ae.nByte] = 0;
61786   pOut->z[u.ae.nByte+1] = 0;
61787   pOut->flags |= MEM_Term;
61788   pOut->n = (int)u.ae.nByte;
61789   pOut->enc = encoding;
61790   UPDATE_MAX_BLOBSIZE(pOut);
61791   break;
61792 }
61793
61794 /* Opcode: Add P1 P2 P3 * *
61795 **
61796 ** Add the value in register P1 to the value in register P2
61797 ** and store the result in register P3.
61798 ** If either input is NULL, the result is NULL.
61799 */
61800 /* Opcode: Multiply P1 P2 P3 * *
61801 **
61802 **
61803 ** Multiply the value in register P1 by the value in register P2
61804 ** and store the result in register P3.
61805 ** If either input is NULL, the result is NULL.
61806 */
61807 /* Opcode: Subtract P1 P2 P3 * *
61808 **
61809 ** Subtract the value in register P1 from the value in register P2
61810 ** and store the result in register P3.
61811 ** If either input is NULL, the result is NULL.
61812 */
61813 /* Opcode: Divide P1 P2 P3 * *
61814 **
61815 ** Divide the value in register P1 by the value in register P2
61816 ** and store the result in register P3 (P3=P2/P1). If the value in 
61817 ** register P1 is zero, then the result is NULL. If either input is 
61818 ** NULL, the result is NULL.
61819 */
61820 /* Opcode: Remainder P1 P2 P3 * *
61821 **
61822 ** Compute the remainder after integer division of the value in
61823 ** register P1 by the value in register P2 and store the result in P3. 
61824 ** If the value in register P2 is zero the result is NULL.
61825 ** If either operand is NULL, the result is NULL.
61826 */
61827 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
61828 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
61829 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
61830 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
61831 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
61832 #if 0  /* local variables moved into u.af */
61833   int flags;      /* Combined MEM_* flags from both inputs */
61834   i64 iA;         /* Integer value of left operand */
61835   i64 iB;         /* Integer value of right operand */
61836   double rA;      /* Real value of left operand */
61837   double rB;      /* Real value of right operand */
61838 #endif /* local variables moved into u.af */
61839
61840   pIn1 = &aMem[pOp->p1];
61841   applyNumericAffinity(pIn1);
61842   pIn2 = &aMem[pOp->p2];
61843   applyNumericAffinity(pIn2);
61844   pOut = &aMem[pOp->p3];
61845   u.af.flags = pIn1->flags | pIn2->flags;
61846   if( (u.af.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
61847   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
61848     u.af.iA = pIn1->u.i;
61849     u.af.iB = pIn2->u.i;
61850     switch( pOp->opcode ){
61851       case OP_Add:         u.af.iB += u.af.iA;       break;
61852       case OP_Subtract:    u.af.iB -= u.af.iA;       break;
61853       case OP_Multiply:    u.af.iB *= u.af.iA;       break;
61854       case OP_Divide: {
61855         if( u.af.iA==0 ) goto arithmetic_result_is_null;
61856         /* Dividing the largest possible negative 64-bit integer (1<<63) by
61857         ** -1 returns an integer too large to store in a 64-bit data-type. On
61858         ** some architectures, the value overflows to (1<<63). On others,
61859         ** a SIGFPE is issued. The following statement normalizes this
61860         ** behavior so that all architectures behave as if integer
61861         ** overflow occurred.
61862         */
61863         if( u.af.iA==-1 && u.af.iB==SMALLEST_INT64 ) u.af.iA = 1;
61864         u.af.iB /= u.af.iA;
61865         break;
61866       }
61867       default: {
61868         if( u.af.iA==0 ) goto arithmetic_result_is_null;
61869         if( u.af.iA==-1 ) u.af.iA = 1;
61870         u.af.iB %= u.af.iA;
61871         break;
61872       }
61873     }
61874     pOut->u.i = u.af.iB;
61875     MemSetTypeFlag(pOut, MEM_Int);
61876   }else{
61877     u.af.rA = sqlite3VdbeRealValue(pIn1);
61878     u.af.rB = sqlite3VdbeRealValue(pIn2);
61879     switch( pOp->opcode ){
61880       case OP_Add:         u.af.rB += u.af.rA;       break;
61881       case OP_Subtract:    u.af.rB -= u.af.rA;       break;
61882       case OP_Multiply:    u.af.rB *= u.af.rA;       break;
61883       case OP_Divide: {
61884         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
61885         if( u.af.rA==(double)0 ) goto arithmetic_result_is_null;
61886         u.af.rB /= u.af.rA;
61887         break;
61888       }
61889       default: {
61890         u.af.iA = (i64)u.af.rA;
61891         u.af.iB = (i64)u.af.rB;
61892         if( u.af.iA==0 ) goto arithmetic_result_is_null;
61893         if( u.af.iA==-1 ) u.af.iA = 1;
61894         u.af.rB = (double)(u.af.iB % u.af.iA);
61895         break;
61896       }
61897     }
61898 #ifdef SQLITE_OMIT_FLOATING_POINT
61899     pOut->u.i = u.af.rB;
61900     MemSetTypeFlag(pOut, MEM_Int);
61901 #else
61902     if( sqlite3IsNaN(u.af.rB) ){
61903       goto arithmetic_result_is_null;
61904     }
61905     pOut->r = u.af.rB;
61906     MemSetTypeFlag(pOut, MEM_Real);
61907     if( (u.af.flags & MEM_Real)==0 ){
61908       sqlite3VdbeIntegerAffinity(pOut);
61909     }
61910 #endif
61911   }
61912   break;
61913
61914 arithmetic_result_is_null:
61915   sqlite3VdbeMemSetNull(pOut);
61916   break;
61917 }
61918
61919 /* Opcode: CollSeq * * P4
61920 **
61921 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
61922 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
61923 ** be returned. This is used by the built-in min(), max() and nullif()
61924 ** functions.
61925 **
61926 ** The interface used by the implementation of the aforementioned functions
61927 ** to retrieve the collation sequence set by this opcode is not available
61928 ** publicly, only to user functions defined in func.c.
61929 */
61930 case OP_CollSeq: {
61931   assert( pOp->p4type==P4_COLLSEQ );
61932   break;
61933 }
61934
61935 /* Opcode: Function P1 P2 P3 P4 P5
61936 **
61937 ** Invoke a user function (P4 is a pointer to a Function structure that
61938 ** defines the function) with P5 arguments taken from register P2 and
61939 ** successors.  The result of the function is stored in register P3.
61940 ** Register P3 must not be one of the function inputs.
61941 **
61942 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
61943 ** function was determined to be constant at compile time. If the first
61944 ** argument was constant then bit 0 of P1 is set. This is used to determine
61945 ** whether meta data associated with a user function argument using the
61946 ** sqlite3_set_auxdata() API may be safely retained until the next
61947 ** invocation of this opcode.
61948 **
61949 ** See also: AggStep and AggFinal
61950 */
61951 case OP_Function: {
61952 #if 0  /* local variables moved into u.ag */
61953   int i;
61954   Mem *pArg;
61955   sqlite3_context ctx;
61956   sqlite3_value **apVal;
61957   int n;
61958 #endif /* local variables moved into u.ag */
61959
61960   u.ag.n = pOp->p5;
61961   u.ag.apVal = p->apArg;
61962   assert( u.ag.apVal || u.ag.n==0 );
61963   assert( pOp->p3>0 && pOp->p3<=p->nMem );
61964   pOut = &aMem[pOp->p3];
61965   memAboutToChange(p, pOut);
61966
61967   assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
61968   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
61969   u.ag.pArg = &aMem[pOp->p2];
61970   for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
61971     assert( memIsValid(u.ag.pArg) );
61972     u.ag.apVal[u.ag.i] = u.ag.pArg;
61973     Deephemeralize(u.ag.pArg);
61974     sqlite3VdbeMemStoreType(u.ag.pArg);
61975     REGISTER_TRACE(pOp->p2+u.ag.i, u.ag.pArg);
61976   }
61977
61978   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
61979   if( pOp->p4type==P4_FUNCDEF ){
61980     u.ag.ctx.pFunc = pOp->p4.pFunc;
61981     u.ag.ctx.pVdbeFunc = 0;
61982   }else{
61983     u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
61984     u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
61985   }
61986
61987   u.ag.ctx.s.flags = MEM_Null;
61988   u.ag.ctx.s.db = db;
61989   u.ag.ctx.s.xDel = 0;
61990   u.ag.ctx.s.zMalloc = 0;
61991
61992   /* The output cell may already have a buffer allocated. Move
61993   ** the pointer to u.ag.ctx.s so in case the user-function can use
61994   ** the already allocated buffer instead of allocating a new one.
61995   */
61996   sqlite3VdbeMemMove(&u.ag.ctx.s, pOut);
61997   MemSetTypeFlag(&u.ag.ctx.s, MEM_Null);
61998
61999   u.ag.ctx.isError = 0;
62000   if( u.ag.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
62001     assert( pOp>aOp );
62002     assert( pOp[-1].p4type==P4_COLLSEQ );
62003     assert( pOp[-1].opcode==OP_CollSeq );
62004     u.ag.ctx.pColl = pOp[-1].p4.pColl;
62005   }
62006   (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal); /* IMP: R-24505-23230 */
62007   if( db->mallocFailed ){
62008     /* Even though a malloc() has failed, the implementation of the
62009     ** user function may have called an sqlite3_result_XXX() function
62010     ** to return a value. The following call releases any resources
62011     ** associated with such a value.
62012     */
62013     sqlite3VdbeMemRelease(&u.ag.ctx.s);
62014     goto no_mem;
62015   }
62016
62017   /* If any auxiliary data functions have been called by this user function,
62018   ** immediately call the destructor for any non-static values.
62019   */
62020   if( u.ag.ctx.pVdbeFunc ){
62021     sqlite3VdbeDeleteAuxData(u.ag.ctx.pVdbeFunc, pOp->p1);
62022     pOp->p4.pVdbeFunc = u.ag.ctx.pVdbeFunc;
62023     pOp->p4type = P4_VDBEFUNC;
62024   }
62025
62026   /* If the function returned an error, throw an exception */
62027   if( u.ag.ctx.isError ){
62028     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ag.ctx.s));
62029     rc = u.ag.ctx.isError;
62030   }
62031
62032   /* Copy the result of the function into register P3 */
62033   sqlite3VdbeChangeEncoding(&u.ag.ctx.s, encoding);
62034   sqlite3VdbeMemMove(pOut, &u.ag.ctx.s);
62035   if( sqlite3VdbeMemTooBig(pOut) ){
62036     goto too_big;
62037   }
62038   REGISTER_TRACE(pOp->p3, pOut);
62039   UPDATE_MAX_BLOBSIZE(pOut);
62040   break;
62041 }
62042
62043 /* Opcode: BitAnd P1 P2 P3 * *
62044 **
62045 ** Take the bit-wise AND of the values in register P1 and P2 and
62046 ** store the result in register P3.
62047 ** If either input is NULL, the result is NULL.
62048 */
62049 /* Opcode: BitOr P1 P2 P3 * *
62050 **
62051 ** Take the bit-wise OR of the values in register P1 and P2 and
62052 ** store the result in register P3.
62053 ** If either input is NULL, the result is NULL.
62054 */
62055 /* Opcode: ShiftLeft P1 P2 P3 * *
62056 **
62057 ** Shift the integer value in register P2 to the left by the
62058 ** number of bits specified by the integer in register P1.
62059 ** Store the result in register P3.
62060 ** If either input is NULL, the result is NULL.
62061 */
62062 /* Opcode: ShiftRight P1 P2 P3 * *
62063 **
62064 ** Shift the integer value in register P2 to the right by the
62065 ** number of bits specified by the integer in register P1.
62066 ** Store the result in register P3.
62067 ** If either input is NULL, the result is NULL.
62068 */
62069 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
62070 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
62071 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
62072 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
62073 #if 0  /* local variables moved into u.ah */
62074   i64 a;
62075   i64 b;
62076 #endif /* local variables moved into u.ah */
62077
62078   pIn1 = &aMem[pOp->p1];
62079   pIn2 = &aMem[pOp->p2];
62080   pOut = &aMem[pOp->p3];
62081   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
62082     sqlite3VdbeMemSetNull(pOut);
62083     break;
62084   }
62085   u.ah.a = sqlite3VdbeIntValue(pIn2);
62086   u.ah.b = sqlite3VdbeIntValue(pIn1);
62087   switch( pOp->opcode ){
62088     case OP_BitAnd:      u.ah.a &= u.ah.b;     break;
62089     case OP_BitOr:       u.ah.a |= u.ah.b;     break;
62090     case OP_ShiftLeft:   u.ah.a <<= u.ah.b;    break;
62091     default:  assert( pOp->opcode==OP_ShiftRight );
62092                          u.ah.a >>= u.ah.b;    break;
62093   }
62094   pOut->u.i = u.ah.a;
62095   MemSetTypeFlag(pOut, MEM_Int);
62096   break;
62097 }
62098
62099 /* Opcode: AddImm  P1 P2 * * *
62100 ** 
62101 ** Add the constant P2 to the value in register P1.
62102 ** The result is always an integer.
62103 **
62104 ** To force any register to be an integer, just add 0.
62105 */
62106 case OP_AddImm: {            /* in1 */
62107   pIn1 = &aMem[pOp->p1];
62108   memAboutToChange(p, pIn1);
62109   sqlite3VdbeMemIntegerify(pIn1);
62110   pIn1->u.i += pOp->p2;
62111   break;
62112 }
62113
62114 /* Opcode: MustBeInt P1 P2 * * *
62115 ** 
62116 ** Force the value in register P1 to be an integer.  If the value
62117 ** in P1 is not an integer and cannot be converted into an integer
62118 ** without data loss, then jump immediately to P2, or if P2==0
62119 ** raise an SQLITE_MISMATCH exception.
62120 */
62121 case OP_MustBeInt: {            /* jump, in1 */
62122   pIn1 = &aMem[pOp->p1];
62123   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
62124   if( (pIn1->flags & MEM_Int)==0 ){
62125     if( pOp->p2==0 ){
62126       rc = SQLITE_MISMATCH;
62127       goto abort_due_to_error;
62128     }else{
62129       pc = pOp->p2 - 1;
62130     }
62131   }else{
62132     MemSetTypeFlag(pIn1, MEM_Int);
62133   }
62134   break;
62135 }
62136
62137 #ifndef SQLITE_OMIT_FLOATING_POINT
62138 /* Opcode: RealAffinity P1 * * * *
62139 **
62140 ** If register P1 holds an integer convert it to a real value.
62141 **
62142 ** This opcode is used when extracting information from a column that
62143 ** has REAL affinity.  Such column values may still be stored as
62144 ** integers, for space efficiency, but after extraction we want them
62145 ** to have only a real value.
62146 */
62147 case OP_RealAffinity: {                  /* in1 */
62148   pIn1 = &aMem[pOp->p1];
62149   if( pIn1->flags & MEM_Int ){
62150     sqlite3VdbeMemRealify(pIn1);
62151   }
62152   break;
62153 }
62154 #endif
62155
62156 #ifndef SQLITE_OMIT_CAST
62157 /* Opcode: ToText P1 * * * *
62158 **
62159 ** Force the value in register P1 to be text.
62160 ** If the value is numeric, convert it to a string using the
62161 ** equivalent of printf().  Blob values are unchanged and
62162 ** are afterwards simply interpreted as text.
62163 **
62164 ** A NULL value is not changed by this routine.  It remains NULL.
62165 */
62166 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
62167   pIn1 = &aMem[pOp->p1];
62168   memAboutToChange(p, pIn1);
62169   if( pIn1->flags & MEM_Null ) break;
62170   assert( MEM_Str==(MEM_Blob>>3) );
62171   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
62172   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
62173   rc = ExpandBlob(pIn1);
62174   assert( pIn1->flags & MEM_Str || db->mallocFailed );
62175   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
62176   UPDATE_MAX_BLOBSIZE(pIn1);
62177   break;
62178 }
62179
62180 /* Opcode: ToBlob P1 * * * *
62181 **
62182 ** Force the value in register P1 to be a BLOB.
62183 ** If the value is numeric, convert it to a string first.
62184 ** Strings are simply reinterpreted as blobs with no change
62185 ** to the underlying data.
62186 **
62187 ** A NULL value is not changed by this routine.  It remains NULL.
62188 */
62189 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
62190   pIn1 = &aMem[pOp->p1];
62191   if( pIn1->flags & MEM_Null ) break;
62192   if( (pIn1->flags & MEM_Blob)==0 ){
62193     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
62194     assert( pIn1->flags & MEM_Str || db->mallocFailed );
62195     MemSetTypeFlag(pIn1, MEM_Blob);
62196   }else{
62197     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
62198   }
62199   UPDATE_MAX_BLOBSIZE(pIn1);
62200   break;
62201 }
62202
62203 /* Opcode: ToNumeric P1 * * * *
62204 **
62205 ** Force the value in register P1 to be numeric (either an
62206 ** integer or a floating-point number.)
62207 ** If the value is text or blob, try to convert it to an using the
62208 ** equivalent of atoi() or atof() and store 0 if no such conversion 
62209 ** is possible.
62210 **
62211 ** A NULL value is not changed by this routine.  It remains NULL.
62212 */
62213 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
62214   pIn1 = &aMem[pOp->p1];
62215   sqlite3VdbeMemNumerify(pIn1);
62216   break;
62217 }
62218 #endif /* SQLITE_OMIT_CAST */
62219
62220 /* Opcode: ToInt P1 * * * *
62221 **
62222 ** Force the value in register P1 to be an integer.  If
62223 ** The value is currently a real number, drop its fractional part.
62224 ** If the value is text or blob, try to convert it to an integer using the
62225 ** equivalent of atoi() and store 0 if no such conversion is possible.
62226 **
62227 ** A NULL value is not changed by this routine.  It remains NULL.
62228 */
62229 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
62230   pIn1 = &aMem[pOp->p1];
62231   if( (pIn1->flags & MEM_Null)==0 ){
62232     sqlite3VdbeMemIntegerify(pIn1);
62233   }
62234   break;
62235 }
62236
62237 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
62238 /* Opcode: ToReal P1 * * * *
62239 **
62240 ** Force the value in register P1 to be a floating point number.
62241 ** If The value is currently an integer, convert it.
62242 ** If the value is text or blob, try to convert it to an integer using the
62243 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
62244 **
62245 ** A NULL value is not changed by this routine.  It remains NULL.
62246 */
62247 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
62248   pIn1 = &aMem[pOp->p1];
62249   memAboutToChange(p, pIn1);
62250   if( (pIn1->flags & MEM_Null)==0 ){
62251     sqlite3VdbeMemRealify(pIn1);
62252   }
62253   break;
62254 }
62255 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
62256
62257 /* Opcode: Lt P1 P2 P3 P4 P5
62258 **
62259 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
62260 ** jump to address P2.  
62261 **
62262 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
62263 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL 
62264 ** bit is clear then fall through if either operand is NULL.
62265 **
62266 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
62267 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
62268 ** to coerce both inputs according to this affinity before the
62269 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
62270 ** affinity is used. Note that the affinity conversions are stored
62271 ** back into the input registers P1 and P3.  So this opcode can cause
62272 ** persistent changes to registers P1 and P3.
62273 **
62274 ** Once any conversions have taken place, and neither value is NULL, 
62275 ** the values are compared. If both values are blobs then memcmp() is
62276 ** used to determine the results of the comparison.  If both values
62277 ** are text, then the appropriate collating function specified in
62278 ** P4 is  used to do the comparison.  If P4 is not specified then
62279 ** memcmp() is used to compare text string.  If both values are
62280 ** numeric, then a numeric comparison is used. If the two values
62281 ** are of different types, then numbers are considered less than
62282 ** strings and strings are considered less than blobs.
62283 **
62284 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
62285 ** store a boolean result (either 0, or 1, or NULL) in register P2.
62286 */
62287 /* Opcode: Ne P1 P2 P3 P4 P5
62288 **
62289 ** This works just like the Lt opcode except that the jump is taken if
62290 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
62291 ** additional information.
62292 **
62293 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
62294 ** true or false and is never NULL.  If both operands are NULL then the result
62295 ** of comparison is false.  If either operand is NULL then the result is true.
62296 ** If neither operand is NULL the the result is the same as it would be if
62297 ** the SQLITE_NULLEQ flag were omitted from P5.
62298 */
62299 /* Opcode: Eq P1 P2 P3 P4 P5
62300 **
62301 ** This works just like the Lt opcode except that the jump is taken if
62302 ** the operands in registers P1 and P3 are equal.
62303 ** See the Lt opcode for additional information.
62304 **
62305 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
62306 ** true or false and is never NULL.  If both operands are NULL then the result
62307 ** of comparison is true.  If either operand is NULL then the result is false.
62308 ** If neither operand is NULL the the result is the same as it would be if
62309 ** the SQLITE_NULLEQ flag were omitted from P5.
62310 */
62311 /* Opcode: Le P1 P2 P3 P4 P5
62312 **
62313 ** This works just like the Lt opcode except that the jump is taken if
62314 ** the content of register P3 is less than or equal to the content of
62315 ** register P1.  See the Lt opcode for additional information.
62316 */
62317 /* Opcode: Gt P1 P2 P3 P4 P5
62318 **
62319 ** This works just like the Lt opcode except that the jump is taken if
62320 ** the content of register P3 is greater than the content of
62321 ** register P1.  See the Lt opcode for additional information.
62322 */
62323 /* Opcode: Ge P1 P2 P3 P4 P5
62324 **
62325 ** This works just like the Lt opcode except that the jump is taken if
62326 ** the content of register P3 is greater than or equal to the content of
62327 ** register P1.  See the Lt opcode for additional information.
62328 */
62329 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
62330 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
62331 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
62332 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
62333 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
62334 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
62335 #if 0  /* local variables moved into u.ai */
62336   int res;            /* Result of the comparison of pIn1 against pIn3 */
62337   char affinity;      /* Affinity to use for comparison */
62338   u16 flags1;         /* Copy of initial value of pIn1->flags */
62339   u16 flags3;         /* Copy of initial value of pIn3->flags */
62340 #endif /* local variables moved into u.ai */
62341
62342   pIn1 = &aMem[pOp->p1];
62343   pIn3 = &aMem[pOp->p3];
62344   u.ai.flags1 = pIn1->flags;
62345   u.ai.flags3 = pIn3->flags;
62346   if( (pIn1->flags | pIn3->flags)&MEM_Null ){
62347     /* One or both operands are NULL */
62348     if( pOp->p5 & SQLITE_NULLEQ ){
62349       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
62350       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
62351       ** or not both operands are null.
62352       */
62353       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
62354       u.ai.res = (pIn1->flags & pIn3->flags & MEM_Null)==0;
62355     }else{
62356       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
62357       ** then the result is always NULL.
62358       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
62359       */
62360       if( pOp->p5 & SQLITE_STOREP2 ){
62361         pOut = &aMem[pOp->p2];
62362         MemSetTypeFlag(pOut, MEM_Null);
62363         REGISTER_TRACE(pOp->p2, pOut);
62364       }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
62365         pc = pOp->p2-1;
62366       }
62367       break;
62368     }
62369   }else{
62370     /* Neither operand is NULL.  Do a comparison. */
62371     u.ai.affinity = pOp->p5 & SQLITE_AFF_MASK;
62372     if( u.ai.affinity ){
62373       applyAffinity(pIn1, u.ai.affinity, encoding);
62374       applyAffinity(pIn3, u.ai.affinity, encoding);
62375       if( db->mallocFailed ) goto no_mem;
62376     }
62377
62378     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
62379     ExpandBlob(pIn1);
62380     ExpandBlob(pIn3);
62381     u.ai.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
62382   }
62383   switch( pOp->opcode ){
62384     case OP_Eq:    u.ai.res = u.ai.res==0;     break;
62385     case OP_Ne:    u.ai.res = u.ai.res!=0;     break;
62386     case OP_Lt:    u.ai.res = u.ai.res<0;      break;
62387     case OP_Le:    u.ai.res = u.ai.res<=0;     break;
62388     case OP_Gt:    u.ai.res = u.ai.res>0;      break;
62389     default:       u.ai.res = u.ai.res>=0;     break;
62390   }
62391
62392   if( pOp->p5 & SQLITE_STOREP2 ){
62393     pOut = &aMem[pOp->p2];
62394     memAboutToChange(p, pOut);
62395     MemSetTypeFlag(pOut, MEM_Int);
62396     pOut->u.i = u.ai.res;
62397     REGISTER_TRACE(pOp->p2, pOut);
62398   }else if( u.ai.res ){
62399     pc = pOp->p2-1;
62400   }
62401
62402   /* Undo any changes made by applyAffinity() to the input registers. */
62403   pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ai.flags1&MEM_TypeMask);
62404   pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ai.flags3&MEM_TypeMask);
62405   break;
62406 }
62407
62408 /* Opcode: Permutation * * * P4 *
62409 **
62410 ** Set the permutation used by the OP_Compare operator to be the array
62411 ** of integers in P4.
62412 **
62413 ** The permutation is only valid until the next OP_Permutation, OP_Compare,
62414 ** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
62415 ** immediately prior to the OP_Compare.
62416 */
62417 case OP_Permutation: {
62418   assert( pOp->p4type==P4_INTARRAY );
62419   assert( pOp->p4.ai );
62420   aPermute = pOp->p4.ai;
62421   break;
62422 }
62423
62424 /* Opcode: Compare P1 P2 P3 P4 *
62425 **
62426 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
62427 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
62428 ** the comparison for use by the next OP_Jump instruct.
62429 **
62430 ** P4 is a KeyInfo structure that defines collating sequences and sort
62431 ** orders for the comparison.  The permutation applies to registers
62432 ** only.  The KeyInfo elements are used sequentially.
62433 **
62434 ** The comparison is a sort comparison, so NULLs compare equal,
62435 ** NULLs are less than numbers, numbers are less than strings,
62436 ** and strings are less than blobs.
62437 */
62438 case OP_Compare: {
62439 #if 0  /* local variables moved into u.aj */
62440   int n;
62441   int i;
62442   int p1;
62443   int p2;
62444   const KeyInfo *pKeyInfo;
62445   int idx;
62446   CollSeq *pColl;    /* Collating sequence to use on this term */
62447   int bRev;          /* True for DESCENDING sort order */
62448 #endif /* local variables moved into u.aj */
62449
62450   u.aj.n = pOp->p3;
62451   u.aj.pKeyInfo = pOp->p4.pKeyInfo;
62452   assert( u.aj.n>0 );
62453   assert( u.aj.pKeyInfo!=0 );
62454   u.aj.p1 = pOp->p1;
62455   u.aj.p2 = pOp->p2;
62456 #if SQLITE_DEBUG
62457   if( aPermute ){
62458     int k, mx = 0;
62459     for(k=0; k<u.aj.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
62460     assert( u.aj.p1>0 && u.aj.p1+mx<=p->nMem+1 );
62461     assert( u.aj.p2>0 && u.aj.p2+mx<=p->nMem+1 );
62462   }else{
62463     assert( u.aj.p1>0 && u.aj.p1+u.aj.n<=p->nMem+1 );
62464     assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
62465   }
62466 #endif /* SQLITE_DEBUG */
62467   for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
62468     u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
62469     assert( memIsValid(&aMem[u.aj.p1+u.aj.idx]) );
62470     assert( memIsValid(&aMem[u.aj.p2+u.aj.idx]) );
62471     REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
62472     REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
62473     assert( u.aj.i<u.aj.pKeyInfo->nField );
62474     u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
62475     u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
62476     iCompare = sqlite3MemCompare(&aMem[u.aj.p1+u.aj.idx], &aMem[u.aj.p2+u.aj.idx], u.aj.pColl);
62477     if( iCompare ){
62478       if( u.aj.bRev ) iCompare = -iCompare;
62479       break;
62480     }
62481   }
62482   aPermute = 0;
62483   break;
62484 }
62485
62486 /* Opcode: Jump P1 P2 P3 * *
62487 **
62488 ** Jump to the instruction at address P1, P2, or P3 depending on whether
62489 ** in the most recent OP_Compare instruction the P1 vector was less than
62490 ** equal to, or greater than the P2 vector, respectively.
62491 */
62492 case OP_Jump: {             /* jump */
62493   if( iCompare<0 ){
62494     pc = pOp->p1 - 1;
62495   }else if( iCompare==0 ){
62496     pc = pOp->p2 - 1;
62497   }else{
62498     pc = pOp->p3 - 1;
62499   }
62500   break;
62501 }
62502
62503 /* Opcode: And P1 P2 P3 * *
62504 **
62505 ** Take the logical AND of the values in registers P1 and P2 and
62506 ** write the result into register P3.
62507 **
62508 ** If either P1 or P2 is 0 (false) then the result is 0 even if
62509 ** the other input is NULL.  A NULL and true or two NULLs give
62510 ** a NULL output.
62511 */
62512 /* Opcode: Or P1 P2 P3 * *
62513 **
62514 ** Take the logical OR of the values in register P1 and P2 and
62515 ** store the answer in register P3.
62516 **
62517 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
62518 ** even if the other input is NULL.  A NULL and false or two NULLs
62519 ** give a NULL output.
62520 */
62521 case OP_And:              /* same as TK_AND, in1, in2, out3 */
62522 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
62523 #if 0  /* local variables moved into u.ak */
62524   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
62525   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
62526 #endif /* local variables moved into u.ak */
62527
62528   pIn1 = &aMem[pOp->p1];
62529   if( pIn1->flags & MEM_Null ){
62530     u.ak.v1 = 2;
62531   }else{
62532     u.ak.v1 = sqlite3VdbeIntValue(pIn1)!=0;
62533   }
62534   pIn2 = &aMem[pOp->p2];
62535   if( pIn2->flags & MEM_Null ){
62536     u.ak.v2 = 2;
62537   }else{
62538     u.ak.v2 = sqlite3VdbeIntValue(pIn2)!=0;
62539   }
62540   if( pOp->opcode==OP_And ){
62541     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
62542     u.ak.v1 = and_logic[u.ak.v1*3+u.ak.v2];
62543   }else{
62544     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
62545     u.ak.v1 = or_logic[u.ak.v1*3+u.ak.v2];
62546   }
62547   pOut = &aMem[pOp->p3];
62548   if( u.ak.v1==2 ){
62549     MemSetTypeFlag(pOut, MEM_Null);
62550   }else{
62551     pOut->u.i = u.ak.v1;
62552     MemSetTypeFlag(pOut, MEM_Int);
62553   }
62554   break;
62555 }
62556
62557 /* Opcode: Not P1 P2 * * *
62558 **
62559 ** Interpret the value in register P1 as a boolean value.  Store the
62560 ** boolean complement in register P2.  If the value in register P1 is 
62561 ** NULL, then a NULL is stored in P2.
62562 */
62563 case OP_Not: {                /* same as TK_NOT, in1, out2 */
62564   pIn1 = &aMem[pOp->p1];
62565   pOut = &aMem[pOp->p2];
62566   if( pIn1->flags & MEM_Null ){
62567     sqlite3VdbeMemSetNull(pOut);
62568   }else{
62569     sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
62570   }
62571   break;
62572 }
62573
62574 /* Opcode: BitNot P1 P2 * * *
62575 **
62576 ** Interpret the content of register P1 as an integer.  Store the
62577 ** ones-complement of the P1 value into register P2.  If P1 holds
62578 ** a NULL then store a NULL in P2.
62579 */
62580 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
62581   pIn1 = &aMem[pOp->p1];
62582   pOut = &aMem[pOp->p2];
62583   if( pIn1->flags & MEM_Null ){
62584     sqlite3VdbeMemSetNull(pOut);
62585   }else{
62586     sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
62587   }
62588   break;
62589 }
62590
62591 /* Opcode: If P1 P2 P3 * *
62592 **
62593 ** Jump to P2 if the value in register P1 is true.  The value is
62594 ** is considered true if it is numeric and non-zero.  If the value
62595 ** in P1 is NULL then take the jump if P3 is true.
62596 */
62597 /* Opcode: IfNot P1 P2 P3 * *
62598 **
62599 ** Jump to P2 if the value in register P1 is False.  The value is
62600 ** is considered true if it has a numeric value of zero.  If the value
62601 ** in P1 is NULL then take the jump if P3 is true.
62602 */
62603 case OP_If:                 /* jump, in1 */
62604 case OP_IfNot: {            /* jump, in1 */
62605 #if 0  /* local variables moved into u.al */
62606   int c;
62607 #endif /* local variables moved into u.al */
62608   pIn1 = &aMem[pOp->p1];
62609   if( pIn1->flags & MEM_Null ){
62610     u.al.c = pOp->p3;
62611   }else{
62612 #ifdef SQLITE_OMIT_FLOATING_POINT
62613     u.al.c = sqlite3VdbeIntValue(pIn1)!=0;
62614 #else
62615     u.al.c = sqlite3VdbeRealValue(pIn1)!=0.0;
62616 #endif
62617     if( pOp->opcode==OP_IfNot ) u.al.c = !u.al.c;
62618   }
62619   if( u.al.c ){
62620     pc = pOp->p2-1;
62621   }
62622   break;
62623 }
62624
62625 /* Opcode: IsNull P1 P2 * * *
62626 **
62627 ** Jump to P2 if the value in register P1 is NULL.
62628 */
62629 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
62630   pIn1 = &aMem[pOp->p1];
62631   if( (pIn1->flags & MEM_Null)!=0 ){
62632     pc = pOp->p2 - 1;
62633   }
62634   break;
62635 }
62636
62637 /* Opcode: NotNull P1 P2 * * *
62638 **
62639 ** Jump to P2 if the value in register P1 is not NULL.  
62640 */
62641 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
62642   pIn1 = &aMem[pOp->p1];
62643   if( (pIn1->flags & MEM_Null)==0 ){
62644     pc = pOp->p2 - 1;
62645   }
62646   break;
62647 }
62648
62649 /* Opcode: Column P1 P2 P3 P4 P5
62650 **
62651 ** Interpret the data that cursor P1 points to as a structure built using
62652 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
62653 ** information about the format of the data.)  Extract the P2-th column
62654 ** from this record.  If there are less that (P2+1) 
62655 ** values in the record, extract a NULL.
62656 **
62657 ** The value extracted is stored in register P3.
62658 **
62659 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
62660 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
62661 ** the result.
62662 **
62663 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
62664 ** then the cache of the cursor is reset prior to extracting the column.
62665 ** The first OP_Column against a pseudo-table after the value of the content
62666 ** register has changed should have this bit set.
62667 */
62668 case OP_Column: {
62669 #if 0  /* local variables moved into u.am */
62670   u32 payloadSize;   /* Number of bytes in the record */
62671   i64 payloadSize64; /* Number of bytes in the record */
62672   int p1;            /* P1 value of the opcode */
62673   int p2;            /* column number to retrieve */
62674   VdbeCursor *pC;    /* The VDBE cursor */
62675   char *zRec;        /* Pointer to complete record-data */
62676   BtCursor *pCrsr;   /* The BTree cursor */
62677   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
62678   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
62679   int nField;        /* number of fields in the record */
62680   int len;           /* The length of the serialized data for the column */
62681   int i;             /* Loop counter */
62682   char *zData;       /* Part of the record being decoded */
62683   Mem *pDest;        /* Where to write the extracted value */
62684   Mem sMem;          /* For storing the record being decoded */
62685   u8 *zIdx;          /* Index into header */
62686   u8 *zEndHdr;       /* Pointer to first byte after the header */
62687   u32 offset;        /* Offset into the data */
62688   u32 szField;       /* Number of bytes in the content of a field */
62689   int szHdr;         /* Size of the header size field at start of record */
62690   int avail;         /* Number of bytes of available data */
62691   Mem *pReg;         /* PseudoTable input register */
62692 #endif /* local variables moved into u.am */
62693
62694
62695   u.am.p1 = pOp->p1;
62696   u.am.p2 = pOp->p2;
62697   u.am.pC = 0;
62698   memset(&u.am.sMem, 0, sizeof(u.am.sMem));
62699   assert( u.am.p1<p->nCursor );
62700   assert( pOp->p3>0 && pOp->p3<=p->nMem );
62701   u.am.pDest = &aMem[pOp->p3];
62702   memAboutToChange(p, u.am.pDest);
62703   MemSetTypeFlag(u.am.pDest, MEM_Null);
62704   u.am.zRec = 0;
62705
62706   /* This block sets the variable u.am.payloadSize to be the total number of
62707   ** bytes in the record.
62708   **
62709   ** u.am.zRec is set to be the complete text of the record if it is available.
62710   ** The complete record text is always available for pseudo-tables
62711   ** If the record is stored in a cursor, the complete record text
62712   ** might be available in the  u.am.pC->aRow cache.  Or it might not be.
62713   ** If the data is unavailable,  u.am.zRec is set to NULL.
62714   **
62715   ** We also compute the number of columns in the record.  For cursors,
62716   ** the number of columns is stored in the VdbeCursor.nField element.
62717   */
62718   u.am.pC = p->apCsr[u.am.p1];
62719   assert( u.am.pC!=0 );
62720 #ifndef SQLITE_OMIT_VIRTUALTABLE
62721   assert( u.am.pC->pVtabCursor==0 );
62722 #endif
62723   u.am.pCrsr = u.am.pC->pCursor;
62724   if( u.am.pCrsr!=0 ){
62725     /* The record is stored in a B-Tree */
62726     rc = sqlite3VdbeCursorMoveto(u.am.pC);
62727     if( rc ) goto abort_due_to_error;
62728     if( u.am.pC->nullRow ){
62729       u.am.payloadSize = 0;
62730     }else if( u.am.pC->cacheStatus==p->cacheCtr ){
62731       u.am.payloadSize = u.am.pC->payloadSize;
62732       u.am.zRec = (char*)u.am.pC->aRow;
62733     }else if( u.am.pC->isIndex ){
62734       assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
62735       rc = sqlite3BtreeKeySize(u.am.pCrsr, &u.am.payloadSize64);
62736       assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
62737       /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
62738       ** payload size, so it is impossible for u.am.payloadSize64 to be
62739       ** larger than 32 bits. */
62740       assert( (u.am.payloadSize64 & SQLITE_MAX_U32)==(u64)u.am.payloadSize64 );
62741       u.am.payloadSize = (u32)u.am.payloadSize64;
62742     }else{
62743       assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
62744       rc = sqlite3BtreeDataSize(u.am.pCrsr, &u.am.payloadSize);
62745       assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
62746     }
62747   }else if( u.am.pC->pseudoTableReg>0 ){
62748     u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
62749     assert( u.am.pReg->flags & MEM_Blob );
62750     assert( memIsValid(u.am.pReg) );
62751     u.am.payloadSize = u.am.pReg->n;
62752     u.am.zRec = u.am.pReg->z;
62753     u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
62754     assert( u.am.payloadSize==0 || u.am.zRec!=0 );
62755   }else{
62756     /* Consider the row to be NULL */
62757     u.am.payloadSize = 0;
62758   }
62759
62760   /* If u.am.payloadSize is 0, then just store a NULL */
62761   if( u.am.payloadSize==0 ){
62762     assert( u.am.pDest->flags&MEM_Null );
62763     goto op_column_out;
62764   }
62765   assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
62766   if( u.am.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
62767     goto too_big;
62768   }
62769
62770   u.am.nField = u.am.pC->nField;
62771   assert( u.am.p2<u.am.nField );
62772
62773   /* Read and parse the table header.  Store the results of the parse
62774   ** into the record header cache fields of the cursor.
62775   */
62776   u.am.aType = u.am.pC->aType;
62777   if( u.am.pC->cacheStatus==p->cacheCtr ){
62778     u.am.aOffset = u.am.pC->aOffset;
62779   }else{
62780     assert(u.am.aType);
62781     u.am.avail = 0;
62782     u.am.pC->aOffset = u.am.aOffset = &u.am.aType[u.am.nField];
62783     u.am.pC->payloadSize = u.am.payloadSize;
62784     u.am.pC->cacheStatus = p->cacheCtr;
62785
62786     /* Figure out how many bytes are in the header */
62787     if( u.am.zRec ){
62788       u.am.zData = u.am.zRec;
62789     }else{
62790       if( u.am.pC->isIndex ){
62791         u.am.zData = (char*)sqlite3BtreeKeyFetch(u.am.pCrsr, &u.am.avail);
62792       }else{
62793         u.am.zData = (char*)sqlite3BtreeDataFetch(u.am.pCrsr, &u.am.avail);
62794       }
62795       /* If KeyFetch()/DataFetch() managed to get the entire payload,
62796       ** save the payload in the u.am.pC->aRow cache.  That will save us from
62797       ** having to make additional calls to fetch the content portion of
62798       ** the record.
62799       */
62800       assert( u.am.avail>=0 );
62801       if( u.am.payloadSize <= (u32)u.am.avail ){
62802         u.am.zRec = u.am.zData;
62803         u.am.pC->aRow = (u8*)u.am.zData;
62804       }else{
62805         u.am.pC->aRow = 0;
62806       }
62807     }
62808     /* The following assert is true in all cases accept when
62809     ** the database file has been corrupted externally.
62810     **    assert( u.am.zRec!=0 || u.am.avail>=u.am.payloadSize || u.am.avail>=9 ); */
62811     u.am.szHdr = getVarint32((u8*)u.am.zData, u.am.offset);
62812
62813     /* Make sure a corrupt database has not given us an oversize header.
62814     ** Do this now to avoid an oversize memory allocation.
62815     **
62816     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
62817     ** types use so much data space that there can only be 4096 and 32 of
62818     ** them, respectively.  So the maximum header length results from a
62819     ** 3-byte type for each of the maximum of 32768 columns plus three
62820     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
62821     */
62822     if( u.am.offset > 98307 ){
62823       rc = SQLITE_CORRUPT_BKPT;
62824       goto op_column_out;
62825     }
62826
62827     /* Compute in u.am.len the number of bytes of data we need to read in order
62828     ** to get u.am.nField type values.  u.am.offset is an upper bound on this.  But
62829     ** u.am.nField might be significantly less than the true number of columns
62830     ** in the table, and in that case, 5*u.am.nField+3 might be smaller than u.am.offset.
62831     ** We want to minimize u.am.len in order to limit the size of the memory
62832     ** allocation, especially if a corrupt database file has caused u.am.offset
62833     ** to be oversized. Offset is limited to 98307 above.  But 98307 might
62834     ** still exceed Robson memory allocation limits on some configurations.
62835     ** On systems that cannot tolerate large memory allocations, u.am.nField*5+3
62836     ** will likely be much smaller since u.am.nField will likely be less than
62837     ** 20 or so.  This insures that Robson memory allocation limits are
62838     ** not exceeded even for corrupt database files.
62839     */
62840     u.am.len = u.am.nField*5 + 3;
62841     if( u.am.len > (int)u.am.offset ) u.am.len = (int)u.am.offset;
62842
62843     /* The KeyFetch() or DataFetch() above are fast and will get the entire
62844     ** record header in most cases.  But they will fail to get the complete
62845     ** record header if the record header does not fit on a single page
62846     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
62847     ** acquire the complete header text.
62848     */
62849     if( !u.am.zRec && u.am.avail<u.am.len ){
62850       u.am.sMem.flags = 0;
62851       u.am.sMem.db = 0;
62852       rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, 0, u.am.len, u.am.pC->isIndex, &u.am.sMem);
62853       if( rc!=SQLITE_OK ){
62854         goto op_column_out;
62855       }
62856       u.am.zData = u.am.sMem.z;
62857     }
62858     u.am.zEndHdr = (u8 *)&u.am.zData[u.am.len];
62859     u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr];
62860
62861     /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[]
62862     ** arrays.  u.am.aType[u.am.i] will contain the type integer for the u.am.i-th
62863     ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beginning
62864     ** of the record to the start of the data for the u.am.i-th column
62865     */
62866     for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){
62867       if( u.am.zIdx<u.am.zEndHdr ){
62868         u.am.aOffset[u.am.i] = u.am.offset;
62869         u.am.zIdx += getVarint32(u.am.zIdx, u.am.aType[u.am.i]);
62870         u.am.szField = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.i]);
62871         u.am.offset += u.am.szField;
62872         if( u.am.offset<u.am.szField ){  /* True if u.am.offset overflows */
62873           u.am.zIdx = &u.am.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
62874           break;
62875         }
62876       }else{
62877         /* If u.am.i is less that u.am.nField, then there are less fields in this
62878         ** record than SetNumColumns indicated there are columns in the
62879         ** table. Set the u.am.offset for any extra columns not present in
62880         ** the record to 0. This tells code below to store a NULL
62881         ** instead of deserializing a value from the record.
62882         */
62883         u.am.aOffset[u.am.i] = 0;
62884       }
62885     }
62886     sqlite3VdbeMemRelease(&u.am.sMem);
62887     u.am.sMem.flags = MEM_Null;
62888
62889     /* If we have read more header data than was contained in the header,
62890     ** or if the end of the last field appears to be past the end of the
62891     ** record, or if the end of the last field appears to be before the end
62892     ** of the record (when all fields present), then we must be dealing
62893     ** with a corrupt database.
62894     */
62895     if( (u.am.zIdx > u.am.zEndHdr) || (u.am.offset > u.am.payloadSize)
62896          || (u.am.zIdx==u.am.zEndHdr && u.am.offset!=u.am.payloadSize) ){
62897       rc = SQLITE_CORRUPT_BKPT;
62898       goto op_column_out;
62899     }
62900   }
62901
62902   /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then
62903   ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero,
62904   ** then there are not enough fields in the record to satisfy the
62905   ** request.  In this case, set the value NULL or to P4 if P4 is
62906   ** a pointer to a Mem object.
62907   */
62908   if( u.am.aOffset[u.am.p2] ){
62909     assert( rc==SQLITE_OK );
62910     if( u.am.zRec ){
62911       sqlite3VdbeMemReleaseExternal(u.am.pDest);
62912       sqlite3VdbeSerialGet((u8 *)&u.am.zRec[u.am.aOffset[u.am.p2]], u.am.aType[u.am.p2], u.am.pDest);
62913     }else{
62914       u.am.len = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.p2]);
62915       sqlite3VdbeMemMove(&u.am.sMem, u.am.pDest);
62916       rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, u.am.aOffset[u.am.p2], u.am.len, u.am.pC->isIndex, &u.am.sMem);
62917       if( rc!=SQLITE_OK ){
62918         goto op_column_out;
62919       }
62920       u.am.zData = u.am.sMem.z;
62921       sqlite3VdbeSerialGet((u8*)u.am.zData, u.am.aType[u.am.p2], u.am.pDest);
62922     }
62923     u.am.pDest->enc = encoding;
62924   }else{
62925     if( pOp->p4type==P4_MEM ){
62926       sqlite3VdbeMemShallowCopy(u.am.pDest, pOp->p4.pMem, MEM_Static);
62927     }else{
62928       assert( u.am.pDest->flags&MEM_Null );
62929     }
62930   }
62931
62932   /* If we dynamically allocated space to hold the data (in the
62933   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
62934   ** dynamically allocated space over to the u.am.pDest structure.
62935   ** This prevents a memory copy.
62936   */
62937   if( u.am.sMem.zMalloc ){
62938     assert( u.am.sMem.z==u.am.sMem.zMalloc );
62939     assert( !(u.am.pDest->flags & MEM_Dyn) );
62940     assert( !(u.am.pDest->flags & (MEM_Blob|MEM_Str)) || u.am.pDest->z==u.am.sMem.z );
62941     u.am.pDest->flags &= ~(MEM_Ephem|MEM_Static);
62942     u.am.pDest->flags |= MEM_Term;
62943     u.am.pDest->z = u.am.sMem.z;
62944     u.am.pDest->zMalloc = u.am.sMem.zMalloc;
62945   }
62946
62947   rc = sqlite3VdbeMemMakeWriteable(u.am.pDest);
62948
62949 op_column_out:
62950   UPDATE_MAX_BLOBSIZE(u.am.pDest);
62951   REGISTER_TRACE(pOp->p3, u.am.pDest);
62952   break;
62953 }
62954
62955 /* Opcode: Affinity P1 P2 * P4 *
62956 **
62957 ** Apply affinities to a range of P2 registers starting with P1.
62958 **
62959 ** P4 is a string that is P2 characters long. The nth character of the
62960 ** string indicates the column affinity that should be used for the nth
62961 ** memory cell in the range.
62962 */
62963 case OP_Affinity: {
62964 #if 0  /* local variables moved into u.an */
62965   const char *zAffinity;   /* The affinity to be applied */
62966   char cAff;               /* A single character of affinity */
62967 #endif /* local variables moved into u.an */
62968
62969   u.an.zAffinity = pOp->p4.z;
62970   assert( u.an.zAffinity!=0 );
62971   assert( u.an.zAffinity[pOp->p2]==0 );
62972   pIn1 = &aMem[pOp->p1];
62973   while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
62974     assert( pIn1 <= &p->aMem[p->nMem] );
62975     assert( memIsValid(pIn1) );
62976     ExpandBlob(pIn1);
62977     applyAffinity(pIn1, u.an.cAff, encoding);
62978     pIn1++;
62979   }
62980   break;
62981 }
62982
62983 /* Opcode: MakeRecord P1 P2 P3 P4 *
62984 **
62985 ** Convert P2 registers beginning with P1 into the [record format]
62986 ** use as a data record in a database table or as a key
62987 ** in an index.  The OP_Column opcode can decode the record later.
62988 **
62989 ** P4 may be a string that is P2 characters long.  The nth character of the
62990 ** string indicates the column affinity that should be used for the nth
62991 ** field of the index key.
62992 **
62993 ** The mapping from character to affinity is given by the SQLITE_AFF_
62994 ** macros defined in sqliteInt.h.
62995 **
62996 ** If P4 is NULL then all index fields have the affinity NONE.
62997 */
62998 case OP_MakeRecord: {
62999 #if 0  /* local variables moved into u.ao */
63000   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
63001   Mem *pRec;             /* The new record */
63002   u64 nData;             /* Number of bytes of data space */
63003   int nHdr;              /* Number of bytes of header space */
63004   i64 nByte;             /* Data space required for this record */
63005   int nZero;             /* Number of zero bytes at the end of the record */
63006   int nVarint;           /* Number of bytes in a varint */
63007   u32 serial_type;       /* Type field */
63008   Mem *pData0;           /* First field to be combined into the record */
63009   Mem *pLast;            /* Last field of the record */
63010   int nField;            /* Number of fields in the record */
63011   char *zAffinity;       /* The affinity string for the record */
63012   int file_format;       /* File format to use for encoding */
63013   int i;                 /* Space used in zNewRecord[] */
63014   int len;               /* Length of a field */
63015 #endif /* local variables moved into u.ao */
63016
63017   /* Assuming the record contains N fields, the record format looks
63018   ** like this:
63019   **
63020   ** ------------------------------------------------------------------------
63021   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
63022   ** ------------------------------------------------------------------------
63023   **
63024   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
63025   ** and so froth.
63026   **
63027   ** Each type field is a varint representing the serial type of the
63028   ** corresponding data element (see sqlite3VdbeSerialType()). The
63029   ** hdr-size field is also a varint which is the offset from the beginning
63030   ** of the record to data0.
63031   */
63032   u.ao.nData = 0;         /* Number of bytes of data space */
63033   u.ao.nHdr = 0;          /* Number of bytes of header space */
63034   u.ao.nByte = 0;         /* Data space required for this record */
63035   u.ao.nZero = 0;         /* Number of zero bytes at the end of the record */
63036   u.ao.nField = pOp->p1;
63037   u.ao.zAffinity = pOp->p4.z;
63038   assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
63039   u.ao.pData0 = &aMem[u.ao.nField];
63040   u.ao.nField = pOp->p2;
63041   u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
63042   u.ao.file_format = p->minWriteFileFormat;
63043
63044   /* Identify the output register */
63045   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
63046   pOut = &aMem[pOp->p3];
63047   memAboutToChange(p, pOut);
63048
63049   /* Loop through the elements that will make up the record to figure
63050   ** out how much space is required for the new record.
63051   */
63052   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
63053     assert( memIsValid(u.ao.pRec) );
63054     if( u.ao.zAffinity ){
63055       applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
63056     }
63057     if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
63058       sqlite3VdbeMemExpandBlob(u.ao.pRec);
63059     }
63060     u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
63061     u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.serial_type);
63062     u.ao.nData += u.ao.len;
63063     u.ao.nHdr += sqlite3VarintLen(u.ao.serial_type);
63064     if( u.ao.pRec->flags & MEM_Zero ){
63065       /* Only pure zero-filled BLOBs can be input to this Opcode.
63066       ** We do not allow blobs with a prefix and a zero-filled tail. */
63067       u.ao.nZero += u.ao.pRec->u.nZero;
63068     }else if( u.ao.len ){
63069       u.ao.nZero = 0;
63070     }
63071   }
63072
63073   /* Add the initial header varint and total the size */
63074   u.ao.nHdr += u.ao.nVarint = sqlite3VarintLen(u.ao.nHdr);
63075   if( u.ao.nVarint<sqlite3VarintLen(u.ao.nHdr) ){
63076     u.ao.nHdr++;
63077   }
63078   u.ao.nByte = u.ao.nHdr+u.ao.nData-u.ao.nZero;
63079   if( u.ao.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
63080     goto too_big;
63081   }
63082
63083   /* Make sure the output register has a buffer large enough to store
63084   ** the new record. The output register (pOp->p3) is not allowed to
63085   ** be one of the input registers (because the following call to
63086   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
63087   */
63088   if( sqlite3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
63089     goto no_mem;
63090   }
63091   u.ao.zNewRecord = (u8 *)pOut->z;
63092
63093   /* Write the record */
63094   u.ao.i = putVarint32(u.ao.zNewRecord, u.ao.nHdr);
63095   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
63096     u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
63097     u.ao.i += putVarint32(&u.ao.zNewRecord[u.ao.i], u.ao.serial_type);      /* serial type */
63098   }
63099   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){  /* serial data */
63100     u.ao.i += sqlite3VdbeSerialPut(&u.ao.zNewRecord[u.ao.i], (int)(u.ao.nByte-u.ao.i), u.ao.pRec,u.ao.file_format);
63101   }
63102   assert( u.ao.i==u.ao.nByte );
63103
63104   assert( pOp->p3>0 && pOp->p3<=p->nMem );
63105   pOut->n = (int)u.ao.nByte;
63106   pOut->flags = MEM_Blob | MEM_Dyn;
63107   pOut->xDel = 0;
63108   if( u.ao.nZero ){
63109     pOut->u.nZero = u.ao.nZero;
63110     pOut->flags |= MEM_Zero;
63111   }
63112   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
63113   REGISTER_TRACE(pOp->p3, pOut);
63114   UPDATE_MAX_BLOBSIZE(pOut);
63115   break;
63116 }
63117
63118 /* Opcode: Count P1 P2 * * *
63119 **
63120 ** Store the number of entries (an integer value) in the table or index 
63121 ** opened by cursor P1 in register P2
63122 */
63123 #ifndef SQLITE_OMIT_BTREECOUNT
63124 case OP_Count: {         /* out2-prerelease */
63125 #if 0  /* local variables moved into u.ap */
63126   i64 nEntry;
63127   BtCursor *pCrsr;
63128 #endif /* local variables moved into u.ap */
63129
63130   u.ap.pCrsr = p->apCsr[pOp->p1]->pCursor;
63131   if( u.ap.pCrsr ){
63132     rc = sqlite3BtreeCount(u.ap.pCrsr, &u.ap.nEntry);
63133   }else{
63134     u.ap.nEntry = 0;
63135   }
63136   pOut->u.i = u.ap.nEntry;
63137   break;
63138 }
63139 #endif
63140
63141 /* Opcode: Savepoint P1 * * P4 *
63142 **
63143 ** Open, release or rollback the savepoint named by parameter P4, depending
63144 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
63145 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
63146 */
63147 case OP_Savepoint: {
63148 #if 0  /* local variables moved into u.aq */
63149   int p1;                         /* Value of P1 operand */
63150   char *zName;                    /* Name of savepoint */
63151   int nName;
63152   Savepoint *pNew;
63153   Savepoint *pSavepoint;
63154   Savepoint *pTmp;
63155   int iSavepoint;
63156   int ii;
63157 #endif /* local variables moved into u.aq */
63158
63159   u.aq.p1 = pOp->p1;
63160   u.aq.zName = pOp->p4.z;
63161
63162   /* Assert that the u.aq.p1 parameter is valid. Also that if there is no open
63163   ** transaction, then there cannot be any savepoints.
63164   */
63165   assert( db->pSavepoint==0 || db->autoCommit==0 );
63166   assert( u.aq.p1==SAVEPOINT_BEGIN||u.aq.p1==SAVEPOINT_RELEASE||u.aq.p1==SAVEPOINT_ROLLBACK );
63167   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
63168   assert( checkSavepointCount(db) );
63169
63170   if( u.aq.p1==SAVEPOINT_BEGIN ){
63171     if( db->writeVdbeCnt>0 ){
63172       /* A new savepoint cannot be created if there are active write
63173       ** statements (i.e. open read/write incremental blob handles).
63174       */
63175       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
63176         "SQL statements in progress");
63177       rc = SQLITE_BUSY;
63178     }else{
63179       u.aq.nName = sqlite3Strlen30(u.aq.zName);
63180
63181       /* Create a new savepoint structure. */
63182       u.aq.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.aq.nName+1);
63183       if( u.aq.pNew ){
63184         u.aq.pNew->zName = (char *)&u.aq.pNew[1];
63185         memcpy(u.aq.pNew->zName, u.aq.zName, u.aq.nName+1);
63186
63187         /* If there is no open transaction, then mark this as a special
63188         ** "transaction savepoint". */
63189         if( db->autoCommit ){
63190           db->autoCommit = 0;
63191           db->isTransactionSavepoint = 1;
63192         }else{
63193           db->nSavepoint++;
63194         }
63195
63196         /* Link the new savepoint into the database handle's list. */
63197         u.aq.pNew->pNext = db->pSavepoint;
63198         db->pSavepoint = u.aq.pNew;
63199         u.aq.pNew->nDeferredCons = db->nDeferredCons;
63200       }
63201     }
63202   }else{
63203     u.aq.iSavepoint = 0;
63204
63205     /* Find the named savepoint. If there is no such savepoint, then an
63206     ** an error is returned to the user.  */
63207     for(
63208       u.aq.pSavepoint = db->pSavepoint;
63209       u.aq.pSavepoint && sqlite3StrICmp(u.aq.pSavepoint->zName, u.aq.zName);
63210       u.aq.pSavepoint = u.aq.pSavepoint->pNext
63211     ){
63212       u.aq.iSavepoint++;
63213     }
63214     if( !u.aq.pSavepoint ){
63215       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.aq.zName);
63216       rc = SQLITE_ERROR;
63217     }else if(
63218         db->writeVdbeCnt>0 || (u.aq.p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
63219     ){
63220       /* It is not possible to release (commit) a savepoint if there are
63221       ** active write statements. It is not possible to rollback a savepoint
63222       ** if there are any active statements at all.
63223       */
63224       sqlite3SetString(&p->zErrMsg, db,
63225         "cannot %s savepoint - SQL statements in progress",
63226         (u.aq.p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
63227       );
63228       rc = SQLITE_BUSY;
63229     }else{
63230
63231       /* Determine whether or not this is a transaction savepoint. If so,
63232       ** and this is a RELEASE command, then the current transaction
63233       ** is committed.
63234       */
63235       int isTransaction = u.aq.pSavepoint->pNext==0 && db->isTransactionSavepoint;
63236       if( isTransaction && u.aq.p1==SAVEPOINT_RELEASE ){
63237         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
63238           goto vdbe_return;
63239         }
63240         db->autoCommit = 1;
63241         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
63242           p->pc = pc;
63243           db->autoCommit = 0;
63244           p->rc = rc = SQLITE_BUSY;
63245           goto vdbe_return;
63246         }
63247         db->isTransactionSavepoint = 0;
63248         rc = p->rc;
63249       }else{
63250         u.aq.iSavepoint = db->nSavepoint - u.aq.iSavepoint - 1;
63251         for(u.aq.ii=0; u.aq.ii<db->nDb; u.aq.ii++){
63252           rc = sqlite3BtreeSavepoint(db->aDb[u.aq.ii].pBt, u.aq.p1, u.aq.iSavepoint);
63253           if( rc!=SQLITE_OK ){
63254             goto abort_due_to_error;
63255           }
63256         }
63257         if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
63258           sqlite3ExpirePreparedStatements(db);
63259           sqlite3ResetInternalSchema(db, 0);
63260           db->flags = (db->flags | SQLITE_InternChanges);
63261         }
63262       }
63263
63264       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
63265       ** savepoints nested inside of the savepoint being operated on. */
63266       while( db->pSavepoint!=u.aq.pSavepoint ){
63267         u.aq.pTmp = db->pSavepoint;
63268         db->pSavepoint = u.aq.pTmp->pNext;
63269         sqlite3DbFree(db, u.aq.pTmp);
63270         db->nSavepoint--;
63271       }
63272
63273       /* If it is a RELEASE, then destroy the savepoint being operated on
63274       ** too. If it is a ROLLBACK TO, then set the number of deferred
63275       ** constraint violations present in the database to the value stored
63276       ** when the savepoint was created.  */
63277       if( u.aq.p1==SAVEPOINT_RELEASE ){
63278         assert( u.aq.pSavepoint==db->pSavepoint );
63279         db->pSavepoint = u.aq.pSavepoint->pNext;
63280         sqlite3DbFree(db, u.aq.pSavepoint);
63281         if( !isTransaction ){
63282           db->nSavepoint--;
63283         }
63284       }else{
63285         db->nDeferredCons = u.aq.pSavepoint->nDeferredCons;
63286       }
63287     }
63288   }
63289
63290   break;
63291 }
63292
63293 /* Opcode: AutoCommit P1 P2 * * *
63294 **
63295 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
63296 ** back any currently active btree transactions. If there are any active
63297 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
63298 ** there are active writing VMs or active VMs that use shared cache.
63299 **
63300 ** This instruction causes the VM to halt.
63301 */
63302 case OP_AutoCommit: {
63303 #if 0  /* local variables moved into u.ar */
63304   int desiredAutoCommit;
63305   int iRollback;
63306   int turnOnAC;
63307 #endif /* local variables moved into u.ar */
63308
63309   u.ar.desiredAutoCommit = pOp->p1;
63310   u.ar.iRollback = pOp->p2;
63311   u.ar.turnOnAC = u.ar.desiredAutoCommit && !db->autoCommit;
63312   assert( u.ar.desiredAutoCommit==1 || u.ar.desiredAutoCommit==0 );
63313   assert( u.ar.desiredAutoCommit==1 || u.ar.iRollback==0 );
63314   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
63315
63316   if( u.ar.turnOnAC && u.ar.iRollback && db->activeVdbeCnt>1 ){
63317     /* If this instruction implements a ROLLBACK and other VMs are
63318     ** still running, and a transaction is active, return an error indicating
63319     ** that the other VMs must complete first.
63320     */
63321     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
63322         "SQL statements in progress");
63323     rc = SQLITE_BUSY;
63324   }else if( u.ar.turnOnAC && !u.ar.iRollback && db->writeVdbeCnt>0 ){
63325     /* If this instruction implements a COMMIT and other VMs are writing
63326     ** return an error indicating that the other VMs must complete first.
63327     */
63328     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
63329         "SQL statements in progress");
63330     rc = SQLITE_BUSY;
63331   }else if( u.ar.desiredAutoCommit!=db->autoCommit ){
63332     if( u.ar.iRollback ){
63333       assert( u.ar.desiredAutoCommit==1 );
63334       sqlite3RollbackAll(db);
63335       db->autoCommit = 1;
63336     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
63337       goto vdbe_return;
63338     }else{
63339       db->autoCommit = (u8)u.ar.desiredAutoCommit;
63340       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
63341         p->pc = pc;
63342         db->autoCommit = (u8)(1-u.ar.desiredAutoCommit);
63343         p->rc = rc = SQLITE_BUSY;
63344         goto vdbe_return;
63345       }
63346     }
63347     assert( db->nStatement==0 );
63348     sqlite3CloseSavepoints(db);
63349     if( p->rc==SQLITE_OK ){
63350       rc = SQLITE_DONE;
63351     }else{
63352       rc = SQLITE_ERROR;
63353     }
63354     goto vdbe_return;
63355   }else{
63356     sqlite3SetString(&p->zErrMsg, db,
63357         (!u.ar.desiredAutoCommit)?"cannot start a transaction within a transaction":(
63358         (u.ar.iRollback)?"cannot rollback - no transaction is active":
63359                    "cannot commit - no transaction is active"));
63360
63361     rc = SQLITE_ERROR;
63362   }
63363   break;
63364 }
63365
63366 /* Opcode: Transaction P1 P2 * * *
63367 **
63368 ** Begin a transaction.  The transaction ends when a Commit or Rollback
63369 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
63370 ** transaction might also be rolled back if an error is encountered.
63371 **
63372 ** P1 is the index of the database file on which the transaction is
63373 ** started.  Index 0 is the main database file and index 1 is the
63374 ** file used for temporary tables.  Indices of 2 or more are used for
63375 ** attached databases.
63376 **
63377 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
63378 ** obtained on the database file when a write-transaction is started.  No
63379 ** other process can start another write transaction while this transaction is
63380 ** underway.  Starting a write transaction also creates a rollback journal. A
63381 ** write transaction must be started before any changes can be made to the
63382 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
63383 ** on the file.
63384 **
63385 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
63386 ** true (this flag is set if the Vdbe may modify more than one row and may
63387 ** throw an ABORT exception), a statement transaction may also be opened.
63388 ** More specifically, a statement transaction is opened iff the database
63389 ** connection is currently not in autocommit mode, or if there are other
63390 ** active statements. A statement transaction allows the affects of this
63391 ** VDBE to be rolled back after an error without having to roll back the
63392 ** entire transaction. If no error is encountered, the statement transaction
63393 ** will automatically commit when the VDBE halts.
63394 **
63395 ** If P2 is zero, then a read-lock is obtained on the database file.
63396 */
63397 case OP_Transaction: {
63398 #if 0  /* local variables moved into u.as */
63399   Btree *pBt;
63400 #endif /* local variables moved into u.as */
63401
63402   assert( pOp->p1>=0 && pOp->p1<db->nDb );
63403   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
63404   u.as.pBt = db->aDb[pOp->p1].pBt;
63405
63406   if( u.as.pBt ){
63407     rc = sqlite3BtreeBeginTrans(u.as.pBt, pOp->p2);
63408     if( rc==SQLITE_BUSY ){
63409       p->pc = pc;
63410       p->rc = rc = SQLITE_BUSY;
63411       goto vdbe_return;
63412     }
63413     if( rc!=SQLITE_OK ){
63414       goto abort_due_to_error;
63415     }
63416
63417     if( pOp->p2 && p->usesStmtJournal
63418      && (db->autoCommit==0 || db->activeVdbeCnt>1)
63419     ){
63420       assert( sqlite3BtreeIsInTrans(u.as.pBt) );
63421       if( p->iStatement==0 ){
63422         assert( db->nStatement>=0 && db->nSavepoint>=0 );
63423         db->nStatement++;
63424         p->iStatement = db->nSavepoint + db->nStatement;
63425       }
63426       rc = sqlite3BtreeBeginStmt(u.as.pBt, p->iStatement);
63427
63428       /* Store the current value of the database handles deferred constraint
63429       ** counter. If the statement transaction needs to be rolled back,
63430       ** the value of this counter needs to be restored too.  */
63431       p->nStmtDefCons = db->nDeferredCons;
63432     }
63433   }
63434   break;
63435 }
63436
63437 /* Opcode: ReadCookie P1 P2 P3 * *
63438 **
63439 ** Read cookie number P3 from database P1 and write it into register P2.
63440 ** P3==1 is the schema version.  P3==2 is the database format.
63441 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
63442 ** the main database file and P1==1 is the database file used to store
63443 ** temporary tables.
63444 **
63445 ** There must be a read-lock on the database (either a transaction
63446 ** must be started or there must be an open cursor) before
63447 ** executing this instruction.
63448 */
63449 case OP_ReadCookie: {               /* out2-prerelease */
63450 #if 0  /* local variables moved into u.at */
63451   int iMeta;
63452   int iDb;
63453   int iCookie;
63454 #endif /* local variables moved into u.at */
63455
63456   u.at.iDb = pOp->p1;
63457   u.at.iCookie = pOp->p3;
63458   assert( pOp->p3<SQLITE_N_BTREE_META );
63459   assert( u.at.iDb>=0 && u.at.iDb<db->nDb );
63460   assert( db->aDb[u.at.iDb].pBt!=0 );
63461   assert( (p->btreeMask & (1<<u.at.iDb))!=0 );
63462
63463   sqlite3BtreeGetMeta(db->aDb[u.at.iDb].pBt, u.at.iCookie, (u32 *)&u.at.iMeta);
63464   pOut->u.i = u.at.iMeta;
63465   break;
63466 }
63467
63468 /* Opcode: SetCookie P1 P2 P3 * *
63469 **
63470 ** Write the content of register P3 (interpreted as an integer)
63471 ** into cookie number P2 of database P1.  P2==1 is the schema version.  
63472 ** P2==2 is the database format. P2==3 is the recommended pager cache 
63473 ** size, and so forth.  P1==0 is the main database file and P1==1 is the 
63474 ** database file used to store temporary tables.
63475 **
63476 ** A transaction must be started before executing this opcode.
63477 */
63478 case OP_SetCookie: {       /* in3 */
63479 #if 0  /* local variables moved into u.au */
63480   Db *pDb;
63481 #endif /* local variables moved into u.au */
63482   assert( pOp->p2<SQLITE_N_BTREE_META );
63483   assert( pOp->p1>=0 && pOp->p1<db->nDb );
63484   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
63485   u.au.pDb = &db->aDb[pOp->p1];
63486   assert( u.au.pDb->pBt!=0 );
63487   pIn3 = &aMem[pOp->p3];
63488   sqlite3VdbeMemIntegerify(pIn3);
63489   /* See note about index shifting on OP_ReadCookie */
63490   rc = sqlite3BtreeUpdateMeta(u.au.pDb->pBt, pOp->p2, (int)pIn3->u.i);
63491   if( pOp->p2==BTREE_SCHEMA_VERSION ){
63492     /* When the schema cookie changes, record the new cookie internally */
63493     u.au.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
63494     db->flags |= SQLITE_InternChanges;
63495   }else if( pOp->p2==BTREE_FILE_FORMAT ){
63496     /* Record changes in the file format */
63497     u.au.pDb->pSchema->file_format = (u8)pIn3->u.i;
63498   }
63499   if( pOp->p1==1 ){
63500     /* Invalidate all prepared statements whenever the TEMP database
63501     ** schema is changed.  Ticket #1644 */
63502     sqlite3ExpirePreparedStatements(db);
63503     p->expired = 0;
63504   }
63505   break;
63506 }
63507
63508 /* Opcode: VerifyCookie P1 P2 *
63509 **
63510 ** Check the value of global database parameter number 0 (the
63511 ** schema version) and make sure it is equal to P2.  
63512 ** P1 is the database number which is 0 for the main database file
63513 ** and 1 for the file holding temporary tables and some higher number
63514 ** for auxiliary databases.
63515 **
63516 ** The cookie changes its value whenever the database schema changes.
63517 ** This operation is used to detect when that the cookie has changed
63518 ** and that the current process needs to reread the schema.
63519 **
63520 ** Either a transaction needs to have been started or an OP_Open needs
63521 ** to be executed (to establish a read lock) before this opcode is
63522 ** invoked.
63523 */
63524 case OP_VerifyCookie: {
63525 #if 0  /* local variables moved into u.av */
63526   int iMeta;
63527   Btree *pBt;
63528 #endif /* local variables moved into u.av */
63529   assert( pOp->p1>=0 && pOp->p1<db->nDb );
63530   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
63531   u.av.pBt = db->aDb[pOp->p1].pBt;
63532   if( u.av.pBt ){
63533     sqlite3BtreeGetMeta(u.av.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.av.iMeta);
63534   }else{
63535     u.av.iMeta = 0;
63536   }
63537   if( u.av.iMeta!=pOp->p2 ){
63538     sqlite3DbFree(db, p->zErrMsg);
63539     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
63540     /* If the schema-cookie from the database file matches the cookie
63541     ** stored with the in-memory representation of the schema, do
63542     ** not reload the schema from the database file.
63543     **
63544     ** If virtual-tables are in use, this is not just an optimization.
63545     ** Often, v-tables store their data in other SQLite tables, which
63546     ** are queried from within xNext() and other v-table methods using
63547     ** prepared queries. If such a query is out-of-date, we do not want to
63548     ** discard the database schema, as the user code implementing the
63549     ** v-table would have to be ready for the sqlite3_vtab structure itself
63550     ** to be invalidated whenever sqlite3_step() is called from within
63551     ** a v-table method.
63552     */
63553     if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.av.iMeta ){
63554       sqlite3ResetInternalSchema(db, pOp->p1);
63555     }
63556
63557     sqlite3ExpirePreparedStatements(db);
63558     rc = SQLITE_SCHEMA;
63559   }
63560   break;
63561 }
63562
63563 /* Opcode: OpenRead P1 P2 P3 P4 P5
63564 **
63565 ** Open a read-only cursor for the database table whose root page is
63566 ** P2 in a database file.  The database file is determined by P3. 
63567 ** P3==0 means the main database, P3==1 means the database used for 
63568 ** temporary tables, and P3>1 means used the corresponding attached
63569 ** database.  Give the new cursor an identifier of P1.  The P1
63570 ** values need not be contiguous but all P1 values should be small integers.
63571 ** It is an error for P1 to be negative.
63572 **
63573 ** If P5!=0 then use the content of register P2 as the root page, not
63574 ** the value of P2 itself.
63575 **
63576 ** There will be a read lock on the database whenever there is an
63577 ** open cursor.  If the database was unlocked prior to this instruction
63578 ** then a read lock is acquired as part of this instruction.  A read
63579 ** lock allows other processes to read the database but prohibits
63580 ** any other process from modifying the database.  The read lock is
63581 ** released when all cursors are closed.  If this instruction attempts
63582 ** to get a read lock but fails, the script terminates with an
63583 ** SQLITE_BUSY error code.
63584 **
63585 ** The P4 value may be either an integer (P4_INT32) or a pointer to
63586 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
63587 ** structure, then said structure defines the content and collating 
63588 ** sequence of the index being opened. Otherwise, if P4 is an integer 
63589 ** value, it is set to the number of columns in the table.
63590 **
63591 ** See also OpenWrite.
63592 */
63593 /* Opcode: OpenWrite P1 P2 P3 P4 P5
63594 **
63595 ** Open a read/write cursor named P1 on the table or index whose root
63596 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
63597 ** root page.
63598 **
63599 ** The P4 value may be either an integer (P4_INT32) or a pointer to
63600 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
63601 ** structure, then said structure defines the content and collating 
63602 ** sequence of the index being opened. Otherwise, if P4 is an integer 
63603 ** value, it is set to the number of columns in the table, or to the
63604 ** largest index of any column of the table that is actually used.
63605 **
63606 ** This instruction works just like OpenRead except that it opens the cursor
63607 ** in read/write mode.  For a given table, there can be one or more read-only
63608 ** cursors or a single read/write cursor but not both.
63609 **
63610 ** See also OpenRead.
63611 */
63612 case OP_OpenRead:
63613 case OP_OpenWrite: {
63614 #if 0  /* local variables moved into u.aw */
63615   int nField;
63616   KeyInfo *pKeyInfo;
63617   int p2;
63618   int iDb;
63619   int wrFlag;
63620   Btree *pX;
63621   VdbeCursor *pCur;
63622   Db *pDb;
63623 #endif /* local variables moved into u.aw */
63624
63625   if( p->expired ){
63626     rc = SQLITE_ABORT;
63627     break;
63628   }
63629
63630   u.aw.nField = 0;
63631   u.aw.pKeyInfo = 0;
63632   u.aw.p2 = pOp->p2;
63633   u.aw.iDb = pOp->p3;
63634   assert( u.aw.iDb>=0 && u.aw.iDb<db->nDb );
63635   assert( (p->btreeMask & (1<<u.aw.iDb))!=0 );
63636   u.aw.pDb = &db->aDb[u.aw.iDb];
63637   u.aw.pX = u.aw.pDb->pBt;
63638   assert( u.aw.pX!=0 );
63639   if( pOp->opcode==OP_OpenWrite ){
63640     u.aw.wrFlag = 1;
63641     if( u.aw.pDb->pSchema->file_format < p->minWriteFileFormat ){
63642       p->minWriteFileFormat = u.aw.pDb->pSchema->file_format;
63643     }
63644   }else{
63645     u.aw.wrFlag = 0;
63646   }
63647   if( pOp->p5 ){
63648     assert( u.aw.p2>0 );
63649     assert( u.aw.p2<=p->nMem );
63650     pIn2 = &aMem[u.aw.p2];
63651     assert( memIsValid(pIn2) );
63652     assert( (pIn2->flags & MEM_Int)!=0 );
63653     sqlite3VdbeMemIntegerify(pIn2);
63654     u.aw.p2 = (int)pIn2->u.i;
63655     /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
63656     ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
63657     ** If there were a failure, the prepared statement would have halted
63658     ** before reaching this instruction. */
63659     if( NEVER(u.aw.p2<2) ) {
63660       rc = SQLITE_CORRUPT_BKPT;
63661       goto abort_due_to_error;
63662     }
63663   }
63664   if( pOp->p4type==P4_KEYINFO ){
63665     u.aw.pKeyInfo = pOp->p4.pKeyInfo;
63666     u.aw.pKeyInfo->enc = ENC(p->db);
63667     u.aw.nField = u.aw.pKeyInfo->nField+1;
63668   }else if( pOp->p4type==P4_INT32 ){
63669     u.aw.nField = pOp->p4.i;
63670   }
63671   assert( pOp->p1>=0 );
63672   u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
63673   if( u.aw.pCur==0 ) goto no_mem;
63674   u.aw.pCur->nullRow = 1;
63675   u.aw.pCur->isOrdered = 1;
63676   rc = sqlite3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
63677   u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
63678
63679   /* Since it performs no memory allocation or IO, the only values that
63680   ** sqlite3BtreeCursor() may return are SQLITE_EMPTY and SQLITE_OK.
63681   ** SQLITE_EMPTY is only returned when attempting to open the table
63682   ** rooted at page 1 of a zero-byte database.  */
63683   assert( rc==SQLITE_EMPTY || rc==SQLITE_OK );
63684   if( rc==SQLITE_EMPTY ){
63685     u.aw.pCur->pCursor = 0;
63686     rc = SQLITE_OK;
63687   }
63688
63689   /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
63690   ** SQLite used to check if the root-page flags were sane at this point
63691   ** and report database corruption if they were not, but this check has
63692   ** since moved into the btree layer.  */
63693   u.aw.pCur->isTable = pOp->p4type!=P4_KEYINFO;
63694   u.aw.pCur->isIndex = !u.aw.pCur->isTable;
63695   break;
63696 }
63697
63698 /* Opcode: OpenEphemeral P1 P2 * P4 *
63699 **
63700 ** Open a new cursor P1 to a transient table.
63701 ** The cursor is always opened read/write even if 
63702 ** the main database is read-only.  The ephemeral
63703 ** table is deleted automatically when the cursor is closed.
63704 **
63705 ** P2 is the number of columns in the ephemeral table.
63706 ** The cursor points to a BTree table if P4==0 and to a BTree index
63707 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
63708 ** that defines the format of keys in the index.
63709 **
63710 ** This opcode was once called OpenTemp.  But that created
63711 ** confusion because the term "temp table", might refer either
63712 ** to a TEMP table at the SQL level, or to a table opened by
63713 ** this opcode.  Then this opcode was call OpenVirtual.  But
63714 ** that created confusion with the whole virtual-table idea.
63715 */
63716 /* Opcode: OpenAutoindex P1 P2 * P4 *
63717 **
63718 ** This opcode works the same as OP_OpenEphemeral.  It has a
63719 ** different name to distinguish its use.  Tables created using
63720 ** by this opcode will be used for automatically created transient
63721 ** indices in joins.
63722 */
63723 case OP_OpenAutoindex: 
63724 case OP_OpenEphemeral: {
63725 #if 0  /* local variables moved into u.ax */
63726   VdbeCursor *pCx;
63727 #endif /* local variables moved into u.ax */
63728   static const int vfsFlags =
63729       SQLITE_OPEN_READWRITE |
63730       SQLITE_OPEN_CREATE |
63731       SQLITE_OPEN_EXCLUSIVE |
63732       SQLITE_OPEN_DELETEONCLOSE |
63733       SQLITE_OPEN_TRANSIENT_DB;
63734
63735   assert( pOp->p1>=0 );
63736   u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
63737   if( u.ax.pCx==0 ) goto no_mem;
63738   u.ax.pCx->nullRow = 1;
63739   rc = sqlite3BtreeOpen(0, db, &u.ax.pCx->pBt,
63740                         BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
63741   if( rc==SQLITE_OK ){
63742     rc = sqlite3BtreeBeginTrans(u.ax.pCx->pBt, 1);
63743   }
63744   if( rc==SQLITE_OK ){
63745     /* If a transient index is required, create it by calling
63746     ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
63747     ** opening it. If a transient table is required, just use the
63748     ** automatically created table with root-page 1 (an BLOB_INTKEY table).
63749     */
63750     if( pOp->p4.pKeyInfo ){
63751       int pgno;
63752       assert( pOp->p4type==P4_KEYINFO );
63753       rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_BLOBKEY);
63754       if( rc==SQLITE_OK ){
63755         assert( pgno==MASTER_ROOT+1 );
63756         rc = sqlite3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
63757                                 (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
63758         u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
63759         u.ax.pCx->pKeyInfo->enc = ENC(p->db);
63760       }
63761       u.ax.pCx->isTable = 0;
63762     }else{
63763       rc = sqlite3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
63764       u.ax.pCx->isTable = 1;
63765     }
63766   }
63767   u.ax.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
63768   u.ax.pCx->isIndex = !u.ax.pCx->isTable;
63769   break;
63770 }
63771
63772 /* Opcode: OpenPseudo P1 P2 P3 * *
63773 **
63774 ** Open a new cursor that points to a fake table that contains a single
63775 ** row of data.  The content of that one row in the content of memory
63776 ** register P2.  In other words, cursor P1 becomes an alias for the 
63777 ** MEM_Blob content contained in register P2.
63778 **
63779 ** A pseudo-table created by this opcode is used to hold a single
63780 ** row output from the sorter so that the row can be decomposed into
63781 ** individual columns using the OP_Column opcode.  The OP_Column opcode
63782 ** is the only cursor opcode that works with a pseudo-table.
63783 **
63784 ** P3 is the number of fields in the records that will be stored by
63785 ** the pseudo-table.
63786 */
63787 case OP_OpenPseudo: {
63788 #if 0  /* local variables moved into u.ay */
63789   VdbeCursor *pCx;
63790 #endif /* local variables moved into u.ay */
63791
63792   assert( pOp->p1>=0 );
63793   u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
63794   if( u.ay.pCx==0 ) goto no_mem;
63795   u.ay.pCx->nullRow = 1;
63796   u.ay.pCx->pseudoTableReg = pOp->p2;
63797   u.ay.pCx->isTable = 1;
63798   u.ay.pCx->isIndex = 0;
63799   break;
63800 }
63801
63802 /* Opcode: Close P1 * * * *
63803 **
63804 ** Close a cursor previously opened as P1.  If P1 is not
63805 ** currently open, this instruction is a no-op.
63806 */
63807 case OP_Close: {
63808   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63809   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
63810   p->apCsr[pOp->p1] = 0;
63811   break;
63812 }
63813
63814 /* Opcode: SeekGe P1 P2 P3 P4 *
63815 **
63816 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
63817 ** use the value in register P3 as the key.  If cursor P1 refers 
63818 ** to an SQL index, then P3 is the first in an array of P4 registers 
63819 ** that are used as an unpacked index key. 
63820 **
63821 ** Reposition cursor P1 so that  it points to the smallest entry that 
63822 ** is greater than or equal to the key value. If there are no records 
63823 ** greater than or equal to the key and P2 is not zero, then jump to P2.
63824 **
63825 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
63826 */
63827 /* Opcode: SeekGt P1 P2 P3 P4 *
63828 **
63829 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
63830 ** use the value in register P3 as a key. If cursor P1 refers 
63831 ** to an SQL index, then P3 is the first in an array of P4 registers 
63832 ** that are used as an unpacked index key. 
63833 **
63834 ** Reposition cursor P1 so that  it points to the smallest entry that 
63835 ** is greater than the key value. If there are no records greater than 
63836 ** the key and P2 is not zero, then jump to P2.
63837 **
63838 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
63839 */
63840 /* Opcode: SeekLt P1 P2 P3 P4 * 
63841 **
63842 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
63843 ** use the value in register P3 as a key. If cursor P1 refers 
63844 ** to an SQL index, then P3 is the first in an array of P4 registers 
63845 ** that are used as an unpacked index key. 
63846 **
63847 ** Reposition cursor P1 so that  it points to the largest entry that 
63848 ** is less than the key value. If there are no records less than 
63849 ** the key and P2 is not zero, then jump to P2.
63850 **
63851 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
63852 */
63853 /* Opcode: SeekLe P1 P2 P3 P4 *
63854 **
63855 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
63856 ** use the value in register P3 as a key. If cursor P1 refers 
63857 ** to an SQL index, then P3 is the first in an array of P4 registers 
63858 ** that are used as an unpacked index key. 
63859 **
63860 ** Reposition cursor P1 so that it points to the largest entry that 
63861 ** is less than or equal to the key value. If there are no records 
63862 ** less than or equal to the key and P2 is not zero, then jump to P2.
63863 **
63864 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
63865 */
63866 case OP_SeekLt:         /* jump, in3 */
63867 case OP_SeekLe:         /* jump, in3 */
63868 case OP_SeekGe:         /* jump, in3 */
63869 case OP_SeekGt: {       /* jump, in3 */
63870 #if 0  /* local variables moved into u.az */
63871   int res;
63872   int oc;
63873   VdbeCursor *pC;
63874   UnpackedRecord r;
63875   int nField;
63876   i64 iKey;      /* The rowid we are to seek to */
63877 #endif /* local variables moved into u.az */
63878
63879   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63880   assert( pOp->p2!=0 );
63881   u.az.pC = p->apCsr[pOp->p1];
63882   assert( u.az.pC!=0 );
63883   assert( u.az.pC->pseudoTableReg==0 );
63884   assert( OP_SeekLe == OP_SeekLt+1 );
63885   assert( OP_SeekGe == OP_SeekLt+2 );
63886   assert( OP_SeekGt == OP_SeekLt+3 );
63887   assert( u.az.pC->isOrdered );
63888   if( u.az.pC->pCursor!=0 ){
63889     u.az.oc = pOp->opcode;
63890     u.az.pC->nullRow = 0;
63891     if( u.az.pC->isTable ){
63892       /* The input value in P3 might be of any type: integer, real, string,
63893       ** blob, or NULL.  But it needs to be an integer before we can do
63894       ** the seek, so covert it. */
63895       pIn3 = &aMem[pOp->p3];
63896       applyNumericAffinity(pIn3);
63897       u.az.iKey = sqlite3VdbeIntValue(pIn3);
63898       u.az.pC->rowidIsValid = 0;
63899
63900       /* If the P3 value could not be converted into an integer without
63901       ** loss of information, then special processing is required... */
63902       if( (pIn3->flags & MEM_Int)==0 ){
63903         if( (pIn3->flags & MEM_Real)==0 ){
63904           /* If the P3 value cannot be converted into any kind of a number,
63905           ** then the seek is not possible, so jump to P2 */
63906           pc = pOp->p2 - 1;
63907           break;
63908         }
63909         /* If we reach this point, then the P3 value must be a floating
63910         ** point number. */
63911         assert( (pIn3->flags & MEM_Real)!=0 );
63912
63913         if( u.az.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.az.iKey || pIn3->r>0) ){
63914           /* The P3 value is too large in magnitude to be expressed as an
63915           ** integer. */
63916           u.az.res = 1;
63917           if( pIn3->r<0 ){
63918             if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
63919               rc = sqlite3BtreeFirst(u.az.pC->pCursor, &u.az.res);
63920               if( rc!=SQLITE_OK ) goto abort_due_to_error;
63921             }
63922           }else{
63923             if( u.az.oc<=OP_SeekLe ){  assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
63924               rc = sqlite3BtreeLast(u.az.pC->pCursor, &u.az.res);
63925               if( rc!=SQLITE_OK ) goto abort_due_to_error;
63926             }
63927           }
63928           if( u.az.res ){
63929             pc = pOp->p2 - 1;
63930           }
63931           break;
63932         }else if( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekGe ){
63933           /* Use the ceiling() function to convert real->int */
63934           if( pIn3->r > (double)u.az.iKey ) u.az.iKey++;
63935         }else{
63936           /* Use the floor() function to convert real->int */
63937           assert( u.az.oc==OP_SeekLe || u.az.oc==OP_SeekGt );
63938           if( pIn3->r < (double)u.az.iKey ) u.az.iKey--;
63939         }
63940       }
63941       rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, 0, (u64)u.az.iKey, 0, &u.az.res);
63942       if( rc!=SQLITE_OK ){
63943         goto abort_due_to_error;
63944       }
63945       if( u.az.res==0 ){
63946         u.az.pC->rowidIsValid = 1;
63947         u.az.pC->lastRowid = u.az.iKey;
63948       }
63949     }else{
63950       u.az.nField = pOp->p4.i;
63951       assert( pOp->p4type==P4_INT32 );
63952       assert( u.az.nField>0 );
63953       u.az.r.pKeyInfo = u.az.pC->pKeyInfo;
63954       u.az.r.nField = (u16)u.az.nField;
63955
63956       /* The next line of code computes as follows, only faster:
63957       **   if( u.az.oc==OP_SeekGt || u.az.oc==OP_SeekLe ){
63958       **     u.az.r.flags = UNPACKED_INCRKEY;
63959       **   }else{
63960       **     u.az.r.flags = 0;
63961       **   }
63962       */
63963       u.az.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.az.oc - OP_SeekLt)));
63964       assert( u.az.oc!=OP_SeekGt || u.az.r.flags==UNPACKED_INCRKEY );
63965       assert( u.az.oc!=OP_SeekLe || u.az.r.flags==UNPACKED_INCRKEY );
63966       assert( u.az.oc!=OP_SeekGe || u.az.r.flags==0 );
63967       assert( u.az.oc!=OP_SeekLt || u.az.r.flags==0 );
63968
63969       u.az.r.aMem = &aMem[pOp->p3];
63970 #ifdef SQLITE_DEBUG
63971       { int i; for(i=0; i<u.az.r.nField; i++) assert( memIsValid(&u.az.r.aMem[i]) ); }
63972 #endif
63973       ExpandBlob(u.az.r.aMem);
63974       rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, &u.az.r, 0, 0, &u.az.res);
63975       if( rc!=SQLITE_OK ){
63976         goto abort_due_to_error;
63977       }
63978       u.az.pC->rowidIsValid = 0;
63979     }
63980     u.az.pC->deferredMoveto = 0;
63981     u.az.pC->cacheStatus = CACHE_STALE;
63982 #ifdef SQLITE_TEST
63983     sqlite3_search_count++;
63984 #endif
63985     if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
63986       if( u.az.res<0 || (u.az.res==0 && u.az.oc==OP_SeekGt) ){
63987         rc = sqlite3BtreeNext(u.az.pC->pCursor, &u.az.res);
63988         if( rc!=SQLITE_OK ) goto abort_due_to_error;
63989         u.az.pC->rowidIsValid = 0;
63990       }else{
63991         u.az.res = 0;
63992       }
63993     }else{
63994       assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
63995       if( u.az.res>0 || (u.az.res==0 && u.az.oc==OP_SeekLt) ){
63996         rc = sqlite3BtreePrevious(u.az.pC->pCursor, &u.az.res);
63997         if( rc!=SQLITE_OK ) goto abort_due_to_error;
63998         u.az.pC->rowidIsValid = 0;
63999       }else{
64000         /* u.az.res might be negative because the table is empty.  Check to
64001         ** see if this is the case.
64002         */
64003         u.az.res = sqlite3BtreeEof(u.az.pC->pCursor);
64004       }
64005     }
64006     assert( pOp->p2>0 );
64007     if( u.az.res ){
64008       pc = pOp->p2 - 1;
64009     }
64010   }else{
64011     /* This happens when attempting to open the sqlite3_master table
64012     ** for read access returns SQLITE_EMPTY. In this case always
64013     ** take the jump (since there are no records in the table).
64014     */
64015     pc = pOp->p2 - 1;
64016   }
64017   break;
64018 }
64019
64020 /* Opcode: Seek P1 P2 * * *
64021 **
64022 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
64023 ** for P1 to move so that it points to the rowid given by P2.
64024 **
64025 ** This is actually a deferred seek.  Nothing actually happens until
64026 ** the cursor is used to read a record.  That way, if no reads
64027 ** occur, no unnecessary I/O happens.
64028 */
64029 case OP_Seek: {    /* in2 */
64030 #if 0  /* local variables moved into u.ba */
64031   VdbeCursor *pC;
64032 #endif /* local variables moved into u.ba */
64033
64034   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64035   u.ba.pC = p->apCsr[pOp->p1];
64036   assert( u.ba.pC!=0 );
64037   if( ALWAYS(u.ba.pC->pCursor!=0) ){
64038     assert( u.ba.pC->isTable );
64039     u.ba.pC->nullRow = 0;
64040     pIn2 = &aMem[pOp->p2];
64041     u.ba.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
64042     u.ba.pC->rowidIsValid = 0;
64043     u.ba.pC->deferredMoveto = 1;
64044   }
64045   break;
64046 }
64047   
64048
64049 /* Opcode: Found P1 P2 P3 P4 *
64050 **
64051 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
64052 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
64053 ** record.
64054 **
64055 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
64056 ** is a prefix of any entry in P1 then a jump is made to P2 and
64057 ** P1 is left pointing at the matching entry.
64058 */
64059 /* Opcode: NotFound P1 P2 P3 P4 *
64060 **
64061 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
64062 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
64063 ** record.
64064 ** 
64065 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
64066 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1 
64067 ** does contain an entry whose prefix matches the P3/P4 record then control
64068 ** falls through to the next instruction and P1 is left pointing at the
64069 ** matching entry.
64070 **
64071 ** See also: Found, NotExists, IsUnique
64072 */
64073 case OP_NotFound:       /* jump, in3 */
64074 case OP_Found: {        /* jump, in3 */
64075 #if 0  /* local variables moved into u.bb */
64076   int alreadyExists;
64077   VdbeCursor *pC;
64078   int res;
64079   UnpackedRecord *pIdxKey;
64080   UnpackedRecord r;
64081   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
64082 #endif /* local variables moved into u.bb */
64083
64084 #ifdef SQLITE_TEST
64085   sqlite3_found_count++;
64086 #endif
64087
64088   u.bb.alreadyExists = 0;
64089   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64090   assert( pOp->p4type==P4_INT32 );
64091   u.bb.pC = p->apCsr[pOp->p1];
64092   assert( u.bb.pC!=0 );
64093   pIn3 = &aMem[pOp->p3];
64094   if( ALWAYS(u.bb.pC->pCursor!=0) ){
64095
64096     assert( u.bb.pC->isTable==0 );
64097     if( pOp->p4.i>0 ){
64098       u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
64099       u.bb.r.nField = (u16)pOp->p4.i;
64100       u.bb.r.aMem = pIn3;
64101 #ifdef SQLITE_DEBUG
64102       { int i; for(i=0; i<u.bb.r.nField; i++) assert( memIsValid(&u.bb.r.aMem[i]) ); }
64103 #endif
64104       u.bb.r.flags = UNPACKED_PREFIX_MATCH;
64105       u.bb.pIdxKey = &u.bb.r;
64106     }else{
64107       assert( pIn3->flags & MEM_Blob );
64108       assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
64109       u.bb.pIdxKey = sqlite3VdbeRecordUnpack(u.bb.pC->pKeyInfo, pIn3->n, pIn3->z,
64110                                         u.bb.aTempRec, sizeof(u.bb.aTempRec));
64111       if( u.bb.pIdxKey==0 ){
64112         goto no_mem;
64113       }
64114       u.bb.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
64115     }
64116     rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, u.bb.pIdxKey, 0, 0, &u.bb.res);
64117     if( pOp->p4.i==0 ){
64118       sqlite3VdbeDeleteUnpackedRecord(u.bb.pIdxKey);
64119     }
64120     if( rc!=SQLITE_OK ){
64121       break;
64122     }
64123     u.bb.alreadyExists = (u.bb.res==0);
64124     u.bb.pC->deferredMoveto = 0;
64125     u.bb.pC->cacheStatus = CACHE_STALE;
64126   }
64127   if( pOp->opcode==OP_Found ){
64128     if( u.bb.alreadyExists ) pc = pOp->p2 - 1;
64129   }else{
64130     if( !u.bb.alreadyExists ) pc = pOp->p2 - 1;
64131   }
64132   break;
64133 }
64134
64135 /* Opcode: IsUnique P1 P2 P3 P4 *
64136 **
64137 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
64138 ** no data and where the key are records generated by OP_MakeRecord with
64139 ** the list field being the integer ROWID of the entry that the index
64140 ** entry refers to.
64141 **
64142 ** The P3 register contains an integer record number. Call this record 
64143 ** number R. Register P4 is the first in a set of N contiguous registers
64144 ** that make up an unpacked index key that can be used with cursor P1.
64145 ** The value of N can be inferred from the cursor. N includes the rowid
64146 ** value appended to the end of the index record. This rowid value may
64147 ** or may not be the same as R.
64148 **
64149 ** If any of the N registers beginning with register P4 contains a NULL
64150 ** value, jump immediately to P2.
64151 **
64152 ** Otherwise, this instruction checks if cursor P1 contains an entry
64153 ** where the first (N-1) fields match but the rowid value at the end
64154 ** of the index entry is not R. If there is no such entry, control jumps
64155 ** to instruction P2. Otherwise, the rowid of the conflicting index
64156 ** entry is copied to register P3 and control falls through to the next
64157 ** instruction.
64158 **
64159 ** See also: NotFound, NotExists, Found
64160 */
64161 case OP_IsUnique: {        /* jump, in3 */
64162 #if 0  /* local variables moved into u.bc */
64163   u16 ii;
64164   VdbeCursor *pCx;
64165   BtCursor *pCrsr;
64166   u16 nField;
64167   Mem *aMx;
64168   UnpackedRecord r;                  /* B-Tree index search key */
64169   i64 R;                             /* Rowid stored in register P3 */
64170 #endif /* local variables moved into u.bc */
64171
64172   pIn3 = &aMem[pOp->p3];
64173   u.bc.aMx = &aMem[pOp->p4.i];
64174   /* Assert that the values of parameters P1 and P4 are in range. */
64175   assert( pOp->p4type==P4_INT32 );
64176   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
64177   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64178
64179   /* Find the index cursor. */
64180   u.bc.pCx = p->apCsr[pOp->p1];
64181   assert( u.bc.pCx->deferredMoveto==0 );
64182   u.bc.pCx->seekResult = 0;
64183   u.bc.pCx->cacheStatus = CACHE_STALE;
64184   u.bc.pCrsr = u.bc.pCx->pCursor;
64185
64186   /* If any of the values are NULL, take the jump. */
64187   u.bc.nField = u.bc.pCx->pKeyInfo->nField;
64188   for(u.bc.ii=0; u.bc.ii<u.bc.nField; u.bc.ii++){
64189     if( u.bc.aMx[u.bc.ii].flags & MEM_Null ){
64190       pc = pOp->p2 - 1;
64191       u.bc.pCrsr = 0;
64192       break;
64193     }
64194   }
64195   assert( (u.bc.aMx[u.bc.nField].flags & MEM_Null)==0 );
64196
64197   if( u.bc.pCrsr!=0 ){
64198     /* Populate the index search key. */
64199     u.bc.r.pKeyInfo = u.bc.pCx->pKeyInfo;
64200     u.bc.r.nField = u.bc.nField + 1;
64201     u.bc.r.flags = UNPACKED_PREFIX_SEARCH;
64202     u.bc.r.aMem = u.bc.aMx;
64203 #ifdef SQLITE_DEBUG
64204     { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
64205 #endif
64206
64207     /* Extract the value of u.bc.R from register P3. */
64208     sqlite3VdbeMemIntegerify(pIn3);
64209     u.bc.R = pIn3->u.i;
64210
64211     /* Search the B-Tree index. If no conflicting record is found, jump
64212     ** to P2. Otherwise, copy the rowid of the conflicting record to
64213     ** register P3 and fall through to the next instruction.  */
64214     rc = sqlite3BtreeMovetoUnpacked(u.bc.pCrsr, &u.bc.r, 0, 0, &u.bc.pCx->seekResult);
64215     if( (u.bc.r.flags & UNPACKED_PREFIX_SEARCH) || u.bc.r.rowid==u.bc.R ){
64216       pc = pOp->p2 - 1;
64217     }else{
64218       pIn3->u.i = u.bc.r.rowid;
64219     }
64220   }
64221   break;
64222 }
64223
64224 /* Opcode: NotExists P1 P2 P3 * *
64225 **
64226 ** Use the content of register P3 as a integer key.  If a record 
64227 ** with that key does not exist in table of P1, then jump to P2. 
64228 ** If the record does exist, then fall through.  The cursor is left 
64229 ** pointing to the record if it exists.
64230 **
64231 ** The difference between this operation and NotFound is that this
64232 ** operation assumes the key is an integer and that P1 is a table whereas
64233 ** NotFound assumes key is a blob constructed from MakeRecord and
64234 ** P1 is an index.
64235 **
64236 ** See also: Found, NotFound, IsUnique
64237 */
64238 case OP_NotExists: {        /* jump, in3 */
64239 #if 0  /* local variables moved into u.bd */
64240   VdbeCursor *pC;
64241   BtCursor *pCrsr;
64242   int res;
64243   u64 iKey;
64244 #endif /* local variables moved into u.bd */
64245
64246   pIn3 = &aMem[pOp->p3];
64247   assert( pIn3->flags & MEM_Int );
64248   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64249   u.bd.pC = p->apCsr[pOp->p1];
64250   assert( u.bd.pC!=0 );
64251   assert( u.bd.pC->isTable );
64252   assert( u.bd.pC->pseudoTableReg==0 );
64253   u.bd.pCrsr = u.bd.pC->pCursor;
64254   if( u.bd.pCrsr!=0 ){
64255     u.bd.res = 0;
64256     u.bd.iKey = pIn3->u.i;
64257     rc = sqlite3BtreeMovetoUnpacked(u.bd.pCrsr, 0, u.bd.iKey, 0, &u.bd.res);
64258     u.bd.pC->lastRowid = pIn3->u.i;
64259     u.bd.pC->rowidIsValid = u.bd.res==0 ?1:0;
64260     u.bd.pC->nullRow = 0;
64261     u.bd.pC->cacheStatus = CACHE_STALE;
64262     u.bd.pC->deferredMoveto = 0;
64263     if( u.bd.res!=0 ){
64264       pc = pOp->p2 - 1;
64265       assert( u.bd.pC->rowidIsValid==0 );
64266     }
64267     u.bd.pC->seekResult = u.bd.res;
64268   }else{
64269     /* This happens when an attempt to open a read cursor on the
64270     ** sqlite_master table returns SQLITE_EMPTY.
64271     */
64272     pc = pOp->p2 - 1;
64273     assert( u.bd.pC->rowidIsValid==0 );
64274     u.bd.pC->seekResult = 0;
64275   }
64276   break;
64277 }
64278
64279 /* Opcode: Sequence P1 P2 * * *
64280 **
64281 ** Find the next available sequence number for cursor P1.
64282 ** Write the sequence number into register P2.
64283 ** The sequence number on the cursor is incremented after this
64284 ** instruction.  
64285 */
64286 case OP_Sequence: {           /* out2-prerelease */
64287   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64288   assert( p->apCsr[pOp->p1]!=0 );
64289   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
64290   break;
64291 }
64292
64293
64294 /* Opcode: NewRowid P1 P2 P3 * *
64295 **
64296 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
64297 ** The record number is not previously used as a key in the database
64298 ** table that cursor P1 points to.  The new record number is written
64299 ** written to register P2.
64300 **
64301 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds 
64302 ** the largest previously generated record number. No new record numbers are
64303 ** allowed to be less than this value. When this value reaches its maximum, 
64304 ** a SQLITE_FULL error is generated. The P3 register is updated with the '
64305 ** generated record number. This P3 mechanism is used to help implement the
64306 ** AUTOINCREMENT feature.
64307 */
64308 case OP_NewRowid: {           /* out2-prerelease */
64309 #if 0  /* local variables moved into u.be */
64310   i64 v;                 /* The new rowid */
64311   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
64312   int res;               /* Result of an sqlite3BtreeLast() */
64313   int cnt;               /* Counter to limit the number of searches */
64314   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
64315   VdbeFrame *pFrame;     /* Root frame of VDBE */
64316 #endif /* local variables moved into u.be */
64317
64318   u.be.v = 0;
64319   u.be.res = 0;
64320   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64321   u.be.pC = p->apCsr[pOp->p1];
64322   assert( u.be.pC!=0 );
64323   if( NEVER(u.be.pC->pCursor==0) ){
64324     /* The zero initialization above is all that is needed */
64325   }else{
64326     /* The next rowid or record number (different terms for the same
64327     ** thing) is obtained in a two-step algorithm.
64328     **
64329     ** First we attempt to find the largest existing rowid and add one
64330     ** to that.  But if the largest existing rowid is already the maximum
64331     ** positive integer, we have to fall through to the second
64332     ** probabilistic algorithm
64333     **
64334     ** The second algorithm is to select a rowid at random and see if
64335     ** it already exists in the table.  If it does not exist, we have
64336     ** succeeded.  If the random rowid does exist, we select a new one
64337     ** and try again, up to 100 times.
64338     */
64339     assert( u.be.pC->isTable );
64340     u.be.cnt = 0;
64341
64342 #ifdef SQLITE_32BIT_ROWID
64343 #   define MAX_ROWID 0x7fffffff
64344 #else
64345     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
64346     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
64347     ** to provide the constant while making all compilers happy.
64348     */
64349 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
64350 #endif
64351
64352     if( !u.be.pC->useRandomRowid ){
64353       u.be.v = sqlite3BtreeGetCachedRowid(u.be.pC->pCursor);
64354       if( u.be.v==0 ){
64355         rc = sqlite3BtreeLast(u.be.pC->pCursor, &u.be.res);
64356         if( rc!=SQLITE_OK ){
64357           goto abort_due_to_error;
64358         }
64359         if( u.be.res ){
64360           u.be.v = 1;   /* IMP: R-61914-48074 */
64361         }else{
64362           assert( sqlite3BtreeCursorIsValid(u.be.pC->pCursor) );
64363           rc = sqlite3BtreeKeySize(u.be.pC->pCursor, &u.be.v);
64364           assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
64365           if( u.be.v==MAX_ROWID ){
64366             u.be.pC->useRandomRowid = 1;
64367           }else{
64368             u.be.v++;   /* IMP: R-29538-34987 */
64369           }
64370         }
64371       }
64372
64373 #ifndef SQLITE_OMIT_AUTOINCREMENT
64374       if( pOp->p3 ){
64375         /* Assert that P3 is a valid memory cell. */
64376         assert( pOp->p3>0 );
64377         if( p->pFrame ){
64378           for(u.be.pFrame=p->pFrame; u.be.pFrame->pParent; u.be.pFrame=u.be.pFrame->pParent);
64379           /* Assert that P3 is a valid memory cell. */
64380           assert( pOp->p3<=u.be.pFrame->nMem );
64381           u.be.pMem = &u.be.pFrame->aMem[pOp->p3];
64382         }else{
64383           /* Assert that P3 is a valid memory cell. */
64384           assert( pOp->p3<=p->nMem );
64385           u.be.pMem = &aMem[pOp->p3];
64386           memAboutToChange(p, u.be.pMem);
64387         }
64388         assert( memIsValid(u.be.pMem) );
64389
64390         REGISTER_TRACE(pOp->p3, u.be.pMem);
64391         sqlite3VdbeMemIntegerify(u.be.pMem);
64392         assert( (u.be.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
64393         if( u.be.pMem->u.i==MAX_ROWID || u.be.pC->useRandomRowid ){
64394           rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
64395           goto abort_due_to_error;
64396         }
64397         if( u.be.v<u.be.pMem->u.i+1 ){
64398           u.be.v = u.be.pMem->u.i + 1;
64399         }
64400         u.be.pMem->u.i = u.be.v;
64401       }
64402 #endif
64403
64404       sqlite3BtreeSetCachedRowid(u.be.pC->pCursor, u.be.v<MAX_ROWID ? u.be.v+1 : 0);
64405     }
64406     if( u.be.pC->useRandomRowid ){
64407       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
64408       ** largest possible integer (9223372036854775807) then the database
64409       ** engine starts picking positive candidate ROWIDs at random until
64410       ** it finds one that is not previously used. */
64411       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
64412                              ** an AUTOINCREMENT table. */
64413       /* on the first attempt, simply do one more than previous */
64414       u.be.v = db->lastRowid;
64415       u.be.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
64416       u.be.v++; /* ensure non-zero */
64417       u.be.cnt = 0;
64418       while(   ((rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, 0, (u64)u.be.v,
64419                                                  0, &u.be.res))==SQLITE_OK)
64420             && (u.be.res==0)
64421             && (++u.be.cnt<100)){
64422         /* collision - try another random rowid */
64423         sqlite3_randomness(sizeof(u.be.v), &u.be.v);
64424         if( u.be.cnt<5 ){
64425           /* try "small" random rowids for the initial attempts */
64426           u.be.v &= 0xffffff;
64427         }else{
64428           u.be.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
64429         }
64430         u.be.v++; /* ensure non-zero */
64431       }
64432       if( rc==SQLITE_OK && u.be.res==0 ){
64433         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
64434         goto abort_due_to_error;
64435       }
64436       assert( u.be.v>0 );  /* EV: R-40812-03570 */
64437     }
64438     u.be.pC->rowidIsValid = 0;
64439     u.be.pC->deferredMoveto = 0;
64440     u.be.pC->cacheStatus = CACHE_STALE;
64441   }
64442   pOut->u.i = u.be.v;
64443   break;
64444 }
64445
64446 /* Opcode: Insert P1 P2 P3 P4 P5
64447 **
64448 ** Write an entry into the table of cursor P1.  A new entry is
64449 ** created if it doesn't already exist or the data for an existing
64450 ** entry is overwritten.  The data is the value MEM_Blob stored in register
64451 ** number P2. The key is stored in register P3. The key must
64452 ** be a MEM_Int.
64453 **
64454 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
64455 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
64456 ** then rowid is stored for subsequent return by the
64457 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
64458 **
64459 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
64460 ** the last seek operation (OP_NotExists) was a success, then this
64461 ** operation will not attempt to find the appropriate row before doing
64462 ** the insert but will instead overwrite the row that the cursor is
64463 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
64464 ** has already positioned the cursor correctly.  This is an optimization
64465 ** that boosts performance by avoiding redundant seeks.
64466 **
64467 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
64468 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
64469 ** is part of an INSERT operation.  The difference is only important to
64470 ** the update hook.
64471 **
64472 ** Parameter P4 may point to a string containing the table-name, or
64473 ** may be NULL. If it is not NULL, then the update-hook 
64474 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
64475 **
64476 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
64477 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
64478 ** and register P2 becomes ephemeral.  If the cursor is changed, the
64479 ** value of register P2 will then change.  Make sure this does not
64480 ** cause any problems.)
64481 **
64482 ** This instruction only works on tables.  The equivalent instruction
64483 ** for indices is OP_IdxInsert.
64484 */
64485 /* Opcode: InsertInt P1 P2 P3 P4 P5
64486 **
64487 ** This works exactly like OP_Insert except that the key is the
64488 ** integer value P3, not the value of the integer stored in register P3.
64489 */
64490 case OP_Insert: 
64491 case OP_InsertInt: {
64492 #if 0  /* local variables moved into u.bf */
64493   Mem *pData;       /* MEM cell holding data for the record to be inserted */
64494   Mem *pKey;        /* MEM cell holding key  for the record */
64495   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
64496   VdbeCursor *pC;   /* Cursor to table into which insert is written */
64497   int nZero;        /* Number of zero-bytes to append */
64498   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
64499   const char *zDb;  /* database name - used by the update hook */
64500   const char *zTbl; /* Table name - used by the opdate hook */
64501   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
64502 #endif /* local variables moved into u.bf */
64503
64504   u.bf.pData = &aMem[pOp->p2];
64505   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64506   assert( memIsValid(u.bf.pData) );
64507   u.bf.pC = p->apCsr[pOp->p1];
64508   assert( u.bf.pC!=0 );
64509   assert( u.bf.pC->pCursor!=0 );
64510   assert( u.bf.pC->pseudoTableReg==0 );
64511   assert( u.bf.pC->isTable );
64512   REGISTER_TRACE(pOp->p2, u.bf.pData);
64513
64514   if( pOp->opcode==OP_Insert ){
64515     u.bf.pKey = &aMem[pOp->p3];
64516     assert( u.bf.pKey->flags & MEM_Int );
64517     assert( memIsValid(u.bf.pKey) );
64518     REGISTER_TRACE(pOp->p3, u.bf.pKey);
64519     u.bf.iKey = u.bf.pKey->u.i;
64520   }else{
64521     assert( pOp->opcode==OP_InsertInt );
64522     u.bf.iKey = pOp->p3;
64523   }
64524
64525   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
64526   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = u.bf.iKey;
64527   if( u.bf.pData->flags & MEM_Null ){
64528     u.bf.pData->z = 0;
64529     u.bf.pData->n = 0;
64530   }else{
64531     assert( u.bf.pData->flags & (MEM_Blob|MEM_Str) );
64532   }
64533   u.bf.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bf.pC->seekResult : 0);
64534   if( u.bf.pData->flags & MEM_Zero ){
64535     u.bf.nZero = u.bf.pData->u.nZero;
64536   }else{
64537     u.bf.nZero = 0;
64538   }
64539   sqlite3BtreeSetCachedRowid(u.bf.pC->pCursor, 0);
64540   rc = sqlite3BtreeInsert(u.bf.pC->pCursor, 0, u.bf.iKey,
64541                           u.bf.pData->z, u.bf.pData->n, u.bf.nZero,
64542                           pOp->p5 & OPFLAG_APPEND, u.bf.seekResult
64543   );
64544   u.bf.pC->rowidIsValid = 0;
64545   u.bf.pC->deferredMoveto = 0;
64546   u.bf.pC->cacheStatus = CACHE_STALE;
64547
64548   /* Invoke the update-hook if required. */
64549   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
64550     u.bf.zDb = db->aDb[u.bf.pC->iDb].zName;
64551     u.bf.zTbl = pOp->p4.z;
64552     u.bf.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
64553     assert( u.bf.pC->isTable );
64554     db->xUpdateCallback(db->pUpdateArg, u.bf.op, u.bf.zDb, u.bf.zTbl, u.bf.iKey);
64555     assert( u.bf.pC->iDb>=0 );
64556   }
64557   break;
64558 }
64559
64560 /* Opcode: Delete P1 P2 * P4 *
64561 **
64562 ** Delete the record at which the P1 cursor is currently pointing.
64563 **
64564 ** The cursor will be left pointing at either the next or the previous
64565 ** record in the table. If it is left pointing at the next record, then
64566 ** the next Next instruction will be a no-op.  Hence it is OK to delete
64567 ** a record from within an Next loop.
64568 **
64569 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
64570 ** incremented (otherwise not).
64571 **
64572 ** P1 must not be pseudo-table.  It has to be a real table with
64573 ** multiple rows.
64574 **
64575 ** If P4 is not NULL, then it is the name of the table that P1 is
64576 ** pointing to.  The update hook will be invoked, if it exists.
64577 ** If P4 is not NULL then the P1 cursor must have been positioned
64578 ** using OP_NotFound prior to invoking this opcode.
64579 */
64580 case OP_Delete: {
64581 #if 0  /* local variables moved into u.bg */
64582   i64 iKey;
64583   VdbeCursor *pC;
64584 #endif /* local variables moved into u.bg */
64585
64586   u.bg.iKey = 0;
64587   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64588   u.bg.pC = p->apCsr[pOp->p1];
64589   assert( u.bg.pC!=0 );
64590   assert( u.bg.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
64591
64592   /* If the update-hook will be invoked, set u.bg.iKey to the rowid of the
64593   ** row being deleted.
64594   */
64595   if( db->xUpdateCallback && pOp->p4.z ){
64596     assert( u.bg.pC->isTable );
64597     assert( u.bg.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
64598     u.bg.iKey = u.bg.pC->lastRowid;
64599   }
64600
64601   /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
64602   ** OP_Column on the same table without any intervening operations that
64603   ** might move or invalidate the cursor.  Hence cursor u.bg.pC is always pointing
64604   ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
64605   ** below is always a no-op and cannot fail.  We will run it anyhow, though,
64606   ** to guard against future changes to the code generator.
64607   **/
64608   assert( u.bg.pC->deferredMoveto==0 );
64609   rc = sqlite3VdbeCursorMoveto(u.bg.pC);
64610   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
64611
64612   sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, 0);
64613   rc = sqlite3BtreeDelete(u.bg.pC->pCursor);
64614   u.bg.pC->cacheStatus = CACHE_STALE;
64615
64616   /* Invoke the update-hook if required. */
64617   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
64618     const char *zDb = db->aDb[u.bg.pC->iDb].zName;
64619     const char *zTbl = pOp->p4.z;
64620     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bg.iKey);
64621     assert( u.bg.pC->iDb>=0 );
64622   }
64623   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
64624   break;
64625 }
64626 /* Opcode: ResetCount * * * * *
64627 **
64628 ** The value of the change counter is copied to the database handle
64629 ** change counter (returned by subsequent calls to sqlite3_changes()).
64630 ** Then the VMs internal change counter resets to 0.
64631 ** This is used by trigger programs.
64632 */
64633 case OP_ResetCount: {
64634   sqlite3VdbeSetChanges(db, p->nChange);
64635   p->nChange = 0;
64636   break;
64637 }
64638
64639 /* Opcode: RowData P1 P2 * * *
64640 **
64641 ** Write into register P2 the complete row data for cursor P1.
64642 ** There is no interpretation of the data.  
64643 ** It is just copied onto the P2 register exactly as 
64644 ** it is found in the database file.
64645 **
64646 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
64647 ** of a real table, not a pseudo-table.
64648 */
64649 /* Opcode: RowKey P1 P2 * * *
64650 **
64651 ** Write into register P2 the complete row key for cursor P1.
64652 ** There is no interpretation of the data.  
64653 ** The key is copied onto the P3 register exactly as 
64654 ** it is found in the database file.
64655 **
64656 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
64657 ** of a real table, not a pseudo-table.
64658 */
64659 case OP_RowKey:
64660 case OP_RowData: {
64661 #if 0  /* local variables moved into u.bh */
64662   VdbeCursor *pC;
64663   BtCursor *pCrsr;
64664   u32 n;
64665   i64 n64;
64666 #endif /* local variables moved into u.bh */
64667
64668   pOut = &aMem[pOp->p2];
64669   memAboutToChange(p, pOut);
64670
64671   /* Note that RowKey and RowData are really exactly the same instruction */
64672   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64673   u.bh.pC = p->apCsr[pOp->p1];
64674   assert( u.bh.pC->isTable || pOp->opcode==OP_RowKey );
64675   assert( u.bh.pC->isIndex || pOp->opcode==OP_RowData );
64676   assert( u.bh.pC!=0 );
64677   assert( u.bh.pC->nullRow==0 );
64678   assert( u.bh.pC->pseudoTableReg==0 );
64679   assert( u.bh.pC->pCursor!=0 );
64680   u.bh.pCrsr = u.bh.pC->pCursor;
64681   assert( sqlite3BtreeCursorIsValid(u.bh.pCrsr) );
64682
64683   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
64684   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
64685   ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
64686   ** a no-op and can never fail.  But we leave it in place as a safety.
64687   */
64688   assert( u.bh.pC->deferredMoveto==0 );
64689   rc = sqlite3VdbeCursorMoveto(u.bh.pC);
64690   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
64691
64692   if( u.bh.pC->isIndex ){
64693     assert( !u.bh.pC->isTable );
64694     rc = sqlite3BtreeKeySize(u.bh.pCrsr, &u.bh.n64);
64695     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
64696     if( u.bh.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
64697       goto too_big;
64698     }
64699     u.bh.n = (u32)u.bh.n64;
64700   }else{
64701     rc = sqlite3BtreeDataSize(u.bh.pCrsr, &u.bh.n);
64702     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
64703     if( u.bh.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
64704       goto too_big;
64705     }
64706   }
64707   if( sqlite3VdbeMemGrow(pOut, u.bh.n, 0) ){
64708     goto no_mem;
64709   }
64710   pOut->n = u.bh.n;
64711   MemSetTypeFlag(pOut, MEM_Blob);
64712   if( u.bh.pC->isIndex ){
64713     rc = sqlite3BtreeKey(u.bh.pCrsr, 0, u.bh.n, pOut->z);
64714   }else{
64715     rc = sqlite3BtreeData(u.bh.pCrsr, 0, u.bh.n, pOut->z);
64716   }
64717   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
64718   UPDATE_MAX_BLOBSIZE(pOut);
64719   break;
64720 }
64721
64722 /* Opcode: Rowid P1 P2 * * *
64723 **
64724 ** Store in register P2 an integer which is the key of the table entry that
64725 ** P1 is currently point to.
64726 **
64727 ** P1 can be either an ordinary table or a virtual table.  There used to
64728 ** be a separate OP_VRowid opcode for use with virtual tables, but this
64729 ** one opcode now works for both table types.
64730 */
64731 case OP_Rowid: {                 /* out2-prerelease */
64732 #if 0  /* local variables moved into u.bi */
64733   VdbeCursor *pC;
64734   i64 v;
64735   sqlite3_vtab *pVtab;
64736   const sqlite3_module *pModule;
64737 #endif /* local variables moved into u.bi */
64738
64739   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64740   u.bi.pC = p->apCsr[pOp->p1];
64741   assert( u.bi.pC!=0 );
64742   assert( u.bi.pC->pseudoTableReg==0 );
64743   if( u.bi.pC->nullRow ){
64744     pOut->flags = MEM_Null;
64745     break;
64746   }else if( u.bi.pC->deferredMoveto ){
64747     u.bi.v = u.bi.pC->movetoTarget;
64748 #ifndef SQLITE_OMIT_VIRTUALTABLE
64749   }else if( u.bi.pC->pVtabCursor ){
64750     u.bi.pVtab = u.bi.pC->pVtabCursor->pVtab;
64751     u.bi.pModule = u.bi.pVtab->pModule;
64752     assert( u.bi.pModule->xRowid );
64753     rc = u.bi.pModule->xRowid(u.bi.pC->pVtabCursor, &u.bi.v);
64754     importVtabErrMsg(p, u.bi.pVtab);
64755 #endif /* SQLITE_OMIT_VIRTUALTABLE */
64756   }else{
64757     assert( u.bi.pC->pCursor!=0 );
64758     rc = sqlite3VdbeCursorMoveto(u.bi.pC);
64759     if( rc ) goto abort_due_to_error;
64760     if( u.bi.pC->rowidIsValid ){
64761       u.bi.v = u.bi.pC->lastRowid;
64762     }else{
64763       rc = sqlite3BtreeKeySize(u.bi.pC->pCursor, &u.bi.v);
64764       assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
64765     }
64766   }
64767   pOut->u.i = u.bi.v;
64768   break;
64769 }
64770
64771 /* Opcode: NullRow P1 * * * *
64772 **
64773 ** Move the cursor P1 to a null row.  Any OP_Column operations
64774 ** that occur while the cursor is on the null row will always
64775 ** write a NULL.
64776 */
64777 case OP_NullRow: {
64778 #if 0  /* local variables moved into u.bj */
64779   VdbeCursor *pC;
64780 #endif /* local variables moved into u.bj */
64781
64782   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64783   u.bj.pC = p->apCsr[pOp->p1];
64784   assert( u.bj.pC!=0 );
64785   u.bj.pC->nullRow = 1;
64786   u.bj.pC->rowidIsValid = 0;
64787   if( u.bj.pC->pCursor ){
64788     sqlite3BtreeClearCursor(u.bj.pC->pCursor);
64789   }
64790   break;
64791 }
64792
64793 /* Opcode: Last P1 P2 * * *
64794 **
64795 ** The next use of the Rowid or Column or Next instruction for P1 
64796 ** will refer to the last entry in the database table or index.
64797 ** If the table or index is empty and P2>0, then jump immediately to P2.
64798 ** If P2 is 0 or if the table or index is not empty, fall through
64799 ** to the following instruction.
64800 */
64801 case OP_Last: {        /* jump */
64802 #if 0  /* local variables moved into u.bk */
64803   VdbeCursor *pC;
64804   BtCursor *pCrsr;
64805   int res;
64806 #endif /* local variables moved into u.bk */
64807
64808   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64809   u.bk.pC = p->apCsr[pOp->p1];
64810   assert( u.bk.pC!=0 );
64811   u.bk.pCrsr = u.bk.pC->pCursor;
64812   if( u.bk.pCrsr==0 ){
64813     u.bk.res = 1;
64814   }else{
64815     rc = sqlite3BtreeLast(u.bk.pCrsr, &u.bk.res);
64816   }
64817   u.bk.pC->nullRow = (u8)u.bk.res;
64818   u.bk.pC->deferredMoveto = 0;
64819   u.bk.pC->rowidIsValid = 0;
64820   u.bk.pC->cacheStatus = CACHE_STALE;
64821   if( pOp->p2>0 && u.bk.res ){
64822     pc = pOp->p2 - 1;
64823   }
64824   break;
64825 }
64826
64827
64828 /* Opcode: Sort P1 P2 * * *
64829 **
64830 ** This opcode does exactly the same thing as OP_Rewind except that
64831 ** it increments an undocumented global variable used for testing.
64832 **
64833 ** Sorting is accomplished by writing records into a sorting index,
64834 ** then rewinding that index and playing it back from beginning to
64835 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
64836 ** rewinding so that the global variable will be incremented and
64837 ** regression tests can determine whether or not the optimizer is
64838 ** correctly optimizing out sorts.
64839 */
64840 case OP_Sort: {        /* jump */
64841 #ifdef SQLITE_TEST
64842   sqlite3_sort_count++;
64843   sqlite3_search_count--;
64844 #endif
64845   p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
64846   /* Fall through into OP_Rewind */
64847 }
64848 /* Opcode: Rewind P1 P2 * * *
64849 **
64850 ** The next use of the Rowid or Column or Next instruction for P1 
64851 ** will refer to the first entry in the database table or index.
64852 ** If the table or index is empty and P2>0, then jump immediately to P2.
64853 ** If P2 is 0 or if the table or index is not empty, fall through
64854 ** to the following instruction.
64855 */
64856 case OP_Rewind: {        /* jump */
64857 #if 0  /* local variables moved into u.bl */
64858   VdbeCursor *pC;
64859   BtCursor *pCrsr;
64860   int res;
64861 #endif /* local variables moved into u.bl */
64862
64863   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64864   u.bl.pC = p->apCsr[pOp->p1];
64865   assert( u.bl.pC!=0 );
64866   u.bl.res = 1;
64867   if( (u.bl.pCrsr = u.bl.pC->pCursor)!=0 ){
64868     rc = sqlite3BtreeFirst(u.bl.pCrsr, &u.bl.res);
64869     u.bl.pC->atFirst = u.bl.res==0 ?1:0;
64870     u.bl.pC->deferredMoveto = 0;
64871     u.bl.pC->cacheStatus = CACHE_STALE;
64872     u.bl.pC->rowidIsValid = 0;
64873   }
64874   u.bl.pC->nullRow = (u8)u.bl.res;
64875   assert( pOp->p2>0 && pOp->p2<p->nOp );
64876   if( u.bl.res ){
64877     pc = pOp->p2 - 1;
64878   }
64879   break;
64880 }
64881
64882 /* Opcode: Next P1 P2 * * P5
64883 **
64884 ** Advance cursor P1 so that it points to the next key/data pair in its
64885 ** table or index.  If there are no more key/value pairs then fall through
64886 ** to the following instruction.  But if the cursor advance was successful,
64887 ** jump immediately to P2.
64888 **
64889 ** The P1 cursor must be for a real table, not a pseudo-table.
64890 **
64891 ** If P5 is positive and the jump is taken, then event counter
64892 ** number P5-1 in the prepared statement is incremented.
64893 **
64894 ** See also: Prev
64895 */
64896 /* Opcode: Prev P1 P2 * * P5
64897 **
64898 ** Back up cursor P1 so that it points to the previous key/data pair in its
64899 ** table or index.  If there is no previous key/value pairs then fall through
64900 ** to the following instruction.  But if the cursor backup was successful,
64901 ** jump immediately to P2.
64902 **
64903 ** The P1 cursor must be for a real table, not a pseudo-table.
64904 **
64905 ** If P5 is positive and the jump is taken, then event counter
64906 ** number P5-1 in the prepared statement is incremented.
64907 */
64908 case OP_Prev:          /* jump */
64909 case OP_Next: {        /* jump */
64910 #if 0  /* local variables moved into u.bm */
64911   VdbeCursor *pC;
64912   BtCursor *pCrsr;
64913   int res;
64914 #endif /* local variables moved into u.bm */
64915
64916   CHECK_FOR_INTERRUPT;
64917   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64918   assert( pOp->p5<=ArraySize(p->aCounter) );
64919   u.bm.pC = p->apCsr[pOp->p1];
64920   if( u.bm.pC==0 ){
64921     break;  /* See ticket #2273 */
64922   }
64923   u.bm.pCrsr = u.bm.pC->pCursor;
64924   if( u.bm.pCrsr==0 ){
64925     u.bm.pC->nullRow = 1;
64926     break;
64927   }
64928   u.bm.res = 1;
64929   assert( u.bm.pC->deferredMoveto==0 );
64930   rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(u.bm.pCrsr, &u.bm.res) :
64931                               sqlite3BtreePrevious(u.bm.pCrsr, &u.bm.res);
64932   u.bm.pC->nullRow = (u8)u.bm.res;
64933   u.bm.pC->cacheStatus = CACHE_STALE;
64934   if( u.bm.res==0 ){
64935     pc = pOp->p2 - 1;
64936     if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
64937 #ifdef SQLITE_TEST
64938     sqlite3_search_count++;
64939 #endif
64940   }
64941   u.bm.pC->rowidIsValid = 0;
64942   break;
64943 }
64944
64945 /* Opcode: IdxInsert P1 P2 P3 * P5
64946 **
64947 ** Register P2 holds a SQL index key made using the
64948 ** MakeRecord instructions.  This opcode writes that key
64949 ** into the index P1.  Data for the entry is nil.
64950 **
64951 ** P3 is a flag that provides a hint to the b-tree layer that this
64952 ** insert is likely to be an append.
64953 **
64954 ** This instruction only works for indices.  The equivalent instruction
64955 ** for tables is OP_Insert.
64956 */
64957 case OP_IdxInsert: {        /* in2 */
64958 #if 0  /* local variables moved into u.bn */
64959   VdbeCursor *pC;
64960   BtCursor *pCrsr;
64961   int nKey;
64962   const char *zKey;
64963 #endif /* local variables moved into u.bn */
64964
64965   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64966   u.bn.pC = p->apCsr[pOp->p1];
64967   assert( u.bn.pC!=0 );
64968   pIn2 = &aMem[pOp->p2];
64969   assert( pIn2->flags & MEM_Blob );
64970   u.bn.pCrsr = u.bn.pC->pCursor;
64971   if( ALWAYS(u.bn.pCrsr!=0) ){
64972     assert( u.bn.pC->isTable==0 );
64973     rc = ExpandBlob(pIn2);
64974     if( rc==SQLITE_OK ){
64975       u.bn.nKey = pIn2->n;
64976       u.bn.zKey = pIn2->z;
64977       rc = sqlite3BtreeInsert(u.bn.pCrsr, u.bn.zKey, u.bn.nKey, "", 0, 0, pOp->p3,
64978           ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bn.pC->seekResult : 0)
64979       );
64980       assert( u.bn.pC->deferredMoveto==0 );
64981       u.bn.pC->cacheStatus = CACHE_STALE;
64982     }
64983   }
64984   break;
64985 }
64986
64987 /* Opcode: IdxDelete P1 P2 P3 * *
64988 **
64989 ** The content of P3 registers starting at register P2 form
64990 ** an unpacked index key. This opcode removes that entry from the 
64991 ** index opened by cursor P1.
64992 */
64993 case OP_IdxDelete: {
64994 #if 0  /* local variables moved into u.bo */
64995   VdbeCursor *pC;
64996   BtCursor *pCrsr;
64997   int res;
64998   UnpackedRecord r;
64999 #endif /* local variables moved into u.bo */
65000
65001   assert( pOp->p3>0 );
65002   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
65003   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65004   u.bo.pC = p->apCsr[pOp->p1];
65005   assert( u.bo.pC!=0 );
65006   u.bo.pCrsr = u.bo.pC->pCursor;
65007   if( ALWAYS(u.bo.pCrsr!=0) ){
65008     u.bo.r.pKeyInfo = u.bo.pC->pKeyInfo;
65009     u.bo.r.nField = (u16)pOp->p3;
65010     u.bo.r.flags = 0;
65011     u.bo.r.aMem = &aMem[pOp->p2];
65012 #ifdef SQLITE_DEBUG
65013     { int i; for(i=0; i<u.bo.r.nField; i++) assert( memIsValid(&u.bo.r.aMem[i]) ); }
65014 #endif
65015     rc = sqlite3BtreeMovetoUnpacked(u.bo.pCrsr, &u.bo.r, 0, 0, &u.bo.res);
65016     if( rc==SQLITE_OK && u.bo.res==0 ){
65017       rc = sqlite3BtreeDelete(u.bo.pCrsr);
65018     }
65019     assert( u.bo.pC->deferredMoveto==0 );
65020     u.bo.pC->cacheStatus = CACHE_STALE;
65021   }
65022   break;
65023 }
65024
65025 /* Opcode: IdxRowid P1 P2 * * *
65026 **
65027 ** Write into register P2 an integer which is the last entry in the record at
65028 ** the end of the index key pointed to by cursor P1.  This integer should be
65029 ** the rowid of the table entry to which this index entry points.
65030 **
65031 ** See also: Rowid, MakeRecord.
65032 */
65033 case OP_IdxRowid: {              /* out2-prerelease */
65034 #if 0  /* local variables moved into u.bp */
65035   BtCursor *pCrsr;
65036   VdbeCursor *pC;
65037   i64 rowid;
65038 #endif /* local variables moved into u.bp */
65039
65040   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65041   u.bp.pC = p->apCsr[pOp->p1];
65042   assert( u.bp.pC!=0 );
65043   u.bp.pCrsr = u.bp.pC->pCursor;
65044   pOut->flags = MEM_Null;
65045   if( ALWAYS(u.bp.pCrsr!=0) ){
65046     rc = sqlite3VdbeCursorMoveto(u.bp.pC);
65047     if( NEVER(rc) ) goto abort_due_to_error;
65048     assert( u.bp.pC->deferredMoveto==0 );
65049     assert( u.bp.pC->isTable==0 );
65050     if( !u.bp.pC->nullRow ){
65051       rc = sqlite3VdbeIdxRowid(db, u.bp.pCrsr, &u.bp.rowid);
65052       if( rc!=SQLITE_OK ){
65053         goto abort_due_to_error;
65054       }
65055       pOut->u.i = u.bp.rowid;
65056       pOut->flags = MEM_Int;
65057     }
65058   }
65059   break;
65060 }
65061
65062 /* Opcode: IdxGE P1 P2 P3 P4 P5
65063 **
65064 ** The P4 register values beginning with P3 form an unpacked index 
65065 ** key that omits the ROWID.  Compare this key value against the index 
65066 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
65067 **
65068 ** If the P1 index entry is greater than or equal to the key value
65069 ** then jump to P2.  Otherwise fall through to the next instruction.
65070 **
65071 ** If P5 is non-zero then the key value is increased by an epsilon 
65072 ** prior to the comparison.  This make the opcode work like IdxGT except
65073 ** that if the key from register P3 is a prefix of the key in the cursor,
65074 ** the result is false whereas it would be true with IdxGT.
65075 */
65076 /* Opcode: IdxLT P1 P2 P3 P4 P5
65077 **
65078 ** The P4 register values beginning with P3 form an unpacked index 
65079 ** key that omits the ROWID.  Compare this key value against the index 
65080 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
65081 **
65082 ** If the P1 index entry is less than the key value then jump to P2.
65083 ** Otherwise fall through to the next instruction.
65084 **
65085 ** If P5 is non-zero then the key value is increased by an epsilon prior 
65086 ** to the comparison.  This makes the opcode work like IdxLE.
65087 */
65088 case OP_IdxLT:          /* jump */
65089 case OP_IdxGE: {        /* jump */
65090 #if 0  /* local variables moved into u.bq */
65091   VdbeCursor *pC;
65092   int res;
65093   UnpackedRecord r;
65094 #endif /* local variables moved into u.bq */
65095
65096   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
65097   u.bq.pC = p->apCsr[pOp->p1];
65098   assert( u.bq.pC!=0 );
65099   assert( u.bq.pC->isOrdered );
65100   if( ALWAYS(u.bq.pC->pCursor!=0) ){
65101     assert( u.bq.pC->deferredMoveto==0 );
65102     assert( pOp->p5==0 || pOp->p5==1 );
65103     assert( pOp->p4type==P4_INT32 );
65104     u.bq.r.pKeyInfo = u.bq.pC->pKeyInfo;
65105     u.bq.r.nField = (u16)pOp->p4.i;
65106     if( pOp->p5 ){
65107       u.bq.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
65108     }else{
65109       u.bq.r.flags = UNPACKED_IGNORE_ROWID;
65110     }
65111     u.bq.r.aMem = &aMem[pOp->p3];
65112 #ifdef SQLITE_DEBUG
65113     { int i; for(i=0; i<u.bq.r.nField; i++) assert( memIsValid(&u.bq.r.aMem[i]) ); }
65114 #endif
65115     rc = sqlite3VdbeIdxKeyCompare(u.bq.pC, &u.bq.r, &u.bq.res);
65116     if( pOp->opcode==OP_IdxLT ){
65117       u.bq.res = -u.bq.res;
65118     }else{
65119       assert( pOp->opcode==OP_IdxGE );
65120       u.bq.res++;
65121     }
65122     if( u.bq.res>0 ){
65123       pc = pOp->p2 - 1 ;
65124     }
65125   }
65126   break;
65127 }
65128
65129 /* Opcode: Destroy P1 P2 P3 * *
65130 **
65131 ** Delete an entire database table or index whose root page in the database
65132 ** file is given by P1.
65133 **
65134 ** The table being destroyed is in the main database file if P3==0.  If
65135 ** P3==1 then the table to be clear is in the auxiliary database file
65136 ** that is used to store tables create using CREATE TEMPORARY TABLE.
65137 **
65138 ** If AUTOVACUUM is enabled then it is possible that another root page
65139 ** might be moved into the newly deleted root page in order to keep all
65140 ** root pages contiguous at the beginning of the database.  The former
65141 ** value of the root page that moved - its value before the move occurred -
65142 ** is stored in register P2.  If no page 
65143 ** movement was required (because the table being dropped was already 
65144 ** the last one in the database) then a zero is stored in register P2.
65145 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
65146 **
65147 ** See also: Clear
65148 */
65149 case OP_Destroy: {     /* out2-prerelease */
65150 #if 0  /* local variables moved into u.br */
65151   int iMoved;
65152   int iCnt;
65153   Vdbe *pVdbe;
65154   int iDb;
65155 #endif /* local variables moved into u.br */
65156 #ifndef SQLITE_OMIT_VIRTUALTABLE
65157   u.br.iCnt = 0;
65158   for(u.br.pVdbe=db->pVdbe; u.br.pVdbe; u.br.pVdbe = u.br.pVdbe->pNext){
65159     if( u.br.pVdbe->magic==VDBE_MAGIC_RUN && u.br.pVdbe->inVtabMethod<2 && u.br.pVdbe->pc>=0 ){
65160       u.br.iCnt++;
65161     }
65162   }
65163 #else
65164   u.br.iCnt = db->activeVdbeCnt;
65165 #endif
65166   pOut->flags = MEM_Null;
65167   if( u.br.iCnt>1 ){
65168     rc = SQLITE_LOCKED;
65169     p->errorAction = OE_Abort;
65170   }else{
65171     u.br.iDb = pOp->p3;
65172     assert( u.br.iCnt==1 );
65173     assert( (p->btreeMask & (1<<u.br.iDb))!=0 );
65174     rc = sqlite3BtreeDropTable(db->aDb[u.br.iDb].pBt, pOp->p1, &u.br.iMoved);
65175     pOut->flags = MEM_Int;
65176     pOut->u.i = u.br.iMoved;
65177 #ifndef SQLITE_OMIT_AUTOVACUUM
65178     if( rc==SQLITE_OK && u.br.iMoved!=0 ){
65179       sqlite3RootPageMoved(&db->aDb[u.br.iDb], u.br.iMoved, pOp->p1);
65180       resetSchemaOnFault = 1;
65181     }
65182 #endif
65183   }
65184   break;
65185 }
65186
65187 /* Opcode: Clear P1 P2 P3
65188 **
65189 ** Delete all contents of the database table or index whose root page
65190 ** in the database file is given by P1.  But, unlike Destroy, do not
65191 ** remove the table or index from the database file.
65192 **
65193 ** The table being clear is in the main database file if P2==0.  If
65194 ** P2==1 then the table to be clear is in the auxiliary database file
65195 ** that is used to store tables create using CREATE TEMPORARY TABLE.
65196 **
65197 ** If the P3 value is non-zero, then the table referred to must be an
65198 ** intkey table (an SQL table, not an index). In this case the row change 
65199 ** count is incremented by the number of rows in the table being cleared. 
65200 ** If P3 is greater than zero, then the value stored in register P3 is
65201 ** also incremented by the number of rows in the table being cleared.
65202 **
65203 ** See also: Destroy
65204 */
65205 case OP_Clear: {
65206 #if 0  /* local variables moved into u.bs */
65207   int nChange;
65208 #endif /* local variables moved into u.bs */
65209
65210   u.bs.nChange = 0;
65211   assert( (p->btreeMask & (1<<pOp->p2))!=0 );
65212   rc = sqlite3BtreeClearTable(
65213       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bs.nChange : 0)
65214   );
65215   if( pOp->p3 ){
65216     p->nChange += u.bs.nChange;
65217     if( pOp->p3>0 ){
65218       assert( memIsValid(&aMem[pOp->p3]) );
65219       memAboutToChange(p, &aMem[pOp->p3]);
65220       aMem[pOp->p3].u.i += u.bs.nChange;
65221     }
65222   }
65223   break;
65224 }
65225
65226 /* Opcode: CreateTable P1 P2 * * *
65227 **
65228 ** Allocate a new table in the main database file if P1==0 or in the
65229 ** auxiliary database file if P1==1 or in an attached database if
65230 ** P1>1.  Write the root page number of the new table into
65231 ** register P2
65232 **
65233 ** The difference between a table and an index is this:  A table must
65234 ** have a 4-byte integer key and can have arbitrary data.  An index
65235 ** has an arbitrary key but no data.
65236 **
65237 ** See also: CreateIndex
65238 */
65239 /* Opcode: CreateIndex P1 P2 * * *
65240 **
65241 ** Allocate a new index in the main database file if P1==0 or in the
65242 ** auxiliary database file if P1==1 or in an attached database if
65243 ** P1>1.  Write the root page number of the new table into
65244 ** register P2.
65245 **
65246 ** See documentation on OP_CreateTable for additional information.
65247 */
65248 case OP_CreateIndex:            /* out2-prerelease */
65249 case OP_CreateTable: {          /* out2-prerelease */
65250 #if 0  /* local variables moved into u.bt */
65251   int pgno;
65252   int flags;
65253   Db *pDb;
65254 #endif /* local variables moved into u.bt */
65255
65256   u.bt.pgno = 0;
65257   assert( pOp->p1>=0 && pOp->p1<db->nDb );
65258   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
65259   u.bt.pDb = &db->aDb[pOp->p1];
65260   assert( u.bt.pDb->pBt!=0 );
65261   if( pOp->opcode==OP_CreateTable ){
65262     /* u.bt.flags = BTREE_INTKEY; */
65263     u.bt.flags = BTREE_INTKEY;
65264   }else{
65265     u.bt.flags = BTREE_BLOBKEY;
65266   }
65267   rc = sqlite3BtreeCreateTable(u.bt.pDb->pBt, &u.bt.pgno, u.bt.flags);
65268   pOut->u.i = u.bt.pgno;
65269   break;
65270 }
65271
65272 /* Opcode: ParseSchema P1 P2 * P4 *
65273 **
65274 ** Read and parse all entries from the SQLITE_MASTER table of database P1
65275 ** that match the WHERE clause P4.  P2 is the "force" flag.   Always do
65276 ** the parsing if P2 is true.  If P2 is false, then this routine is a
65277 ** no-op if the schema is not currently loaded.  In other words, if P2
65278 ** is false, the SQLITE_MASTER table is only parsed if the rest of the
65279 ** schema is already loaded into the symbol table.
65280 **
65281 ** This opcode invokes the parser to create a new virtual machine,
65282 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
65283 */
65284 case OP_ParseSchema: {
65285 #if 0  /* local variables moved into u.bu */
65286   int iDb;
65287   const char *zMaster;
65288   char *zSql;
65289   InitData initData;
65290 #endif /* local variables moved into u.bu */
65291
65292   u.bu.iDb = pOp->p1;
65293   assert( u.bu.iDb>=0 && u.bu.iDb<db->nDb );
65294
65295   /* If pOp->p2 is 0, then this opcode is being executed to read a
65296   ** single row, for example the row corresponding to a new index
65297   ** created by this VDBE, from the sqlite_master table. It only
65298   ** does this if the corresponding in-memory schema is currently
65299   ** loaded. Otherwise, the new index definition can be loaded along
65300   ** with the rest of the schema when it is required.
65301   **
65302   ** Although the mutex on the BtShared object that corresponds to
65303   ** database u.bu.iDb (the database containing the sqlite_master table
65304   ** read by this instruction) is currently held, it is necessary to
65305   ** obtain the mutexes on all attached databases before checking if
65306   ** the schema of u.bu.iDb is loaded. This is because, at the start of
65307   ** the sqlite3_exec() call below, SQLite will invoke
65308   ** sqlite3BtreeEnterAll(). If all mutexes are not already held, the
65309   ** u.bu.iDb mutex may be temporarily released to avoid deadlock. If
65310   ** this happens, then some other thread may delete the in-memory
65311   ** schema of database u.bu.iDb before the SQL statement runs. The schema
65312   ** will not be reloaded becuase the db->init.busy flag is set. This
65313   ** can result in a "no such table: sqlite_master" or "malformed
65314   ** database schema" error being returned to the user.
65315   */
65316   assert( sqlite3BtreeHoldsMutex(db->aDb[u.bu.iDb].pBt) );
65317   sqlite3BtreeEnterAll(db);
65318   if( pOp->p2 || DbHasProperty(db, u.bu.iDb, DB_SchemaLoaded) ){
65319     u.bu.zMaster = SCHEMA_TABLE(u.bu.iDb);
65320     u.bu.initData.db = db;
65321     u.bu.initData.iDb = pOp->p1;
65322     u.bu.initData.pzErrMsg = &p->zErrMsg;
65323     u.bu.zSql = sqlite3MPrintf(db,
65324        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
65325        db->aDb[u.bu.iDb].zName, u.bu.zMaster, pOp->p4.z);
65326     if( u.bu.zSql==0 ){
65327       rc = SQLITE_NOMEM;
65328     }else{
65329       assert( db->init.busy==0 );
65330       db->init.busy = 1;
65331       u.bu.initData.rc = SQLITE_OK;
65332       assert( !db->mallocFailed );
65333       rc = sqlite3_exec(db, u.bu.zSql, sqlite3InitCallback, &u.bu.initData, 0);
65334       if( rc==SQLITE_OK ) rc = u.bu.initData.rc;
65335       sqlite3DbFree(db, u.bu.zSql);
65336       db->init.busy = 0;
65337     }
65338   }
65339   sqlite3BtreeLeaveAll(db);
65340   if( rc==SQLITE_NOMEM ){
65341     goto no_mem;
65342   }
65343   break;
65344 }
65345
65346 #if !defined(SQLITE_OMIT_ANALYZE)
65347 /* Opcode: LoadAnalysis P1 * * * *
65348 **
65349 ** Read the sqlite_stat1 table for database P1 and load the content
65350 ** of that table into the internal index hash table.  This will cause
65351 ** the analysis to be used when preparing all subsequent queries.
65352 */
65353 case OP_LoadAnalysis: {
65354   assert( pOp->p1>=0 && pOp->p1<db->nDb );
65355   rc = sqlite3AnalysisLoad(db, pOp->p1);
65356   break;  
65357 }
65358 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
65359
65360 /* Opcode: DropTable P1 * * P4 *
65361 **
65362 ** Remove the internal (in-memory) data structures that describe
65363 ** the table named P4 in database P1.  This is called after a table
65364 ** is dropped in order to keep the internal representation of the
65365 ** schema consistent with what is on disk.
65366 */
65367 case OP_DropTable: {
65368   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
65369   break;
65370 }
65371
65372 /* Opcode: DropIndex P1 * * P4 *
65373 **
65374 ** Remove the internal (in-memory) data structures that describe
65375 ** the index named P4 in database P1.  This is called after an index
65376 ** is dropped in order to keep the internal representation of the
65377 ** schema consistent with what is on disk.
65378 */
65379 case OP_DropIndex: {
65380   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
65381   break;
65382 }
65383
65384 /* Opcode: DropTrigger P1 * * P4 *
65385 **
65386 ** Remove the internal (in-memory) data structures that describe
65387 ** the trigger named P4 in database P1.  This is called after a trigger
65388 ** is dropped in order to keep the internal representation of the
65389 ** schema consistent with what is on disk.
65390 */
65391 case OP_DropTrigger: {
65392   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
65393   break;
65394 }
65395
65396
65397 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
65398 /* Opcode: IntegrityCk P1 P2 P3 * P5
65399 **
65400 ** Do an analysis of the currently open database.  Store in
65401 ** register P1 the text of an error message describing any problems.
65402 ** If no problems are found, store a NULL in register P1.
65403 **
65404 ** The register P3 contains the maximum number of allowed errors.
65405 ** At most reg(P3) errors will be reported.
65406 ** In other words, the analysis stops as soon as reg(P1) errors are 
65407 ** seen.  Reg(P1) is updated with the number of errors remaining.
65408 **
65409 ** The root page numbers of all tables in the database are integer
65410 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
65411 ** total.
65412 **
65413 ** If P5 is not zero, the check is done on the auxiliary database
65414 ** file, not the main database file.
65415 **
65416 ** This opcode is used to implement the integrity_check pragma.
65417 */
65418 case OP_IntegrityCk: {
65419 #if 0  /* local variables moved into u.bv */
65420   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
65421   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
65422   int j;          /* Loop counter */
65423   int nErr;       /* Number of errors reported */
65424   char *z;        /* Text of the error report */
65425   Mem *pnErr;     /* Register keeping track of errors remaining */
65426 #endif /* local variables moved into u.bv */
65427
65428   u.bv.nRoot = pOp->p2;
65429   assert( u.bv.nRoot>0 );
65430   u.bv.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bv.nRoot+1) );
65431   if( u.bv.aRoot==0 ) goto no_mem;
65432   assert( pOp->p3>0 && pOp->p3<=p->nMem );
65433   u.bv.pnErr = &aMem[pOp->p3];
65434   assert( (u.bv.pnErr->flags & MEM_Int)!=0 );
65435   assert( (u.bv.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
65436   pIn1 = &aMem[pOp->p1];
65437   for(u.bv.j=0; u.bv.j<u.bv.nRoot; u.bv.j++){
65438     u.bv.aRoot[u.bv.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bv.j]);
65439   }
65440   u.bv.aRoot[u.bv.j] = 0;
65441   assert( pOp->p5<db->nDb );
65442   assert( (p->btreeMask & (1<<pOp->p5))!=0 );
65443   u.bv.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bv.aRoot, u.bv.nRoot,
65444                                  (int)u.bv.pnErr->u.i, &u.bv.nErr);
65445   sqlite3DbFree(db, u.bv.aRoot);
65446   u.bv.pnErr->u.i -= u.bv.nErr;
65447   sqlite3VdbeMemSetNull(pIn1);
65448   if( u.bv.nErr==0 ){
65449     assert( u.bv.z==0 );
65450   }else if( u.bv.z==0 ){
65451     goto no_mem;
65452   }else{
65453     sqlite3VdbeMemSetStr(pIn1, u.bv.z, -1, SQLITE_UTF8, sqlite3_free);
65454   }
65455   UPDATE_MAX_BLOBSIZE(pIn1);
65456   sqlite3VdbeChangeEncoding(pIn1, encoding);
65457   break;
65458 }
65459 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
65460
65461 /* Opcode: RowSetAdd P1 P2 * * *
65462 **
65463 ** Insert the integer value held by register P2 into a boolean index
65464 ** held in register P1.
65465 **
65466 ** An assertion fails if P2 is not an integer.
65467 */
65468 case OP_RowSetAdd: {       /* in1, in2 */
65469   pIn1 = &aMem[pOp->p1];
65470   pIn2 = &aMem[pOp->p2];
65471   assert( (pIn2->flags & MEM_Int)!=0 );
65472   if( (pIn1->flags & MEM_RowSet)==0 ){
65473     sqlite3VdbeMemSetRowSet(pIn1);
65474     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
65475   }
65476   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
65477   break;
65478 }
65479
65480 /* Opcode: RowSetRead P1 P2 P3 * *
65481 **
65482 ** Extract the smallest value from boolean index P1 and put that value into
65483 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
65484 ** unchanged and jump to instruction P2.
65485 */
65486 case OP_RowSetRead: {       /* jump, in1, out3 */
65487 #if 0  /* local variables moved into u.bw */
65488   i64 val;
65489 #endif /* local variables moved into u.bw */
65490   CHECK_FOR_INTERRUPT;
65491   pIn1 = &aMem[pOp->p1];
65492   if( (pIn1->flags & MEM_RowSet)==0
65493    || sqlite3RowSetNext(pIn1->u.pRowSet, &u.bw.val)==0
65494   ){
65495     /* The boolean index is empty */
65496     sqlite3VdbeMemSetNull(pIn1);
65497     pc = pOp->p2 - 1;
65498   }else{
65499     /* A value was pulled from the index */
65500     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.bw.val);
65501   }
65502   break;
65503 }
65504
65505 /* Opcode: RowSetTest P1 P2 P3 P4
65506 **
65507 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
65508 ** contains a RowSet object and that RowSet object contains
65509 ** the value held in P3, jump to register P2. Otherwise, insert the
65510 ** integer in P3 into the RowSet and continue on to the
65511 ** next opcode.
65512 **
65513 ** The RowSet object is optimized for the case where successive sets
65514 ** of integers, where each set contains no duplicates. Each set
65515 ** of values is identified by a unique P4 value. The first set
65516 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
65517 ** non-negative.  For non-negative values of P4 only the lower 4
65518 ** bits are significant.
65519 **
65520 ** This allows optimizations: (a) when P4==0 there is no need to test
65521 ** the rowset object for P3, as it is guaranteed not to contain it,
65522 ** (b) when P4==-1 there is no need to insert the value, as it will
65523 ** never be tested for, and (c) when a value that is part of set X is
65524 ** inserted, there is no need to search to see if the same value was
65525 ** previously inserted as part of set X (only if it was previously
65526 ** inserted as part of some other set).
65527 */
65528 case OP_RowSetTest: {                     /* jump, in1, in3 */
65529 #if 0  /* local variables moved into u.bx */
65530   int iSet;
65531   int exists;
65532 #endif /* local variables moved into u.bx */
65533
65534   pIn1 = &aMem[pOp->p1];
65535   pIn3 = &aMem[pOp->p3];
65536   u.bx.iSet = pOp->p4.i;
65537   assert( pIn3->flags&MEM_Int );
65538
65539   /* If there is anything other than a rowset object in memory cell P1,
65540   ** delete it now and initialize P1 with an empty rowset
65541   */
65542   if( (pIn1->flags & MEM_RowSet)==0 ){
65543     sqlite3VdbeMemSetRowSet(pIn1);
65544     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
65545   }
65546
65547   assert( pOp->p4type==P4_INT32 );
65548   assert( u.bx.iSet==-1 || u.bx.iSet>=0 );
65549   if( u.bx.iSet ){
65550     u.bx.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
65551                                (u8)(u.bx.iSet>=0 ? u.bx.iSet & 0xf : 0xff),
65552                                pIn3->u.i);
65553     if( u.bx.exists ){
65554       pc = pOp->p2 - 1;
65555       break;
65556     }
65557   }
65558   if( u.bx.iSet>=0 ){
65559     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
65560   }
65561   break;
65562 }
65563
65564
65565 #ifndef SQLITE_OMIT_TRIGGER
65566
65567 /* Opcode: Program P1 P2 P3 P4 *
65568 **
65569 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 
65570 **
65571 ** P1 contains the address of the memory cell that contains the first memory 
65572 ** cell in an array of values used as arguments to the sub-program. P2 
65573 ** contains the address to jump to if the sub-program throws an IGNORE 
65574 ** exception using the RAISE() function. Register P3 contains the address 
65575 ** of a memory cell in this (the parent) VM that is used to allocate the 
65576 ** memory required by the sub-vdbe at runtime.
65577 **
65578 ** P4 is a pointer to the VM containing the trigger program.
65579 */
65580 case OP_Program: {        /* jump */
65581 #if 0  /* local variables moved into u.by */
65582   int nMem;               /* Number of memory registers for sub-program */
65583   int nByte;              /* Bytes of runtime space required for sub-program */
65584   Mem *pRt;               /* Register to allocate runtime space */
65585   Mem *pMem;              /* Used to iterate through memory cells */
65586   Mem *pEnd;              /* Last memory cell in new array */
65587   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
65588   SubProgram *pProgram;   /* Sub-program to execute */
65589   void *t;                /* Token identifying trigger */
65590 #endif /* local variables moved into u.by */
65591
65592   u.by.pProgram = pOp->p4.pProgram;
65593   u.by.pRt = &aMem[pOp->p3];
65594   assert( memIsValid(u.by.pRt) );
65595   assert( u.by.pProgram->nOp>0 );
65596
65597   /* If the p5 flag is clear, then recursive invocation of triggers is
65598   ** disabled for backwards compatibility (p5 is set if this sub-program
65599   ** is really a trigger, not a foreign key action, and the flag set
65600   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
65601   **
65602   ** It is recursive invocation of triggers, at the SQL level, that is
65603   ** disabled. In some cases a single trigger may generate more than one
65604   ** SubProgram (if the trigger may be executed with more than one different
65605   ** ON CONFLICT algorithm). SubProgram structures associated with a
65606   ** single trigger all have the same value for the SubProgram.token
65607   ** variable.  */
65608   if( pOp->p5 ){
65609     u.by.t = u.by.pProgram->token;
65610     for(u.by.pFrame=p->pFrame; u.by.pFrame && u.by.pFrame->token!=u.by.t; u.by.pFrame=u.by.pFrame->pParent);
65611     if( u.by.pFrame ) break;
65612   }
65613
65614   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
65615     rc = SQLITE_ERROR;
65616     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
65617     break;
65618   }
65619
65620   /* Register u.by.pRt is used to store the memory required to save the state
65621   ** of the current program, and the memory required at runtime to execute
65622   ** the trigger program. If this trigger has been fired before, then u.by.pRt
65623   ** is already allocated. Otherwise, it must be initialized.  */
65624   if( (u.by.pRt->flags&MEM_Frame)==0 ){
65625     /* SubProgram.nMem is set to the number of memory cells used by the
65626     ** program stored in SubProgram.aOp. As well as these, one memory
65627     ** cell is required for each cursor used by the program. Set local
65628     ** variable u.by.nMem (and later, VdbeFrame.nChildMem) to this value.
65629     */
65630     u.by.nMem = u.by.pProgram->nMem + u.by.pProgram->nCsr;
65631     u.by.nByte = ROUND8(sizeof(VdbeFrame))
65632               + u.by.nMem * sizeof(Mem)
65633               + u.by.pProgram->nCsr * sizeof(VdbeCursor *);
65634     u.by.pFrame = sqlite3DbMallocZero(db, u.by.nByte);
65635     if( !u.by.pFrame ){
65636       goto no_mem;
65637     }
65638     sqlite3VdbeMemRelease(u.by.pRt);
65639     u.by.pRt->flags = MEM_Frame;
65640     u.by.pRt->u.pFrame = u.by.pFrame;
65641
65642     u.by.pFrame->v = p;
65643     u.by.pFrame->nChildMem = u.by.nMem;
65644     u.by.pFrame->nChildCsr = u.by.pProgram->nCsr;
65645     u.by.pFrame->pc = pc;
65646     u.by.pFrame->aMem = p->aMem;
65647     u.by.pFrame->nMem = p->nMem;
65648     u.by.pFrame->apCsr = p->apCsr;
65649     u.by.pFrame->nCursor = p->nCursor;
65650     u.by.pFrame->aOp = p->aOp;
65651     u.by.pFrame->nOp = p->nOp;
65652     u.by.pFrame->token = u.by.pProgram->token;
65653
65654     u.by.pEnd = &VdbeFrameMem(u.by.pFrame)[u.by.pFrame->nChildMem];
65655     for(u.by.pMem=VdbeFrameMem(u.by.pFrame); u.by.pMem!=u.by.pEnd; u.by.pMem++){
65656       u.by.pMem->flags = MEM_Null;
65657       u.by.pMem->db = db;
65658     }
65659   }else{
65660     u.by.pFrame = u.by.pRt->u.pFrame;
65661     assert( u.by.pProgram->nMem+u.by.pProgram->nCsr==u.by.pFrame->nChildMem );
65662     assert( u.by.pProgram->nCsr==u.by.pFrame->nChildCsr );
65663     assert( pc==u.by.pFrame->pc );
65664   }
65665
65666   p->nFrame++;
65667   u.by.pFrame->pParent = p->pFrame;
65668   u.by.pFrame->lastRowid = db->lastRowid;
65669   u.by.pFrame->nChange = p->nChange;
65670   p->nChange = 0;
65671   p->pFrame = u.by.pFrame;
65672   p->aMem = aMem = &VdbeFrameMem(u.by.pFrame)[-1];
65673   p->nMem = u.by.pFrame->nChildMem;
65674   p->nCursor = (u16)u.by.pFrame->nChildCsr;
65675   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
65676   p->aOp = aOp = u.by.pProgram->aOp;
65677   p->nOp = u.by.pProgram->nOp;
65678   pc = -1;
65679
65680   break;
65681 }
65682
65683 /* Opcode: Param P1 P2 * * *
65684 **
65685 ** This opcode is only ever present in sub-programs called via the 
65686 ** OP_Program instruction. Copy a value currently stored in a memory 
65687 ** cell of the calling (parent) frame to cell P2 in the current frames 
65688 ** address space. This is used by trigger programs to access the new.* 
65689 ** and old.* values.
65690 **
65691 ** The address of the cell in the parent frame is determined by adding
65692 ** the value of the P1 argument to the value of the P1 argument to the
65693 ** calling OP_Program instruction.
65694 */
65695 case OP_Param: {           /* out2-prerelease */
65696 #if 0  /* local variables moved into u.bz */
65697   VdbeFrame *pFrame;
65698   Mem *pIn;
65699 #endif /* local variables moved into u.bz */
65700   u.bz.pFrame = p->pFrame;
65701   u.bz.pIn = &u.bz.pFrame->aMem[pOp->p1 + u.bz.pFrame->aOp[u.bz.pFrame->pc].p1];
65702   sqlite3VdbeMemShallowCopy(pOut, u.bz.pIn, MEM_Ephem);
65703   break;
65704 }
65705
65706 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
65707
65708 #ifndef SQLITE_OMIT_FOREIGN_KEY
65709 /* Opcode: FkCounter P1 P2 * * *
65710 **
65711 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
65712 ** If P1 is non-zero, the database constraint counter is incremented 
65713 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the 
65714 ** statement counter is incremented (immediate foreign key constraints).
65715 */
65716 case OP_FkCounter: {
65717   if( pOp->p1 ){
65718     db->nDeferredCons += pOp->p2;
65719   }else{
65720     p->nFkConstraint += pOp->p2;
65721   }
65722   break;
65723 }
65724
65725 /* Opcode: FkIfZero P1 P2 * * *
65726 **
65727 ** This opcode tests if a foreign key constraint-counter is currently zero.
65728 ** If so, jump to instruction P2. Otherwise, fall through to the next 
65729 ** instruction.
65730 **
65731 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
65732 ** is zero (the one that counts deferred constraint violations). If P1 is
65733 ** zero, the jump is taken if the statement constraint-counter is zero
65734 ** (immediate foreign key constraint violations).
65735 */
65736 case OP_FkIfZero: {         /* jump */
65737   if( pOp->p1 ){
65738     if( db->nDeferredCons==0 ) pc = pOp->p2-1;
65739   }else{
65740     if( p->nFkConstraint==0 ) pc = pOp->p2-1;
65741   }
65742   break;
65743 }
65744 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
65745
65746 #ifndef SQLITE_OMIT_AUTOINCREMENT
65747 /* Opcode: MemMax P1 P2 * * *
65748 **
65749 ** P1 is a register in the root frame of this VM (the root frame is
65750 ** different from the current frame if this instruction is being executed
65751 ** within a sub-program). Set the value of register P1 to the maximum of 
65752 ** its current value and the value in register P2.
65753 **
65754 ** This instruction throws an error if the memory cell is not initially
65755 ** an integer.
65756 */
65757 case OP_MemMax: {        /* in2 */
65758 #if 0  /* local variables moved into u.ca */
65759   Mem *pIn1;
65760   VdbeFrame *pFrame;
65761 #endif /* local variables moved into u.ca */
65762   if( p->pFrame ){
65763     for(u.ca.pFrame=p->pFrame; u.ca.pFrame->pParent; u.ca.pFrame=u.ca.pFrame->pParent);
65764     u.ca.pIn1 = &u.ca.pFrame->aMem[pOp->p1];
65765   }else{
65766     u.ca.pIn1 = &aMem[pOp->p1];
65767   }
65768   assert( memIsValid(u.ca.pIn1) );
65769   sqlite3VdbeMemIntegerify(u.ca.pIn1);
65770   pIn2 = &aMem[pOp->p2];
65771   sqlite3VdbeMemIntegerify(pIn2);
65772   if( u.ca.pIn1->u.i<pIn2->u.i){
65773     u.ca.pIn1->u.i = pIn2->u.i;
65774   }
65775   break;
65776 }
65777 #endif /* SQLITE_OMIT_AUTOINCREMENT */
65778
65779 /* Opcode: IfPos P1 P2 * * *
65780 **
65781 ** If the value of register P1 is 1 or greater, jump to P2.
65782 **
65783 ** It is illegal to use this instruction on a register that does
65784 ** not contain an integer.  An assertion fault will result if you try.
65785 */
65786 case OP_IfPos: {        /* jump, in1 */
65787   pIn1 = &aMem[pOp->p1];
65788   assert( pIn1->flags&MEM_Int );
65789   if( pIn1->u.i>0 ){
65790      pc = pOp->p2 - 1;
65791   }
65792   break;
65793 }
65794
65795 /* Opcode: IfNeg P1 P2 * * *
65796 **
65797 ** If the value of register P1 is less than zero, jump to P2. 
65798 **
65799 ** It is illegal to use this instruction on a register that does
65800 ** not contain an integer.  An assertion fault will result if you try.
65801 */
65802 case OP_IfNeg: {        /* jump, in1 */
65803   pIn1 = &aMem[pOp->p1];
65804   assert( pIn1->flags&MEM_Int );
65805   if( pIn1->u.i<0 ){
65806      pc = pOp->p2 - 1;
65807   }
65808   break;
65809 }
65810
65811 /* Opcode: IfZero P1 P2 P3 * *
65812 **
65813 ** The register P1 must contain an integer.  Add literal P3 to the
65814 ** value in register P1.  If the result is exactly 0, jump to P2. 
65815 **
65816 ** It is illegal to use this instruction on a register that does
65817 ** not contain an integer.  An assertion fault will result if you try.
65818 */
65819 case OP_IfZero: {        /* jump, in1 */
65820   pIn1 = &aMem[pOp->p1];
65821   assert( pIn1->flags&MEM_Int );
65822   pIn1->u.i += pOp->p3;
65823   if( pIn1->u.i==0 ){
65824      pc = pOp->p2 - 1;
65825   }
65826   break;
65827 }
65828
65829 /* Opcode: AggStep * P2 P3 P4 P5
65830 **
65831 ** Execute the step function for an aggregate.  The
65832 ** function has P5 arguments.   P4 is a pointer to the FuncDef
65833 ** structure that specifies the function.  Use register
65834 ** P3 as the accumulator.
65835 **
65836 ** The P5 arguments are taken from register P2 and its
65837 ** successors.
65838 */
65839 case OP_AggStep: {
65840 #if 0  /* local variables moved into u.cb */
65841   int n;
65842   int i;
65843   Mem *pMem;
65844   Mem *pRec;
65845   sqlite3_context ctx;
65846   sqlite3_value **apVal;
65847 #endif /* local variables moved into u.cb */
65848
65849   u.cb.n = pOp->p5;
65850   assert( u.cb.n>=0 );
65851   u.cb.pRec = &aMem[pOp->p2];
65852   u.cb.apVal = p->apArg;
65853   assert( u.cb.apVal || u.cb.n==0 );
65854   for(u.cb.i=0; u.cb.i<u.cb.n; u.cb.i++, u.cb.pRec++){
65855     assert( memIsValid(u.cb.pRec) );
65856     u.cb.apVal[u.cb.i] = u.cb.pRec;
65857     memAboutToChange(p, u.cb.pRec);
65858     sqlite3VdbeMemStoreType(u.cb.pRec);
65859   }
65860   u.cb.ctx.pFunc = pOp->p4.pFunc;
65861   assert( pOp->p3>0 && pOp->p3<=p->nMem );
65862   u.cb.ctx.pMem = u.cb.pMem = &aMem[pOp->p3];
65863   u.cb.pMem->n++;
65864   u.cb.ctx.s.flags = MEM_Null;
65865   u.cb.ctx.s.z = 0;
65866   u.cb.ctx.s.zMalloc = 0;
65867   u.cb.ctx.s.xDel = 0;
65868   u.cb.ctx.s.db = db;
65869   u.cb.ctx.isError = 0;
65870   u.cb.ctx.pColl = 0;
65871   if( u.cb.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
65872     assert( pOp>p->aOp );
65873     assert( pOp[-1].p4type==P4_COLLSEQ );
65874     assert( pOp[-1].opcode==OP_CollSeq );
65875     u.cb.ctx.pColl = pOp[-1].p4.pColl;
65876   }
65877   (u.cb.ctx.pFunc->xStep)(&u.cb.ctx, u.cb.n, u.cb.apVal); /* IMP: R-24505-23230 */
65878   if( u.cb.ctx.isError ){
65879     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cb.ctx.s));
65880     rc = u.cb.ctx.isError;
65881   }
65882   sqlite3VdbeMemRelease(&u.cb.ctx.s);
65883   break;
65884 }
65885
65886 /* Opcode: AggFinal P1 P2 * P4 *
65887 **
65888 ** Execute the finalizer function for an aggregate.  P1 is
65889 ** the memory location that is the accumulator for the aggregate.
65890 **
65891 ** P2 is the number of arguments that the step function takes and
65892 ** P4 is a pointer to the FuncDef for this function.  The P2
65893 ** argument is not used by this opcode.  It is only there to disambiguate
65894 ** functions that can take varying numbers of arguments.  The
65895 ** P4 argument is only needed for the degenerate case where
65896 ** the step function was not previously called.
65897 */
65898 case OP_AggFinal: {
65899 #if 0  /* local variables moved into u.cc */
65900   Mem *pMem;
65901 #endif /* local variables moved into u.cc */
65902   assert( pOp->p1>0 && pOp->p1<=p->nMem );
65903   u.cc.pMem = &aMem[pOp->p1];
65904   assert( (u.cc.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
65905   rc = sqlite3VdbeMemFinalize(u.cc.pMem, pOp->p4.pFunc);
65906   if( rc ){
65907     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cc.pMem));
65908   }
65909   sqlite3VdbeChangeEncoding(u.cc.pMem, encoding);
65910   UPDATE_MAX_BLOBSIZE(u.cc.pMem);
65911   if( sqlite3VdbeMemTooBig(u.cc.pMem) ){
65912     goto too_big;
65913   }
65914   break;
65915 }
65916
65917 #ifndef SQLITE_OMIT_WAL
65918 /* Opcode: Checkpoint P1 * * * *
65919 **
65920 ** Checkpoint database P1. This is a no-op if P1 is not currently in
65921 ** WAL mode.
65922 */
65923 case OP_Checkpoint: {
65924   rc = sqlite3Checkpoint(db, pOp->p1);
65925   break;
65926 };  
65927 #endif
65928
65929 #ifndef SQLITE_OMIT_PRAGMA
65930 /* Opcode: JournalMode P1 P2 P3 * P5
65931 **
65932 ** Change the journal mode of database P1 to P3. P3 must be one of the
65933 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
65934 ** modes (delete, truncate, persist, off and memory), this is a simple
65935 ** operation. No IO is required.
65936 **
65937 ** If changing into or out of WAL mode the procedure is more complicated.
65938 **
65939 ** Write a string containing the final journal-mode to register P2.
65940 */
65941 case OP_JournalMode: {    /* out2-prerelease */
65942 #if 0  /* local variables moved into u.cd */
65943   Btree *pBt;                     /* Btree to change journal mode of */
65944   Pager *pPager;                  /* Pager associated with pBt */
65945   int eNew;                       /* New journal mode */
65946   int eOld;                       /* The old journal mode */
65947   const char *zFilename;          /* Name of database file for pPager */
65948 #endif /* local variables moved into u.cd */
65949
65950   u.cd.eNew = pOp->p3;
65951   assert( u.cd.eNew==PAGER_JOURNALMODE_DELETE
65952        || u.cd.eNew==PAGER_JOURNALMODE_TRUNCATE
65953        || u.cd.eNew==PAGER_JOURNALMODE_PERSIST
65954        || u.cd.eNew==PAGER_JOURNALMODE_OFF
65955        || u.cd.eNew==PAGER_JOURNALMODE_MEMORY
65956        || u.cd.eNew==PAGER_JOURNALMODE_WAL
65957        || u.cd.eNew==PAGER_JOURNALMODE_QUERY
65958   );
65959   assert( pOp->p1>=0 && pOp->p1<db->nDb );
65960
65961   /* This opcode is used in two places: PRAGMA journal_mode and ATTACH.
65962   ** In PRAGMA journal_mode, the sqlite3VdbeUsesBtree() routine is called
65963   ** when the statment is prepared and so p->aMutex.nMutex>0.  All mutexes
65964   ** are already acquired.  But when used in ATTACH, sqlite3VdbeUsesBtree()
65965   ** is not called when the statement is prepared because it requires the
65966   ** iDb index of the database as a parameter, and the database has not
65967   ** yet been attached so that index is unavailable.  We have to wait
65968   ** until runtime (now) to get the mutex on the newly attached database.
65969   ** No other mutexes are required by the ATTACH command so this is safe
65970   ** to do.
65971   */
65972   assert( (p->btreeMask & (1<<pOp->p1))!=0 || p->aMutex.nMutex==0 );
65973   if( p->aMutex.nMutex==0 ){
65974     /* This occurs right after ATTACH.  Get a mutex on the newly ATTACHed
65975     ** database. */
65976     sqlite3VdbeUsesBtree(p, pOp->p1);
65977     sqlite3VdbeMutexArrayEnter(p);
65978   }
65979
65980   u.cd.pBt = db->aDb[pOp->p1].pBt;
65981   u.cd.pPager = sqlite3BtreePager(u.cd.pBt);
65982   u.cd.eOld = sqlite3PagerGetJournalMode(u.cd.pPager);
65983   if( u.cd.eNew==PAGER_JOURNALMODE_QUERY ) u.cd.eNew = u.cd.eOld;
65984   if( !sqlite3PagerOkToChangeJournalMode(u.cd.pPager) ) u.cd.eNew = u.cd.eOld;
65985
65986 #ifndef SQLITE_OMIT_WAL
65987   u.cd.zFilename = sqlite3PagerFilename(u.cd.pPager);
65988
65989   /* Do not allow a transition to journal_mode=WAL for a database
65990   ** in temporary storage or if the VFS does not support shared memory
65991   */
65992   if( u.cd.eNew==PAGER_JOURNALMODE_WAL
65993    && (u.cd.zFilename[0]==0                         /* Temp file */
65994        || !sqlite3PagerWalSupported(u.cd.pPager))   /* No shared-memory support */
65995   ){
65996     u.cd.eNew = u.cd.eOld;
65997   }
65998
65999   if( (u.cd.eNew!=u.cd.eOld)
66000    && (u.cd.eOld==PAGER_JOURNALMODE_WAL || u.cd.eNew==PAGER_JOURNALMODE_WAL)
66001   ){
66002     if( !db->autoCommit || db->activeVdbeCnt>1 ){
66003       rc = SQLITE_ERROR;
66004       sqlite3SetString(&p->zErrMsg, db,
66005           "cannot change %s wal mode from within a transaction",
66006           (u.cd.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
66007       );
66008       break;
66009     }else{
66010
66011       if( u.cd.eOld==PAGER_JOURNALMODE_WAL ){
66012         /* If leaving WAL mode, close the log file. If successful, the call
66013         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
66014         ** file. An EXCLUSIVE lock may still be held on the database file
66015         ** after a successful return.
66016         */
66017         rc = sqlite3PagerCloseWal(u.cd.pPager);
66018         if( rc==SQLITE_OK ){
66019           sqlite3PagerSetJournalMode(u.cd.pPager, u.cd.eNew);
66020         }
66021       }else if( u.cd.eOld==PAGER_JOURNALMODE_MEMORY ){
66022         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
66023         ** as an intermediate */
66024         sqlite3PagerSetJournalMode(u.cd.pPager, PAGER_JOURNALMODE_OFF);
66025       }
66026
66027       /* Open a transaction on the database file. Regardless of the journal
66028       ** mode, this transaction always uses a rollback journal.
66029       */
66030       assert( sqlite3BtreeIsInTrans(u.cd.pBt)==0 );
66031       if( rc==SQLITE_OK ){
66032         rc = sqlite3BtreeSetVersion(u.cd.pBt, (u.cd.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
66033       }
66034     }
66035   }
66036 #endif /* ifndef SQLITE_OMIT_WAL */
66037
66038   if( rc ){
66039     u.cd.eNew = u.cd.eOld;
66040   }
66041   u.cd.eNew = sqlite3PagerSetJournalMode(u.cd.pPager, u.cd.eNew);
66042
66043   pOut = &aMem[pOp->p2];
66044   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
66045   pOut->z = (char *)sqlite3JournalModename(u.cd.eNew);
66046   pOut->n = sqlite3Strlen30(pOut->z);
66047   pOut->enc = SQLITE_UTF8;
66048   sqlite3VdbeChangeEncoding(pOut, encoding);
66049   break;
66050 };
66051 #endif /* SQLITE_OMIT_PRAGMA */
66052
66053 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
66054 /* Opcode: Vacuum * * * * *
66055 **
66056 ** Vacuum the entire database.  This opcode will cause other virtual
66057 ** machines to be created and run.  It may not be called from within
66058 ** a transaction.
66059 */
66060 case OP_Vacuum: {
66061   rc = sqlite3RunVacuum(&p->zErrMsg, db);
66062   break;
66063 }
66064 #endif
66065
66066 #if !defined(SQLITE_OMIT_AUTOVACUUM)
66067 /* Opcode: IncrVacuum P1 P2 * * *
66068 **
66069 ** Perform a single step of the incremental vacuum procedure on
66070 ** the P1 database. If the vacuum has finished, jump to instruction
66071 ** P2. Otherwise, fall through to the next instruction.
66072 */
66073 case OP_IncrVacuum: {        /* jump */
66074 #if 0  /* local variables moved into u.ce */
66075   Btree *pBt;
66076 #endif /* local variables moved into u.ce */
66077
66078   assert( pOp->p1>=0 && pOp->p1<db->nDb );
66079   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
66080   u.ce.pBt = db->aDb[pOp->p1].pBt;
66081   rc = sqlite3BtreeIncrVacuum(u.ce.pBt);
66082   if( rc==SQLITE_DONE ){
66083     pc = pOp->p2 - 1;
66084     rc = SQLITE_OK;
66085   }
66086   break;
66087 }
66088 #endif
66089
66090 /* Opcode: Expire P1 * * * *
66091 **
66092 ** Cause precompiled statements to become expired. An expired statement
66093 ** fails with an error code of SQLITE_SCHEMA if it is ever executed 
66094 ** (via sqlite3_step()).
66095 ** 
66096 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
66097 ** then only the currently executing statement is affected. 
66098 */
66099 case OP_Expire: {
66100   if( !pOp->p1 ){
66101     sqlite3ExpirePreparedStatements(db);
66102   }else{
66103     p->expired = 1;
66104   }
66105   break;
66106 }
66107
66108 #ifndef SQLITE_OMIT_SHARED_CACHE
66109 /* Opcode: TableLock P1 P2 P3 P4 *
66110 **
66111 ** Obtain a lock on a particular table. This instruction is only used when
66112 ** the shared-cache feature is enabled. 
66113 **
66114 ** P1 is the index of the database in sqlite3.aDb[] of the database
66115 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
66116 ** a write lock if P3==1.
66117 **
66118 ** P2 contains the root-page of the table to lock.
66119 **
66120 ** P4 contains a pointer to the name of the table being locked. This is only
66121 ** used to generate an error message if the lock cannot be obtained.
66122 */
66123 case OP_TableLock: {
66124   u8 isWriteLock = (u8)pOp->p3;
66125   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
66126     int p1 = pOp->p1; 
66127     assert( p1>=0 && p1<db->nDb );
66128     assert( (p->btreeMask & (1<<p1))!=0 );
66129     assert( isWriteLock==0 || isWriteLock==1 );
66130     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
66131     if( (rc&0xFF)==SQLITE_LOCKED ){
66132       const char *z = pOp->p4.z;
66133       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
66134     }
66135   }
66136   break;
66137 }
66138 #endif /* SQLITE_OMIT_SHARED_CACHE */
66139
66140 #ifndef SQLITE_OMIT_VIRTUALTABLE
66141 /* Opcode: VBegin * * * P4 *
66142 **
66143 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
66144 ** xBegin method for that table.
66145 **
66146 ** Also, whether or not P4 is set, check that this is not being called from
66147 ** within a callback to a virtual table xSync() method. If it is, the error
66148 ** code will be set to SQLITE_LOCKED.
66149 */
66150 case OP_VBegin: {
66151 #if 0  /* local variables moved into u.cf */
66152   VTable *pVTab;
66153 #endif /* local variables moved into u.cf */
66154   u.cf.pVTab = pOp->p4.pVtab;
66155   rc = sqlite3VtabBegin(db, u.cf.pVTab);
66156   if( u.cf.pVTab ) importVtabErrMsg(p, u.cf.pVTab->pVtab);
66157   break;
66158 }
66159 #endif /* SQLITE_OMIT_VIRTUALTABLE */
66160
66161 #ifndef SQLITE_OMIT_VIRTUALTABLE
66162 /* Opcode: VCreate P1 * * P4 *
66163 **
66164 ** P4 is the name of a virtual table in database P1. Call the xCreate method
66165 ** for that table.
66166 */
66167 case OP_VCreate: {
66168   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
66169   break;
66170 }
66171 #endif /* SQLITE_OMIT_VIRTUALTABLE */
66172
66173 #ifndef SQLITE_OMIT_VIRTUALTABLE
66174 /* Opcode: VDestroy P1 * * P4 *
66175 **
66176 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
66177 ** of that table.
66178 */
66179 case OP_VDestroy: {
66180   p->inVtabMethod = 2;
66181   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
66182   p->inVtabMethod = 0;
66183   break;
66184 }
66185 #endif /* SQLITE_OMIT_VIRTUALTABLE */
66186
66187 #ifndef SQLITE_OMIT_VIRTUALTABLE
66188 /* Opcode: VOpen P1 * * P4 *
66189 **
66190 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
66191 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
66192 ** table and stores that cursor in P1.
66193 */
66194 case OP_VOpen: {
66195 #if 0  /* local variables moved into u.cg */
66196   VdbeCursor *pCur;
66197   sqlite3_vtab_cursor *pVtabCursor;
66198   sqlite3_vtab *pVtab;
66199   sqlite3_module *pModule;
66200 #endif /* local variables moved into u.cg */
66201
66202   u.cg.pCur = 0;
66203   u.cg.pVtabCursor = 0;
66204   u.cg.pVtab = pOp->p4.pVtab->pVtab;
66205   u.cg.pModule = (sqlite3_module *)u.cg.pVtab->pModule;
66206   assert(u.cg.pVtab && u.cg.pModule);
66207   rc = u.cg.pModule->xOpen(u.cg.pVtab, &u.cg.pVtabCursor);
66208   importVtabErrMsg(p, u.cg.pVtab);
66209   if( SQLITE_OK==rc ){
66210     /* Initialize sqlite3_vtab_cursor base class */
66211     u.cg.pVtabCursor->pVtab = u.cg.pVtab;
66212
66213     /* Initialise vdbe cursor object */
66214     u.cg.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
66215     if( u.cg.pCur ){
66216       u.cg.pCur->pVtabCursor = u.cg.pVtabCursor;
66217       u.cg.pCur->pModule = u.cg.pVtabCursor->pVtab->pModule;
66218     }else{
66219       db->mallocFailed = 1;
66220       u.cg.pModule->xClose(u.cg.pVtabCursor);
66221     }
66222   }
66223   break;
66224 }
66225 #endif /* SQLITE_OMIT_VIRTUALTABLE */
66226
66227 #ifndef SQLITE_OMIT_VIRTUALTABLE
66228 /* Opcode: VFilter P1 P2 P3 P4 *
66229 **
66230 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
66231 ** the filtered result set is empty.
66232 **
66233 ** P4 is either NULL or a string that was generated by the xBestIndex
66234 ** method of the module.  The interpretation of the P4 string is left
66235 ** to the module implementation.
66236 **
66237 ** This opcode invokes the xFilter method on the virtual table specified
66238 ** by P1.  The integer query plan parameter to xFilter is stored in register
66239 ** P3. Register P3+1 stores the argc parameter to be passed to the
66240 ** xFilter method. Registers P3+2..P3+1+argc are the argc
66241 ** additional parameters which are passed to
66242 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
66243 **
66244 ** A jump is made to P2 if the result set after filtering would be empty.
66245 */
66246 case OP_VFilter: {   /* jump */
66247 #if 0  /* local variables moved into u.ch */
66248   int nArg;
66249   int iQuery;
66250   const sqlite3_module *pModule;
66251   Mem *pQuery;
66252   Mem *pArgc;
66253   sqlite3_vtab_cursor *pVtabCursor;
66254   sqlite3_vtab *pVtab;
66255   VdbeCursor *pCur;
66256   int res;
66257   int i;
66258   Mem **apArg;
66259 #endif /* local variables moved into u.ch */
66260
66261   u.ch.pQuery = &aMem[pOp->p3];
66262   u.ch.pArgc = &u.ch.pQuery[1];
66263   u.ch.pCur = p->apCsr[pOp->p1];
66264   assert( memIsValid(u.ch.pQuery) );
66265   REGISTER_TRACE(pOp->p3, u.ch.pQuery);
66266   assert( u.ch.pCur->pVtabCursor );
66267   u.ch.pVtabCursor = u.ch.pCur->pVtabCursor;
66268   u.ch.pVtab = u.ch.pVtabCursor->pVtab;
66269   u.ch.pModule = u.ch.pVtab->pModule;
66270
66271   /* Grab the index number and argc parameters */
66272   assert( (u.ch.pQuery->flags&MEM_Int)!=0 && u.ch.pArgc->flags==MEM_Int );
66273   u.ch.nArg = (int)u.ch.pArgc->u.i;
66274   u.ch.iQuery = (int)u.ch.pQuery->u.i;
66275
66276   /* Invoke the xFilter method */
66277   {
66278     u.ch.res = 0;
66279     u.ch.apArg = p->apArg;
66280     for(u.ch.i = 0; u.ch.i<u.ch.nArg; u.ch.i++){
66281       u.ch.apArg[u.ch.i] = &u.ch.pArgc[u.ch.i+1];
66282       sqlite3VdbeMemStoreType(u.ch.apArg[u.ch.i]);
66283     }
66284
66285     p->inVtabMethod = 1;
66286     rc = u.ch.pModule->xFilter(u.ch.pVtabCursor, u.ch.iQuery, pOp->p4.z, u.ch.nArg, u.ch.apArg);
66287     p->inVtabMethod = 0;
66288     importVtabErrMsg(p, u.ch.pVtab);
66289     if( rc==SQLITE_OK ){
66290       u.ch.res = u.ch.pModule->xEof(u.ch.pVtabCursor);
66291     }
66292
66293     if( u.ch.res ){
66294       pc = pOp->p2 - 1;
66295     }
66296   }
66297   u.ch.pCur->nullRow = 0;
66298
66299   break;
66300 }
66301 #endif /* SQLITE_OMIT_VIRTUALTABLE */
66302
66303 #ifndef SQLITE_OMIT_VIRTUALTABLE
66304 /* Opcode: VColumn P1 P2 P3 * *
66305 **
66306 ** Store the value of the P2-th column of
66307 ** the row of the virtual-table that the 
66308 ** P1 cursor is pointing to into register P3.
66309 */
66310 case OP_VColumn: {
66311 #if 0  /* local variables moved into u.ci */
66312   sqlite3_vtab *pVtab;
66313   const sqlite3_module *pModule;
66314   Mem *pDest;
66315   sqlite3_context sContext;
66316 #endif /* local variables moved into u.ci */
66317
66318   VdbeCursor *pCur = p->apCsr[pOp->p1];
66319   assert( pCur->pVtabCursor );
66320   assert( pOp->p3>0 && pOp->p3<=p->nMem );
66321   u.ci.pDest = &aMem[pOp->p3];
66322   memAboutToChange(p, u.ci.pDest);
66323   if( pCur->nullRow ){
66324     sqlite3VdbeMemSetNull(u.ci.pDest);
66325     break;
66326   }
66327   u.ci.pVtab = pCur->pVtabCursor->pVtab;
66328   u.ci.pModule = u.ci.pVtab->pModule;
66329   assert( u.ci.pModule->xColumn );
66330   memset(&u.ci.sContext, 0, sizeof(u.ci.sContext));
66331
66332   /* The output cell may already have a buffer allocated. Move
66333   ** the current contents to u.ci.sContext.s so in case the user-function
66334   ** can use the already allocated buffer instead of allocating a
66335   ** new one.
66336   */
66337   sqlite3VdbeMemMove(&u.ci.sContext.s, u.ci.pDest);
66338   MemSetTypeFlag(&u.ci.sContext.s, MEM_Null);
66339
66340   rc = u.ci.pModule->xColumn(pCur->pVtabCursor, &u.ci.sContext, pOp->p2);
66341   importVtabErrMsg(p, u.ci.pVtab);
66342   if( u.ci.sContext.isError ){
66343     rc = u.ci.sContext.isError;
66344   }
66345
66346   /* Copy the result of the function to the P3 register. We
66347   ** do this regardless of whether or not an error occurred to ensure any
66348   ** dynamic allocation in u.ci.sContext.s (a Mem struct) is  released.
66349   */
66350   sqlite3VdbeChangeEncoding(&u.ci.sContext.s, encoding);
66351   sqlite3VdbeMemMove(u.ci.pDest, &u.ci.sContext.s);
66352   REGISTER_TRACE(pOp->p3, u.ci.pDest);
66353   UPDATE_MAX_BLOBSIZE(u.ci.pDest);
66354
66355   if( sqlite3VdbeMemTooBig(u.ci.pDest) ){
66356     goto too_big;
66357   }
66358   break;
66359 }
66360 #endif /* SQLITE_OMIT_VIRTUALTABLE */
66361
66362 #ifndef SQLITE_OMIT_VIRTUALTABLE
66363 /* Opcode: VNext P1 P2 * * *
66364 **
66365 ** Advance virtual table P1 to the next row in its result set and
66366 ** jump to instruction P2.  Or, if the virtual table has reached
66367 ** the end of its result set, then fall through to the next instruction.
66368 */
66369 case OP_VNext: {   /* jump */
66370 #if 0  /* local variables moved into u.cj */
66371   sqlite3_vtab *pVtab;
66372   const sqlite3_module *pModule;
66373   int res;
66374   VdbeCursor *pCur;
66375 #endif /* local variables moved into u.cj */
66376
66377   u.cj.res = 0;
66378   u.cj.pCur = p->apCsr[pOp->p1];
66379   assert( u.cj.pCur->pVtabCursor );
66380   if( u.cj.pCur->nullRow ){
66381     break;
66382   }
66383   u.cj.pVtab = u.cj.pCur->pVtabCursor->pVtab;
66384   u.cj.pModule = u.cj.pVtab->pModule;
66385   assert( u.cj.pModule->xNext );
66386
66387   /* Invoke the xNext() method of the module. There is no way for the
66388   ** underlying implementation to return an error if one occurs during
66389   ** xNext(). Instead, if an error occurs, true is returned (indicating that
66390   ** data is available) and the error code returned when xColumn or
66391   ** some other method is next invoked on the save virtual table cursor.
66392   */
66393   p->inVtabMethod = 1;
66394   rc = u.cj.pModule->xNext(u.cj.pCur->pVtabCursor);
66395   p->inVtabMethod = 0;
66396   importVtabErrMsg(p, u.cj.pVtab);
66397   if( rc==SQLITE_OK ){
66398     u.cj.res = u.cj.pModule->xEof(u.cj.pCur->pVtabCursor);
66399   }
66400
66401   if( !u.cj.res ){
66402     /* If there is data, jump to P2 */
66403     pc = pOp->p2 - 1;
66404   }
66405   break;
66406 }
66407 #endif /* SQLITE_OMIT_VIRTUALTABLE */
66408
66409 #ifndef SQLITE_OMIT_VIRTUALTABLE
66410 /* Opcode: VRename P1 * * P4 *
66411 **
66412 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
66413 ** This opcode invokes the corresponding xRename method. The value
66414 ** in register P1 is passed as the zName argument to the xRename method.
66415 */
66416 case OP_VRename: {
66417 #if 0  /* local variables moved into u.ck */
66418   sqlite3_vtab *pVtab;
66419   Mem *pName;
66420 #endif /* local variables moved into u.ck */
66421
66422   u.ck.pVtab = pOp->p4.pVtab->pVtab;
66423   u.ck.pName = &aMem[pOp->p1];
66424   assert( u.ck.pVtab->pModule->xRename );
66425   assert( memIsValid(u.ck.pName) );
66426   REGISTER_TRACE(pOp->p1, u.ck.pName);
66427   assert( u.ck.pName->flags & MEM_Str );
66428   rc = u.ck.pVtab->pModule->xRename(u.ck.pVtab, u.ck.pName->z);
66429   importVtabErrMsg(p, u.ck.pVtab);
66430   p->expired = 0;
66431
66432   break;
66433 }
66434 #endif
66435
66436 #ifndef SQLITE_OMIT_VIRTUALTABLE
66437 /* Opcode: VUpdate P1 P2 P3 P4 *
66438 **
66439 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
66440 ** This opcode invokes the corresponding xUpdate method. P2 values
66441 ** are contiguous memory cells starting at P3 to pass to the xUpdate 
66442 ** invocation. The value in register (P3+P2-1) corresponds to the 
66443 ** p2th element of the argv array passed to xUpdate.
66444 **
66445 ** The xUpdate method will do a DELETE or an INSERT or both.
66446 ** The argv[0] element (which corresponds to memory cell P3)
66447 ** is the rowid of a row to delete.  If argv[0] is NULL then no 
66448 ** deletion occurs.  The argv[1] element is the rowid of the new 
66449 ** row.  This can be NULL to have the virtual table select the new 
66450 ** rowid for itself.  The subsequent elements in the array are 
66451 ** the values of columns in the new row.
66452 **
66453 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
66454 ** a row to delete.
66455 **
66456 ** P1 is a boolean flag. If it is set to true and the xUpdate call
66457 ** is successful, then the value returned by sqlite3_last_insert_rowid() 
66458 ** is set to the value of the rowid for the row just inserted.
66459 */
66460 case OP_VUpdate: {
66461 #if 0  /* local variables moved into u.cl */
66462   sqlite3_vtab *pVtab;
66463   sqlite3_module *pModule;
66464   int nArg;
66465   int i;
66466   sqlite_int64 rowid;
66467   Mem **apArg;
66468   Mem *pX;
66469 #endif /* local variables moved into u.cl */
66470
66471   u.cl.pVtab = pOp->p4.pVtab->pVtab;
66472   u.cl.pModule = (sqlite3_module *)u.cl.pVtab->pModule;
66473   u.cl.nArg = pOp->p2;
66474   assert( pOp->p4type==P4_VTAB );
66475   if( ALWAYS(u.cl.pModule->xUpdate) ){
66476     u.cl.apArg = p->apArg;
66477     u.cl.pX = &aMem[pOp->p3];
66478     for(u.cl.i=0; u.cl.i<u.cl.nArg; u.cl.i++){
66479       assert( memIsValid(u.cl.pX) );
66480       memAboutToChange(p, u.cl.pX);
66481       sqlite3VdbeMemStoreType(u.cl.pX);
66482       u.cl.apArg[u.cl.i] = u.cl.pX;
66483       u.cl.pX++;
66484     }
66485     rc = u.cl.pModule->xUpdate(u.cl.pVtab, u.cl.nArg, u.cl.apArg, &u.cl.rowid);
66486     importVtabErrMsg(p, u.cl.pVtab);
66487     if( rc==SQLITE_OK && pOp->p1 ){
66488       assert( u.cl.nArg>1 && u.cl.apArg[0] && (u.cl.apArg[0]->flags&MEM_Null) );
66489       db->lastRowid = u.cl.rowid;
66490     }
66491     p->nChange++;
66492   }
66493   break;
66494 }
66495 #endif /* SQLITE_OMIT_VIRTUALTABLE */
66496
66497 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
66498 /* Opcode: Pagecount P1 P2 * * *
66499 **
66500 ** Write the current number of pages in database P1 to memory cell P2.
66501 */
66502 case OP_Pagecount: {            /* out2-prerelease */
66503   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
66504   break;
66505 }
66506 #endif
66507
66508
66509 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
66510 /* Opcode: MaxPgcnt P1 P2 P3 * *
66511 **
66512 ** Try to set the maximum page count for database P1 to the value in P3.
66513 ** Do not let the maximum page count fall below the current page count and
66514 ** do not change the maximum page count value if P3==0.
66515 **
66516 ** Store the maximum page count after the change in register P2.
66517 */
66518 case OP_MaxPgcnt: {            /* out2-prerelease */
66519   unsigned int newMax;
66520   Btree *pBt;
66521
66522   pBt = db->aDb[pOp->p1].pBt;
66523   newMax = 0;
66524   if( pOp->p3 ){
66525     newMax = sqlite3BtreeLastPage(pBt);
66526     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
66527   }
66528   pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
66529   break;
66530 }
66531 #endif
66532
66533
66534 #ifndef SQLITE_OMIT_TRACE
66535 /* Opcode: Trace * * * P4 *
66536 **
66537 ** If tracing is enabled (by the sqlite3_trace()) interface, then
66538 ** the UTF-8 string contained in P4 is emitted on the trace callback.
66539 */
66540 case OP_Trace: {
66541 #if 0  /* local variables moved into u.cm */
66542   char *zTrace;
66543 #endif /* local variables moved into u.cm */
66544
66545   u.cm.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
66546   if( u.cm.zTrace ){
66547     if( db->xTrace ){
66548       char *z = sqlite3VdbeExpandSql(p, u.cm.zTrace);
66549       db->xTrace(db->pTraceArg, z);
66550       sqlite3DbFree(db, z);
66551     }
66552 #ifdef SQLITE_DEBUG
66553     if( (db->flags & SQLITE_SqlTrace)!=0 ){
66554       sqlite3DebugPrintf("SQL-trace: %s\n", u.cm.zTrace);
66555     }
66556 #endif /* SQLITE_DEBUG */
66557   }
66558   break;
66559 }
66560 #endif
66561
66562
66563 /* Opcode: Noop * * * * *
66564 **
66565 ** Do nothing.  This instruction is often useful as a jump
66566 ** destination.
66567 */
66568 /*
66569 ** The magic Explain opcode are only inserted when explain==2 (which
66570 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
66571 ** This opcode records information from the optimizer.  It is the
66572 ** the same as a no-op.  This opcodesnever appears in a real VM program.
66573 */
66574 default: {          /* This is really OP_Noop and OP_Explain */
66575   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
66576   break;
66577 }
66578
66579 /*****************************************************************************
66580 ** The cases of the switch statement above this line should all be indented
66581 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
66582 ** readability.  From this point on down, the normal indentation rules are
66583 ** restored.
66584 *****************************************************************************/
66585     }
66586
66587 #ifdef VDBE_PROFILE
66588     {
66589       u64 elapsed = sqlite3Hwtime() - start;
66590       pOp->cycles += elapsed;
66591       pOp->cnt++;
66592 #if 0
66593         fprintf(stdout, "%10llu ", elapsed);
66594         sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
66595 #endif
66596     }
66597 #endif
66598
66599     /* The following code adds nothing to the actual functionality
66600     ** of the program.  It is only here for testing and debugging.
66601     ** On the other hand, it does burn CPU cycles every time through
66602     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
66603     */
66604 #ifndef NDEBUG
66605     assert( pc>=-1 && pc<p->nOp );
66606
66607 #ifdef SQLITE_DEBUG
66608     if( p->trace ){
66609       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
66610       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
66611         registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
66612       }
66613       if( pOp->opflags & OPFLG_OUT3 ){
66614         registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
66615       }
66616     }
66617 #endif  /* SQLITE_DEBUG */
66618 #endif  /* NDEBUG */
66619   }  /* The end of the for(;;) loop the loops through opcodes */
66620
66621   /* If we reach this point, it means that execution is finished with
66622   ** an error of some kind.
66623   */
66624 vdbe_error_halt:
66625   assert( rc );
66626   p->rc = rc;
66627   testcase( sqlite3GlobalConfig.xLog!=0 );
66628   sqlite3_log(rc, "statement aborts at %d: [%s] %s", 
66629                    pc, p->zSql, p->zErrMsg);
66630   sqlite3VdbeHalt(p);
66631   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
66632   rc = SQLITE_ERROR;
66633   if( resetSchemaOnFault ) sqlite3ResetInternalSchema(db, 0);
66634
66635   /* This is the only way out of this procedure.  We have to
66636   ** release the mutexes on btrees that were acquired at the
66637   ** top. */
66638 vdbe_return:
66639   sqlite3BtreeMutexArrayLeave(&p->aMutex);
66640   return rc;
66641
66642   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
66643   ** is encountered.
66644   */
66645 too_big:
66646   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
66647   rc = SQLITE_TOOBIG;
66648   goto vdbe_error_halt;
66649
66650   /* Jump to here if a malloc() fails.
66651   */
66652 no_mem:
66653   db->mallocFailed = 1;
66654   sqlite3SetString(&p->zErrMsg, db, "out of memory");
66655   rc = SQLITE_NOMEM;
66656   goto vdbe_error_halt;
66657
66658   /* Jump to here for any other kind of fatal error.  The "rc" variable
66659   ** should hold the error number.
66660   */
66661 abort_due_to_error:
66662   assert( p->zErrMsg==0 );
66663   if( db->mallocFailed ) rc = SQLITE_NOMEM;
66664   if( rc!=SQLITE_IOERR_NOMEM ){
66665     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
66666   }
66667   goto vdbe_error_halt;
66668
66669   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
66670   ** flag.
66671   */
66672 abort_due_to_interrupt:
66673   assert( db->u1.isInterrupted );
66674   rc = SQLITE_INTERRUPT;
66675   p->rc = rc;
66676   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
66677   goto vdbe_error_halt;
66678 }
66679
66680 /************** End of vdbe.c ************************************************/
66681 /************** Begin file vdbeblob.c ****************************************/
66682 /*
66683 ** 2007 May 1
66684 **
66685 ** The author disclaims copyright to this source code.  In place of
66686 ** a legal notice, here is a blessing:
66687 **
66688 **    May you do good and not evil.
66689 **    May you find forgiveness for yourself and forgive others.
66690 **    May you share freely, never taking more than you give.
66691 **
66692 *************************************************************************
66693 **
66694 ** This file contains code used to implement incremental BLOB I/O.
66695 */
66696
66697
66698 #ifndef SQLITE_OMIT_INCRBLOB
66699
66700 /*
66701 ** Valid sqlite3_blob* handles point to Incrblob structures.
66702 */
66703 typedef struct Incrblob Incrblob;
66704 struct Incrblob {
66705   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
66706   int nByte;              /* Size of open blob, in bytes */
66707   int iOffset;            /* Byte offset of blob in cursor data */
66708   int iCol;               /* Table column this handle is open on */
66709   BtCursor *pCsr;         /* Cursor pointing at blob row */
66710   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
66711   sqlite3 *db;            /* The associated database */
66712 };
66713
66714
66715 /*
66716 ** This function is used by both blob_open() and blob_reopen(). It seeks
66717 ** the b-tree cursor associated with blob handle p to point to row iRow.
66718 ** If successful, SQLITE_OK is returned and subsequent calls to
66719 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
66720 **
66721 ** If an error occurs, or if the specified row does not exist or does not
66722 ** contain a value of type TEXT or BLOB in the column nominated when the
66723 ** blob handle was opened, then an error code is returned and *pzErr may
66724 ** be set to point to a buffer containing an error message. It is the
66725 ** responsibility of the caller to free the error message buffer using
66726 ** sqlite3DbFree().
66727 **
66728 ** If an error does occur, then the b-tree cursor is closed. All subsequent
66729 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will 
66730 ** immediately return SQLITE_ABORT.
66731 */
66732 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
66733   int rc;                         /* Error code */
66734   char *zErr = 0;                 /* Error message */
66735   Vdbe *v = (Vdbe *)p->pStmt;
66736
66737   /* Set the value of the SQL statements only variable to integer iRow. 
66738   ** This is done directly instead of using sqlite3_bind_int64() to avoid 
66739   ** triggering asserts related to mutexes.
66740   */
66741   assert( v->aVar[0].flags&MEM_Int );
66742   v->aVar[0].u.i = iRow;
66743
66744   rc = sqlite3_step(p->pStmt);
66745   if( rc==SQLITE_ROW ){
66746     u32 type = v->apCsr[0]->aType[p->iCol];
66747     if( type<12 ){
66748       zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
66749           type==0?"null": type==7?"real": "integer"
66750       );
66751       rc = SQLITE_ERROR;
66752       sqlite3_finalize(p->pStmt);
66753       p->pStmt = 0;
66754     }else{
66755       p->iOffset = v->apCsr[0]->aOffset[p->iCol];
66756       p->nByte = sqlite3VdbeSerialTypeLen(type);
66757       p->pCsr =  v->apCsr[0]->pCursor;
66758       sqlite3BtreeEnterCursor(p->pCsr);
66759       sqlite3BtreeCacheOverflow(p->pCsr);
66760       sqlite3BtreeLeaveCursor(p->pCsr);
66761     }
66762   }
66763
66764   if( rc==SQLITE_ROW ){
66765     rc = SQLITE_OK;
66766   }else if( p->pStmt ){
66767     rc = sqlite3_finalize(p->pStmt);
66768     p->pStmt = 0;
66769     if( rc==SQLITE_OK ){
66770       zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
66771       rc = SQLITE_ERROR;
66772     }else{
66773       zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
66774     }
66775   }
66776
66777   assert( rc!=SQLITE_OK || zErr==0 );
66778   assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
66779
66780   *pzErr = zErr;
66781   return rc;
66782 }
66783
66784 /*
66785 ** Open a blob handle.
66786 */
66787 SQLITE_API int sqlite3_blob_open(
66788   sqlite3* db,            /* The database connection */
66789   const char *zDb,        /* The attached database containing the blob */
66790   const char *zTable,     /* The table containing the blob */
66791   const char *zColumn,    /* The column containing the blob */
66792   sqlite_int64 iRow,      /* The row containing the glob */
66793   int flags,              /* True -> read/write access, false -> read-only */
66794   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
66795 ){
66796   int nAttempt = 0;
66797   int iCol;               /* Index of zColumn in row-record */
66798
66799   /* This VDBE program seeks a btree cursor to the identified 
66800   ** db/table/row entry. The reason for using a vdbe program instead
66801   ** of writing code to use the b-tree layer directly is that the
66802   ** vdbe program will take advantage of the various transaction,
66803   ** locking and error handling infrastructure built into the vdbe.
66804   **
66805   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
66806   ** Code external to the Vdbe then "borrows" the b-tree cursor and
66807   ** uses it to implement the blob_read(), blob_write() and 
66808   ** blob_bytes() functions.
66809   **
66810   ** The sqlite3_blob_close() function finalizes the vdbe program,
66811   ** which closes the b-tree cursor and (possibly) commits the 
66812   ** transaction.
66813   */
66814   static const VdbeOpList openBlob[] = {
66815     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
66816     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
66817     {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
66818
66819     /* One of the following two instructions is replaced by an OP_Noop. */
66820     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
66821     {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
66822
66823     {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
66824     {OP_NotExists, 0, 10, 1},      /* 6: Seek the cursor */
66825     {OP_Column, 0, 0, 1},          /* 7  */
66826     {OP_ResultRow, 1, 0, 0},       /* 8  */
66827     {OP_Goto, 0, 5, 0},            /* 9  */
66828     {OP_Close, 0, 0, 0},           /* 10 */
66829     {OP_Halt, 0, 0, 0},            /* 11 */
66830   };
66831
66832   int rc = SQLITE_OK;
66833   char *zErr = 0;
66834   Table *pTab;
66835   Parse *pParse = 0;
66836   Incrblob *pBlob = 0;
66837
66838   flags = !!flags;                /* flags = (flags ? 1 : 0); */
66839   *ppBlob = 0;
66840
66841   sqlite3_mutex_enter(db->mutex);
66842
66843   pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
66844   if( !pBlob ) goto blob_open_out;
66845   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
66846   if( !pParse ) goto blob_open_out;
66847
66848   do {
66849     memset(pParse, 0, sizeof(Parse));
66850     pParse->db = db;
66851     sqlite3DbFree(db, zErr);
66852     zErr = 0;
66853
66854     sqlite3BtreeEnterAll(db);
66855     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
66856     if( pTab && IsVirtual(pTab) ){
66857       pTab = 0;
66858       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
66859     }
66860 #ifndef SQLITE_OMIT_VIEW
66861     if( pTab && pTab->pSelect ){
66862       pTab = 0;
66863       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
66864     }
66865 #endif
66866     if( !pTab ){
66867       if( pParse->zErrMsg ){
66868         sqlite3DbFree(db, zErr);
66869         zErr = pParse->zErrMsg;
66870         pParse->zErrMsg = 0;
66871       }
66872       rc = SQLITE_ERROR;
66873       sqlite3BtreeLeaveAll(db);
66874       goto blob_open_out;
66875     }
66876
66877     /* Now search pTab for the exact column. */
66878     for(iCol=0; iCol<pTab->nCol; iCol++) {
66879       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
66880         break;
66881       }
66882     }
66883     if( iCol==pTab->nCol ){
66884       sqlite3DbFree(db, zErr);
66885       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
66886       rc = SQLITE_ERROR;
66887       sqlite3BtreeLeaveAll(db);
66888       goto blob_open_out;
66889     }
66890
66891     /* If the value is being opened for writing, check that the
66892     ** column is not indexed, and that it is not part of a foreign key. 
66893     ** It is against the rules to open a column to which either of these
66894     ** descriptions applies for writing.  */
66895     if( flags ){
66896       const char *zFault = 0;
66897       Index *pIdx;
66898 #ifndef SQLITE_OMIT_FOREIGN_KEY
66899       if( db->flags&SQLITE_ForeignKeys ){
66900         /* Check that the column is not part of an FK child key definition. It
66901         ** is not necessary to check if it is part of a parent key, as parent
66902         ** key columns must be indexed. The check below will pick up this 
66903         ** case.  */
66904         FKey *pFKey;
66905         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
66906           int j;
66907           for(j=0; j<pFKey->nCol; j++){
66908             if( pFKey->aCol[j].iFrom==iCol ){
66909               zFault = "foreign key";
66910             }
66911           }
66912         }
66913       }
66914 #endif
66915       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
66916         int j;
66917         for(j=0; j<pIdx->nColumn; j++){
66918           if( pIdx->aiColumn[j]==iCol ){
66919             zFault = "indexed";
66920           }
66921         }
66922       }
66923       if( zFault ){
66924         sqlite3DbFree(db, zErr);
66925         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
66926         rc = SQLITE_ERROR;
66927         sqlite3BtreeLeaveAll(db);
66928         goto blob_open_out;
66929       }
66930     }
66931
66932     pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
66933     assert( pBlob->pStmt || db->mallocFailed );
66934     if( pBlob->pStmt ){
66935       Vdbe *v = (Vdbe *)pBlob->pStmt;
66936       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
66937
66938       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
66939
66940
66941       /* Configure the OP_Transaction */
66942       sqlite3VdbeChangeP1(v, 0, iDb);
66943       sqlite3VdbeChangeP2(v, 0, flags);
66944
66945       /* Configure the OP_VerifyCookie */
66946       sqlite3VdbeChangeP1(v, 1, iDb);
66947       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
66948
66949       /* Make sure a mutex is held on the table to be accessed */
66950       sqlite3VdbeUsesBtree(v, iDb); 
66951
66952       /* Configure the OP_TableLock instruction */
66953 #ifdef SQLITE_OMIT_SHARED_CACHE
66954       sqlite3VdbeChangeToNoop(v, 2, 1);
66955 #else
66956       sqlite3VdbeChangeP1(v, 2, iDb);
66957       sqlite3VdbeChangeP2(v, 2, pTab->tnum);
66958       sqlite3VdbeChangeP3(v, 2, flags);
66959       sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
66960 #endif
66961
66962       /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
66963       ** parameter of the other to pTab->tnum.  */
66964       sqlite3VdbeChangeToNoop(v, 4 - flags, 1);
66965       sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
66966       sqlite3VdbeChangeP3(v, 3 + flags, iDb);
66967
66968       /* Configure the number of columns. Configure the cursor to
66969       ** think that the table has one more column than it really
66970       ** does. An OP_Column to retrieve this imaginary column will
66971       ** always return an SQL NULL. This is useful because it means
66972       ** we can invoke OP_Column to fill in the vdbe cursors type 
66973       ** and offset cache without causing any IO.
66974       */
66975       sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
66976       sqlite3VdbeChangeP2(v, 7, pTab->nCol);
66977       if( !db->mallocFailed ){
66978         sqlite3VdbeMakeReady(v, 1, 1, 1, 0, 0, 0);
66979       }
66980     }
66981    
66982     pBlob->flags = flags;
66983     pBlob->iCol = iCol;
66984     pBlob->db = db;
66985     sqlite3BtreeLeaveAll(db);
66986     if( db->mallocFailed ){
66987       goto blob_open_out;
66988     }
66989     sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
66990     rc = blobSeekToRow(pBlob, iRow, &zErr);
66991   } while( (++nAttempt)<5 && rc==SQLITE_SCHEMA );
66992
66993 blob_open_out:
66994   if( rc==SQLITE_OK && db->mallocFailed==0 ){
66995     *ppBlob = (sqlite3_blob *)pBlob;
66996   }else{
66997     if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
66998     sqlite3DbFree(db, pBlob);
66999   }
67000   sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
67001   sqlite3DbFree(db, zErr);
67002   sqlite3StackFree(db, pParse);
67003   rc = sqlite3ApiExit(db, rc);
67004   sqlite3_mutex_leave(db->mutex);
67005   return rc;
67006 }
67007
67008 /*
67009 ** Close a blob handle that was previously created using
67010 ** sqlite3_blob_open().
67011 */
67012 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
67013   Incrblob *p = (Incrblob *)pBlob;
67014   int rc;
67015   sqlite3 *db;
67016
67017   if( p ){
67018     db = p->db;
67019     sqlite3_mutex_enter(db->mutex);
67020     rc = sqlite3_finalize(p->pStmt);
67021     sqlite3DbFree(db, p);
67022     sqlite3_mutex_leave(db->mutex);
67023   }else{
67024     rc = SQLITE_OK;
67025   }
67026   return rc;
67027 }
67028
67029 /*
67030 ** Perform a read or write operation on a blob
67031 */
67032 static int blobReadWrite(
67033   sqlite3_blob *pBlob, 
67034   void *z, 
67035   int n, 
67036   int iOffset, 
67037   int (*xCall)(BtCursor*, u32, u32, void*)
67038 ){
67039   int rc;
67040   Incrblob *p = (Incrblob *)pBlob;
67041   Vdbe *v;
67042   sqlite3 *db;
67043
67044   if( p==0 ) return SQLITE_MISUSE_BKPT;
67045   db = p->db;
67046   sqlite3_mutex_enter(db->mutex);
67047   v = (Vdbe*)p->pStmt;
67048
67049   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
67050     /* Request is out of range. Return a transient error. */
67051     rc = SQLITE_ERROR;
67052     sqlite3Error(db, SQLITE_ERROR, 0);
67053   }else if( v==0 ){
67054     /* If there is no statement handle, then the blob-handle has
67055     ** already been invalidated. Return SQLITE_ABORT in this case.
67056     */
67057     rc = SQLITE_ABORT;
67058   }else{
67059     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
67060     ** returned, clean-up the statement handle.
67061     */
67062     assert( db == v->db );
67063     sqlite3BtreeEnterCursor(p->pCsr);
67064     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
67065     sqlite3BtreeLeaveCursor(p->pCsr);
67066     if( rc==SQLITE_ABORT ){
67067       sqlite3VdbeFinalize(v);
67068       p->pStmt = 0;
67069     }else{
67070       db->errCode = rc;
67071       v->rc = rc;
67072     }
67073   }
67074   rc = sqlite3ApiExit(db, rc);
67075   sqlite3_mutex_leave(db->mutex);
67076   return rc;
67077 }
67078
67079 /*
67080 ** Read data from a blob handle.
67081 */
67082 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
67083   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
67084 }
67085
67086 /*
67087 ** Write data to a blob handle.
67088 */
67089 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
67090   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
67091 }
67092
67093 /*
67094 ** Query a blob handle for the size of the data.
67095 **
67096 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
67097 ** so no mutex is required for access.
67098 */
67099 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
67100   Incrblob *p = (Incrblob *)pBlob;
67101   return (p && p->pStmt) ? p->nByte : 0;
67102 }
67103
67104 /*
67105 ** Move an existing blob handle to point to a different row of the same
67106 ** database table.
67107 **
67108 ** If an error occurs, or if the specified row does not exist or does not
67109 ** contain a blob or text value, then an error code is returned and the
67110 ** database handle error code and message set. If this happens, then all 
67111 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close()) 
67112 ** immediately return SQLITE_ABORT.
67113 */
67114 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
67115   int rc;
67116   Incrblob *p = (Incrblob *)pBlob;
67117   sqlite3 *db;
67118
67119   if( p==0 ) return SQLITE_MISUSE_BKPT;
67120   db = p->db;
67121   sqlite3_mutex_enter(db->mutex);
67122
67123   if( p->pStmt==0 ){
67124     /* If there is no statement handle, then the blob-handle has
67125     ** already been invalidated. Return SQLITE_ABORT in this case.
67126     */
67127     rc = SQLITE_ABORT;
67128   }else{
67129     char *zErr;
67130     rc = blobSeekToRow(p, iRow, &zErr);
67131     if( rc!=SQLITE_OK ){
67132       sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
67133       sqlite3DbFree(db, zErr);
67134     }
67135     assert( rc!=SQLITE_SCHEMA );
67136   }
67137
67138   rc = sqlite3ApiExit(db, rc);
67139   assert( rc==SQLITE_OK || p->pStmt==0 );
67140   sqlite3_mutex_leave(db->mutex);
67141   return rc;
67142 }
67143
67144 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
67145
67146 /************** End of vdbeblob.c ********************************************/
67147 /************** Begin file journal.c *****************************************/
67148 /*
67149 ** 2007 August 22
67150 **
67151 ** The author disclaims copyright to this source code.  In place of
67152 ** a legal notice, here is a blessing:
67153 **
67154 **    May you do good and not evil.
67155 **    May you find forgiveness for yourself and forgive others.
67156 **    May you share freely, never taking more than you give.
67157 **
67158 *************************************************************************
67159 **
67160 ** This file implements a special kind of sqlite3_file object used
67161 ** by SQLite to create journal files if the atomic-write optimization
67162 ** is enabled.
67163 **
67164 ** The distinctive characteristic of this sqlite3_file is that the
67165 ** actual on disk file is created lazily. When the file is created,
67166 ** the caller specifies a buffer size for an in-memory buffer to
67167 ** be used to service read() and write() requests. The actual file
67168 ** on disk is not created or populated until either:
67169 **
67170 **   1) The in-memory representation grows too large for the allocated 
67171 **      buffer, or
67172 **   2) The sqlite3JournalCreate() function is called.
67173 */
67174 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
67175
67176
67177 /*
67178 ** A JournalFile object is a subclass of sqlite3_file used by
67179 ** as an open file handle for journal files.
67180 */
67181 struct JournalFile {
67182   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
67183   int nBuf;                       /* Size of zBuf[] in bytes */
67184   char *zBuf;                     /* Space to buffer journal writes */
67185   int iSize;                      /* Amount of zBuf[] currently used */
67186   int flags;                      /* xOpen flags */
67187   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
67188   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
67189   const char *zJournal;           /* Name of the journal file */
67190 };
67191 typedef struct JournalFile JournalFile;
67192
67193 /*
67194 ** If it does not already exists, create and populate the on-disk file 
67195 ** for JournalFile p.
67196 */
67197 static int createFile(JournalFile *p){
67198   int rc = SQLITE_OK;
67199   if( !p->pReal ){
67200     sqlite3_file *pReal = (sqlite3_file *)&p[1];
67201     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
67202     if( rc==SQLITE_OK ){
67203       p->pReal = pReal;
67204       if( p->iSize>0 ){
67205         assert(p->iSize<=p->nBuf);
67206         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
67207       }
67208     }
67209   }
67210   return rc;
67211 }
67212
67213 /*
67214 ** Close the file.
67215 */
67216 static int jrnlClose(sqlite3_file *pJfd){
67217   JournalFile *p = (JournalFile *)pJfd;
67218   if( p->pReal ){
67219     sqlite3OsClose(p->pReal);
67220   }
67221   sqlite3_free(p->zBuf);
67222   return SQLITE_OK;
67223 }
67224
67225 /*
67226 ** Read data from the file.
67227 */
67228 static int jrnlRead(
67229   sqlite3_file *pJfd,    /* The journal file from which to read */
67230   void *zBuf,            /* Put the results here */
67231   int iAmt,              /* Number of bytes to read */
67232   sqlite_int64 iOfst     /* Begin reading at this offset */
67233 ){
67234   int rc = SQLITE_OK;
67235   JournalFile *p = (JournalFile *)pJfd;
67236   if( p->pReal ){
67237     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
67238   }else if( (iAmt+iOfst)>p->iSize ){
67239     rc = SQLITE_IOERR_SHORT_READ;
67240   }else{
67241     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
67242   }
67243   return rc;
67244 }
67245
67246 /*
67247 ** Write data to the file.
67248 */
67249 static int jrnlWrite(
67250   sqlite3_file *pJfd,    /* The journal file into which to write */
67251   const void *zBuf,      /* Take data to be written from here */
67252   int iAmt,              /* Number of bytes to write */
67253   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
67254 ){
67255   int rc = SQLITE_OK;
67256   JournalFile *p = (JournalFile *)pJfd;
67257   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
67258     rc = createFile(p);
67259   }
67260   if( rc==SQLITE_OK ){
67261     if( p->pReal ){
67262       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
67263     }else{
67264       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
67265       if( p->iSize<(iOfst+iAmt) ){
67266         p->iSize = (iOfst+iAmt);
67267       }
67268     }
67269   }
67270   return rc;
67271 }
67272
67273 /*
67274 ** Truncate the file.
67275 */
67276 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
67277   int rc = SQLITE_OK;
67278   JournalFile *p = (JournalFile *)pJfd;
67279   if( p->pReal ){
67280     rc = sqlite3OsTruncate(p->pReal, size);
67281   }else if( size<p->iSize ){
67282     p->iSize = size;
67283   }
67284   return rc;
67285 }
67286
67287 /*
67288 ** Sync the file.
67289 */
67290 static int jrnlSync(sqlite3_file *pJfd, int flags){
67291   int rc;
67292   JournalFile *p = (JournalFile *)pJfd;
67293   if( p->pReal ){
67294     rc = sqlite3OsSync(p->pReal, flags);
67295   }else{
67296     rc = SQLITE_OK;
67297   }
67298   return rc;
67299 }
67300
67301 /*
67302 ** Query the size of the file in bytes.
67303 */
67304 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
67305   int rc = SQLITE_OK;
67306   JournalFile *p = (JournalFile *)pJfd;
67307   if( p->pReal ){
67308     rc = sqlite3OsFileSize(p->pReal, pSize);
67309   }else{
67310     *pSize = (sqlite_int64) p->iSize;
67311   }
67312   return rc;
67313 }
67314
67315 /*
67316 ** Table of methods for JournalFile sqlite3_file object.
67317 */
67318 static struct sqlite3_io_methods JournalFileMethods = {
67319   1,             /* iVersion */
67320   jrnlClose,     /* xClose */
67321   jrnlRead,      /* xRead */
67322   jrnlWrite,     /* xWrite */
67323   jrnlTruncate,  /* xTruncate */
67324   jrnlSync,      /* xSync */
67325   jrnlFileSize,  /* xFileSize */
67326   0,             /* xLock */
67327   0,             /* xUnlock */
67328   0,             /* xCheckReservedLock */
67329   0,             /* xFileControl */
67330   0,             /* xSectorSize */
67331   0,             /* xDeviceCharacteristics */
67332   0,             /* xShmMap */
67333   0,             /* xShmLock */
67334   0,             /* xShmBarrier */
67335   0              /* xShmUnmap */
67336 };
67337
67338 /* 
67339 ** Open a journal file.
67340 */
67341 SQLITE_PRIVATE int sqlite3JournalOpen(
67342   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
67343   const char *zName,         /* Name of the journal file */
67344   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
67345   int flags,                 /* Opening flags */
67346   int nBuf                   /* Bytes buffered before opening the file */
67347 ){
67348   JournalFile *p = (JournalFile *)pJfd;
67349   memset(p, 0, sqlite3JournalSize(pVfs));
67350   if( nBuf>0 ){
67351     p->zBuf = sqlite3MallocZero(nBuf);
67352     if( !p->zBuf ){
67353       return SQLITE_NOMEM;
67354     }
67355   }else{
67356     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
67357   }
67358   p->pMethod = &JournalFileMethods;
67359   p->nBuf = nBuf;
67360   p->flags = flags;
67361   p->zJournal = zName;
67362   p->pVfs = pVfs;
67363   return SQLITE_OK;
67364 }
67365
67366 /*
67367 ** If the argument p points to a JournalFile structure, and the underlying
67368 ** file has not yet been created, create it now.
67369 */
67370 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
67371   if( p->pMethods!=&JournalFileMethods ){
67372     return SQLITE_OK;
67373   }
67374   return createFile((JournalFile *)p);
67375 }
67376
67377 /* 
67378 ** Return the number of bytes required to store a JournalFile that uses vfs
67379 ** pVfs to create the underlying on-disk files.
67380 */
67381 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
67382   return (pVfs->szOsFile+sizeof(JournalFile));
67383 }
67384 #endif
67385
67386 /************** End of journal.c *********************************************/
67387 /************** Begin file memjournal.c **************************************/
67388 /*
67389 ** 2008 October 7
67390 **
67391 ** The author disclaims copyright to this source code.  In place of
67392 ** a legal notice, here is a blessing:
67393 **
67394 **    May you do good and not evil.
67395 **    May you find forgiveness for yourself and forgive others.
67396 **    May you share freely, never taking more than you give.
67397 **
67398 *************************************************************************
67399 **
67400 ** This file contains code use to implement an in-memory rollback journal.
67401 ** The in-memory rollback journal is used to journal transactions for
67402 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
67403 */
67404
67405 /* Forward references to internal structures */
67406 typedef struct MemJournal MemJournal;
67407 typedef struct FilePoint FilePoint;
67408 typedef struct FileChunk FileChunk;
67409
67410 /* Space to hold the rollback journal is allocated in increments of
67411 ** this many bytes.
67412 **
67413 ** The size chosen is a little less than a power of two.  That way,
67414 ** the FileChunk object will have a size that almost exactly fills
67415 ** a power-of-two allocation.  This mimimizes wasted space in power-of-two
67416 ** memory allocators.
67417 */
67418 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
67419
67420 /* Macro to find the minimum of two numeric values.
67421 */
67422 #ifndef MIN
67423 # define MIN(x,y) ((x)<(y)?(x):(y))
67424 #endif
67425
67426 /*
67427 ** The rollback journal is composed of a linked list of these structures.
67428 */
67429 struct FileChunk {
67430   FileChunk *pNext;               /* Next chunk in the journal */
67431   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
67432 };
67433
67434 /*
67435 ** An instance of this object serves as a cursor into the rollback journal.
67436 ** The cursor can be either for reading or writing.
67437 */
67438 struct FilePoint {
67439   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
67440   FileChunk *pChunk;              /* Specific chunk into which cursor points */
67441 };
67442
67443 /*
67444 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
67445 ** is an instance of this class.
67446 */
67447 struct MemJournal {
67448   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
67449   FileChunk *pFirst;              /* Head of in-memory chunk-list */
67450   FilePoint endpoint;             /* Pointer to the end of the file */
67451   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
67452 };
67453
67454 /*
67455 ** Read data from the in-memory journal file.  This is the implementation
67456 ** of the sqlite3_vfs.xRead method.
67457 */
67458 static int memjrnlRead(
67459   sqlite3_file *pJfd,    /* The journal file from which to read */
67460   void *zBuf,            /* Put the results here */
67461   int iAmt,              /* Number of bytes to read */
67462   sqlite_int64 iOfst     /* Begin reading at this offset */
67463 ){
67464   MemJournal *p = (MemJournal *)pJfd;
67465   u8 *zOut = zBuf;
67466   int nRead = iAmt;
67467   int iChunkOffset;
67468   FileChunk *pChunk;
67469
67470   /* SQLite never tries to read past the end of a rollback journal file */
67471   assert( iOfst+iAmt<=p->endpoint.iOffset );
67472
67473   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
67474     sqlite3_int64 iOff = 0;
67475     for(pChunk=p->pFirst; 
67476         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
67477         pChunk=pChunk->pNext
67478     ){
67479       iOff += JOURNAL_CHUNKSIZE;
67480     }
67481   }else{
67482     pChunk = p->readpoint.pChunk;
67483   }
67484
67485   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
67486   do {
67487     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
67488     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
67489     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
67490     zOut += nCopy;
67491     nRead -= iSpace;
67492     iChunkOffset = 0;
67493   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
67494   p->readpoint.iOffset = iOfst+iAmt;
67495   p->readpoint.pChunk = pChunk;
67496
67497   return SQLITE_OK;
67498 }
67499
67500 /*
67501 ** Write data to the file.
67502 */
67503 static int memjrnlWrite(
67504   sqlite3_file *pJfd,    /* The journal file into which to write */
67505   const void *zBuf,      /* Take data to be written from here */
67506   int iAmt,              /* Number of bytes to write */
67507   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
67508 ){
67509   MemJournal *p = (MemJournal *)pJfd;
67510   int nWrite = iAmt;
67511   u8 *zWrite = (u8 *)zBuf;
67512
67513   /* An in-memory journal file should only ever be appended to. Random
67514   ** access writes are not required by sqlite.
67515   */
67516   assert( iOfst==p->endpoint.iOffset );
67517   UNUSED_PARAMETER(iOfst);
67518
67519   while( nWrite>0 ){
67520     FileChunk *pChunk = p->endpoint.pChunk;
67521     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
67522     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
67523
67524     if( iChunkOffset==0 ){
67525       /* New chunk is required to extend the file. */
67526       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
67527       if( !pNew ){
67528         return SQLITE_IOERR_NOMEM;
67529       }
67530       pNew->pNext = 0;
67531       if( pChunk ){
67532         assert( p->pFirst );
67533         pChunk->pNext = pNew;
67534       }else{
67535         assert( !p->pFirst );
67536         p->pFirst = pNew;
67537       }
67538       p->endpoint.pChunk = pNew;
67539     }
67540
67541     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
67542     zWrite += iSpace;
67543     nWrite -= iSpace;
67544     p->endpoint.iOffset += iSpace;
67545   }
67546
67547   return SQLITE_OK;
67548 }
67549
67550 /*
67551 ** Truncate the file.
67552 */
67553 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
67554   MemJournal *p = (MemJournal *)pJfd;
67555   FileChunk *pChunk;
67556   assert(size==0);
67557   UNUSED_PARAMETER(size);
67558   pChunk = p->pFirst;
67559   while( pChunk ){
67560     FileChunk *pTmp = pChunk;
67561     pChunk = pChunk->pNext;
67562     sqlite3_free(pTmp);
67563   }
67564   sqlite3MemJournalOpen(pJfd);
67565   return SQLITE_OK;
67566 }
67567
67568 /*
67569 ** Close the file.
67570 */
67571 static int memjrnlClose(sqlite3_file *pJfd){
67572   memjrnlTruncate(pJfd, 0);
67573   return SQLITE_OK;
67574 }
67575
67576
67577 /*
67578 ** Sync the file.
67579 **
67580 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
67581 ** is never called in a working implementation.  This implementation
67582 ** exists purely as a contingency, in case some malfunction in some other
67583 ** part of SQLite causes Sync to be called by mistake.
67584 */
67585 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
67586   UNUSED_PARAMETER2(NotUsed, NotUsed2);
67587   return SQLITE_OK;
67588 }
67589
67590 /*
67591 ** Query the size of the file in bytes.
67592 */
67593 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
67594   MemJournal *p = (MemJournal *)pJfd;
67595   *pSize = (sqlite_int64) p->endpoint.iOffset;
67596   return SQLITE_OK;
67597 }
67598
67599 /*
67600 ** Table of methods for MemJournal sqlite3_file object.
67601 */
67602 static const struct sqlite3_io_methods MemJournalMethods = {
67603   1,                /* iVersion */
67604   memjrnlClose,     /* xClose */
67605   memjrnlRead,      /* xRead */
67606   memjrnlWrite,     /* xWrite */
67607   memjrnlTruncate,  /* xTruncate */
67608   memjrnlSync,      /* xSync */
67609   memjrnlFileSize,  /* xFileSize */
67610   0,                /* xLock */
67611   0,                /* xUnlock */
67612   0,                /* xCheckReservedLock */
67613   0,                /* xFileControl */
67614   0,                /* xSectorSize */
67615   0,                /* xDeviceCharacteristics */
67616   0,                /* xShmMap */
67617   0,                /* xShmLock */
67618   0,                /* xShmBarrier */
67619   0                 /* xShmUnlock */
67620 };
67621
67622 /* 
67623 ** Open a journal file.
67624 */
67625 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
67626   MemJournal *p = (MemJournal *)pJfd;
67627   assert( EIGHT_BYTE_ALIGNMENT(p) );
67628   memset(p, 0, sqlite3MemJournalSize());
67629   p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
67630 }
67631
67632 /*
67633 ** Return true if the file-handle passed as an argument is 
67634 ** an in-memory journal 
67635 */
67636 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
67637   return pJfd->pMethods==&MemJournalMethods;
67638 }
67639
67640 /* 
67641 ** Return the number of bytes required to store a MemJournal file descriptor.
67642 */
67643 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
67644   return sizeof(MemJournal);
67645 }
67646
67647 /************** End of memjournal.c ******************************************/
67648 /************** Begin file walker.c ******************************************/
67649 /*
67650 ** 2008 August 16
67651 **
67652 ** The author disclaims copyright to this source code.  In place of
67653 ** a legal notice, here is a blessing:
67654 **
67655 **    May you do good and not evil.
67656 **    May you find forgiveness for yourself and forgive others.
67657 **    May you share freely, never taking more than you give.
67658 **
67659 *************************************************************************
67660 ** This file contains routines used for walking the parser tree for
67661 ** an SQL statement.
67662 */
67663
67664
67665 /*
67666 ** Walk an expression tree.  Invoke the callback once for each node
67667 ** of the expression, while decending.  (In other words, the callback
67668 ** is invoked before visiting children.)
67669 **
67670 ** The return value from the callback should be one of the WRC_*
67671 ** constants to specify how to proceed with the walk.
67672 **
67673 **    WRC_Continue      Continue descending down the tree.
67674 **
67675 **    WRC_Prune         Do not descend into child nodes.  But allow
67676 **                      the walk to continue with sibling nodes.
67677 **
67678 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
67679 **                      return the top-level walk call.
67680 **
67681 ** The return value from this routine is WRC_Abort to abandon the tree walk
67682 ** and WRC_Continue to continue.
67683 */
67684 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
67685   int rc;
67686   if( pExpr==0 ) return WRC_Continue;
67687   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
67688   testcase( ExprHasProperty(pExpr, EP_Reduced) );
67689   rc = pWalker->xExprCallback(pWalker, pExpr);
67690   if( rc==WRC_Continue
67691               && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
67692     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
67693     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
67694     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
67695       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
67696     }else{
67697       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
67698     }
67699   }
67700   return rc & WRC_Abort;
67701 }
67702
67703 /*
67704 ** Call sqlite3WalkExpr() for every expression in list p or until
67705 ** an abort request is seen.
67706 */
67707 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
67708   int i;
67709   struct ExprList_item *pItem;
67710   if( p ){
67711     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
67712       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
67713     }
67714   }
67715   return WRC_Continue;
67716 }
67717
67718 /*
67719 ** Walk all expressions associated with SELECT statement p.  Do
67720 ** not invoke the SELECT callback on p, but do (of course) invoke
67721 ** any expr callbacks and SELECT callbacks that come from subqueries.
67722 ** Return WRC_Abort or WRC_Continue.
67723 */
67724 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
67725   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
67726   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
67727   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
67728   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
67729   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
67730   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
67731   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
67732   return WRC_Continue;
67733 }
67734
67735 /*
67736 ** Walk the parse trees associated with all subqueries in the
67737 ** FROM clause of SELECT statement p.  Do not invoke the select
67738 ** callback on p, but do invoke it on each FROM clause subquery
67739 ** and on any subqueries further down in the tree.  Return 
67740 ** WRC_Abort or WRC_Continue;
67741 */
67742 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
67743   SrcList *pSrc;
67744   int i;
67745   struct SrcList_item *pItem;
67746
67747   pSrc = p->pSrc;
67748   if( ALWAYS(pSrc) ){
67749     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
67750       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
67751         return WRC_Abort;
67752       }
67753     }
67754   }
67755   return WRC_Continue;
67756
67757
67758 /*
67759 ** Call sqlite3WalkExpr() for every expression in Select statement p.
67760 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
67761 ** on the compound select chain, p->pPrior.
67762 **
67763 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
67764 ** there is an abort request.
67765 **
67766 ** If the Walker does not have an xSelectCallback() then this routine
67767 ** is a no-op returning WRC_Continue.
67768 */
67769 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
67770   int rc;
67771   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
67772   rc = WRC_Continue;
67773   while( p  ){
67774     rc = pWalker->xSelectCallback(pWalker, p);
67775     if( rc ) break;
67776     if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
67777     if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
67778     p = p->pPrior;
67779   }
67780   return rc & WRC_Abort;
67781 }
67782
67783 /************** End of walker.c **********************************************/
67784 /************** Begin file resolve.c *****************************************/
67785 /*
67786 ** 2008 August 18
67787 **
67788 ** The author disclaims copyright to this source code.  In place of
67789 ** a legal notice, here is a blessing:
67790 **
67791 **    May you do good and not evil.
67792 **    May you find forgiveness for yourself and forgive others.
67793 **    May you share freely, never taking more than you give.
67794 **
67795 *************************************************************************
67796 **
67797 ** This file contains routines used for walking the parser tree and
67798 ** resolve all identifiers by associating them with a particular
67799 ** table and column.
67800 */
67801
67802 /*
67803 ** Turn the pExpr expression into an alias for the iCol-th column of the
67804 ** result set in pEList.
67805 **
67806 ** If the result set column is a simple column reference, then this routine
67807 ** makes an exact copy.  But for any other kind of expression, this
67808 ** routine make a copy of the result set column as the argument to the
67809 ** TK_AS operator.  The TK_AS operator causes the expression to be
67810 ** evaluated just once and then reused for each alias.
67811 **
67812 ** The reason for suppressing the TK_AS term when the expression is a simple
67813 ** column reference is so that the column reference will be recognized as
67814 ** usable by indices within the WHERE clause processing logic. 
67815 **
67816 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
67817 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
67818 **
67819 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
67820 **
67821 ** Is equivalent to:
67822 **
67823 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
67824 **
67825 ** The result of random()%5 in the GROUP BY clause is probably different
67826 ** from the result in the result-set.  We might fix this someday.  Or
67827 ** then again, we might not...
67828 */
67829 static void resolveAlias(
67830   Parse *pParse,         /* Parsing context */
67831   ExprList *pEList,      /* A result set */
67832   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
67833   Expr *pExpr,           /* Transform this into an alias to the result set */
67834   const char *zType      /* "GROUP" or "ORDER" or "" */
67835 ){
67836   Expr *pOrig;           /* The iCol-th column of the result set */
67837   Expr *pDup;            /* Copy of pOrig */
67838   sqlite3 *db;           /* The database connection */
67839
67840   assert( iCol>=0 && iCol<pEList->nExpr );
67841   pOrig = pEList->a[iCol].pExpr;
67842   assert( pOrig!=0 );
67843   assert( pOrig->flags & EP_Resolved );
67844   db = pParse->db;
67845   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
67846     pDup = sqlite3ExprDup(db, pOrig, 0);
67847     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
67848     if( pDup==0 ) return;
67849     if( pEList->a[iCol].iAlias==0 ){
67850       pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
67851     }
67852     pDup->iTable = pEList->a[iCol].iAlias;
67853   }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
67854     pDup = sqlite3ExprDup(db, pOrig, 0);
67855     if( pDup==0 ) return;
67856   }else{
67857     char *zToken = pOrig->u.zToken;
67858     assert( zToken!=0 );
67859     pOrig->u.zToken = 0;
67860     pDup = sqlite3ExprDup(db, pOrig, 0);
67861     pOrig->u.zToken = zToken;
67862     if( pDup==0 ) return;
67863     assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
67864     pDup->flags2 |= EP2_MallocedToken;
67865     pDup->u.zToken = sqlite3DbStrDup(db, zToken);
67866   }
67867   if( pExpr->flags & EP_ExpCollate ){
67868     pDup->pColl = pExpr->pColl;
67869     pDup->flags |= EP_ExpCollate;
67870   }
67871
67872   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 
67873   ** prevents ExprDelete() from deleting the Expr structure itself,
67874   ** allowing it to be repopulated by the memcpy() on the following line.
67875   */
67876   ExprSetProperty(pExpr, EP_Static);
67877   sqlite3ExprDelete(db, pExpr);
67878   memcpy(pExpr, pDup, sizeof(*pExpr));
67879   sqlite3DbFree(db, pDup);
67880 }
67881
67882 /*
67883 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
67884 ** that name in the set of source tables in pSrcList and make the pExpr 
67885 ** expression node refer back to that source column.  The following changes
67886 ** are made to pExpr:
67887 **
67888 **    pExpr->iDb           Set the index in db->aDb[] of the database X
67889 **                         (even if X is implied).
67890 **    pExpr->iTable        Set to the cursor number for the table obtained
67891 **                         from pSrcList.
67892 **    pExpr->pTab          Points to the Table structure of X.Y (even if
67893 **                         X and/or Y are implied.)
67894 **    pExpr->iColumn       Set to the column number within the table.
67895 **    pExpr->op            Set to TK_COLUMN.
67896 **    pExpr->pLeft         Any expression this points to is deleted
67897 **    pExpr->pRight        Any expression this points to is deleted.
67898 **
67899 ** The zDb variable is the name of the database (the "X").  This value may be
67900 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
67901 ** can be used.  The zTable variable is the name of the table (the "Y").  This
67902 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
67903 ** means that the form of the name is Z and that columns from any table
67904 ** can be used.
67905 **
67906 ** If the name cannot be resolved unambiguously, leave an error message
67907 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
67908 */
67909 static int lookupName(
67910   Parse *pParse,       /* The parsing context */
67911   const char *zDb,     /* Name of the database containing table, or NULL */
67912   const char *zTab,    /* Name of table containing column, or NULL */
67913   const char *zCol,    /* Name of the column. */
67914   NameContext *pNC,    /* The name context used to resolve the name */
67915   Expr *pExpr          /* Make this EXPR node point to the selected column */
67916 ){
67917   int i, j;            /* Loop counters */
67918   int cnt = 0;                      /* Number of matching column names */
67919   int cntTab = 0;                   /* Number of matching table names */
67920   sqlite3 *db = pParse->db;         /* The database connection */
67921   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
67922   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
67923   NameContext *pTopNC = pNC;        /* First namecontext in the list */
67924   Schema *pSchema = 0;              /* Schema of the expression */
67925   int isTrigger = 0;
67926
67927   assert( pNC );     /* the name context cannot be NULL. */
67928   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
67929   assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
67930
67931   /* Initialize the node to no-match */
67932   pExpr->iTable = -1;
67933   pExpr->pTab = 0;
67934   ExprSetIrreducible(pExpr);
67935
67936   /* Start at the inner-most context and move outward until a match is found */
67937   while( pNC && cnt==0 ){
67938     ExprList *pEList;
67939     SrcList *pSrcList = pNC->pSrcList;
67940
67941     if( pSrcList ){
67942       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
67943         Table *pTab;
67944         int iDb;
67945         Column *pCol;
67946   
67947         pTab = pItem->pTab;
67948         assert( pTab!=0 && pTab->zName!=0 );
67949         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
67950         assert( pTab->nCol>0 );
67951         if( zTab ){
67952           if( pItem->zAlias ){
67953             char *zTabName = pItem->zAlias;
67954             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
67955           }else{
67956             char *zTabName = pTab->zName;
67957             if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
67958               continue;
67959             }
67960             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
67961               continue;
67962             }
67963           }
67964         }
67965         if( 0==(cntTab++) ){
67966           pExpr->iTable = pItem->iCursor;
67967           pExpr->pTab = pTab;
67968           pSchema = pTab->pSchema;
67969           pMatch = pItem;
67970         }
67971         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
67972           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
67973             IdList *pUsing;
67974             cnt++;
67975             pExpr->iTable = pItem->iCursor;
67976             pExpr->pTab = pTab;
67977             pMatch = pItem;
67978             pSchema = pTab->pSchema;
67979             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
67980             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
67981             if( i<pSrcList->nSrc-1 ){
67982               if( pItem[1].jointype & JT_NATURAL ){
67983                 /* If this match occurred in the left table of a natural join,
67984                 ** then skip the right table to avoid a duplicate match */
67985                 pItem++;
67986                 i++;
67987               }else if( (pUsing = pItem[1].pUsing)!=0 ){
67988                 /* If this match occurs on a column that is in the USING clause
67989                 ** of a join, skip the search of the right table of the join
67990                 ** to avoid a duplicate match there. */
67991                 int k;
67992                 for(k=0; k<pUsing->nId; k++){
67993                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
67994                     pItem++;
67995                     i++;
67996                     break;
67997                   }
67998                 }
67999               }
68000             }
68001             break;
68002           }
68003         }
68004       }
68005     }
68006
68007 #ifndef SQLITE_OMIT_TRIGGER
68008     /* If we have not already resolved the name, then maybe 
68009     ** it is a new.* or old.* trigger argument reference
68010     */
68011     if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
68012       int op = pParse->eTriggerOp;
68013       Table *pTab = 0;
68014       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
68015       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
68016         pExpr->iTable = 1;
68017         pTab = pParse->pTriggerTab;
68018       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
68019         pExpr->iTable = 0;
68020         pTab = pParse->pTriggerTab;
68021       }
68022
68023       if( pTab ){ 
68024         int iCol;
68025         pSchema = pTab->pSchema;
68026         cntTab++;
68027         for(iCol=0; iCol<pTab->nCol; iCol++){
68028           Column *pCol = &pTab->aCol[iCol];
68029           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
68030             if( iCol==pTab->iPKey ){
68031               iCol = -1;
68032             }
68033             break;
68034           }
68035         }
68036         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
68037           iCol = -1;        /* IMP: R-44911-55124 */
68038         }
68039         if( iCol<pTab->nCol ){
68040           cnt++;
68041           if( iCol<0 ){
68042             pExpr->affinity = SQLITE_AFF_INTEGER;
68043           }else if( pExpr->iTable==0 ){
68044             testcase( iCol==31 );
68045             testcase( iCol==32 );
68046             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
68047           }else{
68048             testcase( iCol==31 );
68049             testcase( iCol==32 );
68050             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
68051           }
68052           pExpr->iColumn = (i16)iCol;
68053           pExpr->pTab = pTab;
68054           isTrigger = 1;
68055         }
68056       }
68057     }
68058 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
68059
68060     /*
68061     ** Perhaps the name is a reference to the ROWID
68062     */
68063     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
68064       cnt = 1;
68065       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
68066       pExpr->affinity = SQLITE_AFF_INTEGER;
68067     }
68068
68069     /*
68070     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
68071     ** might refer to an result-set alias.  This happens, for example, when
68072     ** we are resolving names in the WHERE clause of the following command:
68073     **
68074     **     SELECT a+b AS x FROM table WHERE x<10;
68075     **
68076     ** In cases like this, replace pExpr with a copy of the expression that
68077     ** forms the result set entry ("a+b" in the example) and return immediately.
68078     ** Note that the expression in the result set should have already been
68079     ** resolved by the time the WHERE clause is resolved.
68080     */
68081     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
68082       for(j=0; j<pEList->nExpr; j++){
68083         char *zAs = pEList->a[j].zName;
68084         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
68085           Expr *pOrig;
68086           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
68087           assert( pExpr->x.pList==0 );
68088           assert( pExpr->x.pSelect==0 );
68089           pOrig = pEList->a[j].pExpr;
68090           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
68091             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
68092             return WRC_Abort;
68093           }
68094           resolveAlias(pParse, pEList, j, pExpr, "");
68095           cnt = 1;
68096           pMatch = 0;
68097           assert( zTab==0 && zDb==0 );
68098           goto lookupname_end;
68099         }
68100       } 
68101     }
68102
68103     /* Advance to the next name context.  The loop will exit when either
68104     ** we have a match (cnt>0) or when we run out of name contexts.
68105     */
68106     if( cnt==0 ){
68107       pNC = pNC->pNext;
68108     }
68109   }
68110
68111   /*
68112   ** If X and Y are NULL (in other words if only the column name Z is
68113   ** supplied) and the value of Z is enclosed in double-quotes, then
68114   ** Z is a string literal if it doesn't match any column names.  In that
68115   ** case, we need to return right away and not make any changes to
68116   ** pExpr.
68117   **
68118   ** Because no reference was made to outer contexts, the pNC->nRef
68119   ** fields are not changed in any context.
68120   */
68121   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
68122     pExpr->op = TK_STRING;
68123     pExpr->pTab = 0;
68124     return WRC_Prune;
68125   }
68126
68127   /*
68128   ** cnt==0 means there was not match.  cnt>1 means there were two or
68129   ** more matches.  Either way, we have an error.
68130   */
68131   if( cnt!=1 ){
68132     const char *zErr;
68133     zErr = cnt==0 ? "no such column" : "ambiguous column name";
68134     if( zDb ){
68135       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
68136     }else if( zTab ){
68137       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
68138     }else{
68139       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
68140     }
68141     pParse->checkSchema = 1;
68142     pTopNC->nErr++;
68143   }
68144
68145   /* If a column from a table in pSrcList is referenced, then record
68146   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
68147   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
68148   ** column number is greater than the number of bits in the bitmask
68149   ** then set the high-order bit of the bitmask.
68150   */
68151   if( pExpr->iColumn>=0 && pMatch!=0 ){
68152     int n = pExpr->iColumn;
68153     testcase( n==BMS-1 );
68154     if( n>=BMS ){
68155       n = BMS-1;
68156     }
68157     assert( pMatch->iCursor==pExpr->iTable );
68158     pMatch->colUsed |= ((Bitmask)1)<<n;
68159   }
68160
68161   /* Clean up and return
68162   */
68163   sqlite3ExprDelete(db, pExpr->pLeft);
68164   pExpr->pLeft = 0;
68165   sqlite3ExprDelete(db, pExpr->pRight);
68166   pExpr->pRight = 0;
68167   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
68168 lookupname_end:
68169   if( cnt==1 ){
68170     assert( pNC!=0 );
68171     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
68172     /* Increment the nRef value on all name contexts from TopNC up to
68173     ** the point where the name matched. */
68174     for(;;){
68175       assert( pTopNC!=0 );
68176       pTopNC->nRef++;
68177       if( pTopNC==pNC ) break;
68178       pTopNC = pTopNC->pNext;
68179     }
68180     return WRC_Prune;
68181   } else {
68182     return WRC_Abort;
68183   }
68184 }
68185
68186 /*
68187 ** Allocate and return a pointer to an expression to load the column iCol
68188 ** from datasource iSrc in SrcList pSrc.
68189 */
68190 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
68191   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
68192   if( p ){
68193     struct SrcList_item *pItem = &pSrc->a[iSrc];
68194     p->pTab = pItem->pTab;
68195     p->iTable = pItem->iCursor;
68196     if( p->pTab->iPKey==iCol ){
68197       p->iColumn = -1;
68198     }else{
68199       p->iColumn = (ynVar)iCol;
68200       testcase( iCol==BMS );
68201       testcase( iCol==BMS-1 );
68202       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
68203     }
68204     ExprSetProperty(p, EP_Resolved);
68205   }
68206   return p;
68207 }
68208
68209 /*
68210 ** This routine is callback for sqlite3WalkExpr().
68211 **
68212 ** Resolve symbolic names into TK_COLUMN operators for the current
68213 ** node in the expression tree.  Return 0 to continue the search down
68214 ** the tree or 2 to abort the tree walk.
68215 **
68216 ** This routine also does error checking and name resolution for
68217 ** function names.  The operator for aggregate functions is changed
68218 ** to TK_AGG_FUNCTION.
68219 */
68220 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
68221   NameContext *pNC;
68222   Parse *pParse;
68223
68224   pNC = pWalker->u.pNC;
68225   assert( pNC!=0 );
68226   pParse = pNC->pParse;
68227   assert( pParse==pWalker->pParse );
68228
68229   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
68230   ExprSetProperty(pExpr, EP_Resolved);
68231 #ifndef NDEBUG
68232   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
68233     SrcList *pSrcList = pNC->pSrcList;
68234     int i;
68235     for(i=0; i<pNC->pSrcList->nSrc; i++){
68236       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
68237     }
68238   }
68239 #endif
68240   switch( pExpr->op ){
68241
68242 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
68243     /* The special operator TK_ROW means use the rowid for the first
68244     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
68245     ** clause processing on UPDATE and DELETE statements.
68246     */
68247     case TK_ROW: {
68248       SrcList *pSrcList = pNC->pSrcList;
68249       struct SrcList_item *pItem;
68250       assert( pSrcList && pSrcList->nSrc==1 );
68251       pItem = pSrcList->a; 
68252       pExpr->op = TK_COLUMN;
68253       pExpr->pTab = pItem->pTab;
68254       pExpr->iTable = pItem->iCursor;
68255       pExpr->iColumn = -1;
68256       pExpr->affinity = SQLITE_AFF_INTEGER;
68257       break;
68258     }
68259 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
68260
68261     /* A lone identifier is the name of a column.
68262     */
68263     case TK_ID: {
68264       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
68265     }
68266   
68267     /* A table name and column name:     ID.ID
68268     ** Or a database, table and column:  ID.ID.ID
68269     */
68270     case TK_DOT: {
68271       const char *zColumn;
68272       const char *zTable;
68273       const char *zDb;
68274       Expr *pRight;
68275
68276       /* if( pSrcList==0 ) break; */
68277       pRight = pExpr->pRight;
68278       if( pRight->op==TK_ID ){
68279         zDb = 0;
68280         zTable = pExpr->pLeft->u.zToken;
68281         zColumn = pRight->u.zToken;
68282       }else{
68283         assert( pRight->op==TK_DOT );
68284         zDb = pExpr->pLeft->u.zToken;
68285         zTable = pRight->pLeft->u.zToken;
68286         zColumn = pRight->pRight->u.zToken;
68287       }
68288       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
68289     }
68290
68291     /* Resolve function names
68292     */
68293     case TK_CONST_FUNC:
68294     case TK_FUNCTION: {
68295       ExprList *pList = pExpr->x.pList;    /* The argument list */
68296       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
68297       int no_such_func = 0;       /* True if no such function exists */
68298       int wrong_num_args = 0;     /* True if wrong number of arguments */
68299       int is_agg = 0;             /* True if is an aggregate function */
68300       int auth;                   /* Authorization to use the function */
68301       int nId;                    /* Number of characters in function name */
68302       const char *zId;            /* The function name. */
68303       FuncDef *pDef;              /* Information about the function */
68304       u8 enc = ENC(pParse->db);   /* The database encoding */
68305
68306       testcase( pExpr->op==TK_CONST_FUNC );
68307       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
68308       zId = pExpr->u.zToken;
68309       nId = sqlite3Strlen30(zId);
68310       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
68311       if( pDef==0 ){
68312         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
68313         if( pDef==0 ){
68314           no_such_func = 1;
68315         }else{
68316           wrong_num_args = 1;
68317         }
68318       }else{
68319         is_agg = pDef->xFunc==0;
68320       }
68321 #ifndef SQLITE_OMIT_AUTHORIZATION
68322       if( pDef ){
68323         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
68324         if( auth!=SQLITE_OK ){
68325           if( auth==SQLITE_DENY ){
68326             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
68327                                     pDef->zName);
68328             pNC->nErr++;
68329           }
68330           pExpr->op = TK_NULL;
68331           return WRC_Prune;
68332         }
68333       }
68334 #endif
68335       if( is_agg && !pNC->allowAgg ){
68336         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
68337         pNC->nErr++;
68338         is_agg = 0;
68339       }else if( no_such_func ){
68340         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
68341         pNC->nErr++;
68342       }else if( wrong_num_args ){
68343         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
68344              nId, zId);
68345         pNC->nErr++;
68346       }
68347       if( is_agg ){
68348         pExpr->op = TK_AGG_FUNCTION;
68349         pNC->hasAgg = 1;
68350       }
68351       if( is_agg ) pNC->allowAgg = 0;
68352       sqlite3WalkExprList(pWalker, pList);
68353       if( is_agg ) pNC->allowAgg = 1;
68354       /* FIX ME:  Compute pExpr->affinity based on the expected return
68355       ** type of the function 
68356       */
68357       return WRC_Prune;
68358     }
68359 #ifndef SQLITE_OMIT_SUBQUERY
68360     case TK_SELECT:
68361     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
68362 #endif
68363     case TK_IN: {
68364       testcase( pExpr->op==TK_IN );
68365       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
68366         int nRef = pNC->nRef;
68367 #ifndef SQLITE_OMIT_CHECK
68368         if( pNC->isCheck ){
68369           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
68370         }
68371 #endif
68372         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
68373         assert( pNC->nRef>=nRef );
68374         if( nRef!=pNC->nRef ){
68375           ExprSetProperty(pExpr, EP_VarSelect);
68376         }
68377       }
68378       break;
68379     }
68380 #ifndef SQLITE_OMIT_CHECK
68381     case TK_VARIABLE: {
68382       if( pNC->isCheck ){
68383         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
68384       }
68385       break;
68386     }
68387 #endif
68388   }
68389   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
68390 }
68391
68392 /*
68393 ** pEList is a list of expressions which are really the result set of the
68394 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
68395 ** This routine checks to see if pE is a simple identifier which corresponds
68396 ** to the AS-name of one of the terms of the expression list.  If it is,
68397 ** this routine return an integer between 1 and N where N is the number of
68398 ** elements in pEList, corresponding to the matching entry.  If there is
68399 ** no match, or if pE is not a simple identifier, then this routine
68400 ** return 0.
68401 **
68402 ** pEList has been resolved.  pE has not.
68403 */
68404 static int resolveAsName(
68405   Parse *pParse,     /* Parsing context for error messages */
68406   ExprList *pEList,  /* List of expressions to scan */
68407   Expr *pE           /* Expression we are trying to match */
68408 ){
68409   int i;             /* Loop counter */
68410
68411   UNUSED_PARAMETER(pParse);
68412
68413   if( pE->op==TK_ID ){
68414     char *zCol = pE->u.zToken;
68415     for(i=0; i<pEList->nExpr; i++){
68416       char *zAs = pEList->a[i].zName;
68417       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
68418         return i+1;
68419       }
68420     }
68421   }
68422   return 0;
68423 }
68424
68425 /*
68426 ** pE is a pointer to an expression which is a single term in the
68427 ** ORDER BY of a compound SELECT.  The expression has not been
68428 ** name resolved.
68429 **
68430 ** At the point this routine is called, we already know that the
68431 ** ORDER BY term is not an integer index into the result set.  That
68432 ** case is handled by the calling routine.
68433 **
68434 ** Attempt to match pE against result set columns in the left-most
68435 ** SELECT statement.  Return the index i of the matching column,
68436 ** as an indication to the caller that it should sort by the i-th column.
68437 ** The left-most column is 1.  In other words, the value returned is the
68438 ** same integer value that would be used in the SQL statement to indicate
68439 ** the column.
68440 **
68441 ** If there is no match, return 0.  Return -1 if an error occurs.
68442 */
68443 static int resolveOrderByTermToExprList(
68444   Parse *pParse,     /* Parsing context for error messages */
68445   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
68446   Expr *pE           /* The specific ORDER BY term */
68447 ){
68448   int i;             /* Loop counter */
68449   ExprList *pEList;  /* The columns of the result set */
68450   NameContext nc;    /* Name context for resolving pE */
68451   sqlite3 *db;       /* Database connection */
68452   int rc;            /* Return code from subprocedures */
68453   u8 savedSuppErr;   /* Saved value of db->suppressErr */
68454
68455   assert( sqlite3ExprIsInteger(pE, &i)==0 );
68456   pEList = pSelect->pEList;
68457
68458   /* Resolve all names in the ORDER BY term expression
68459   */
68460   memset(&nc, 0, sizeof(nc));
68461   nc.pParse = pParse;
68462   nc.pSrcList = pSelect->pSrc;
68463   nc.pEList = pEList;
68464   nc.allowAgg = 1;
68465   nc.nErr = 0;
68466   db = pParse->db;
68467   savedSuppErr = db->suppressErr;
68468   db->suppressErr = 1;
68469   rc = sqlite3ResolveExprNames(&nc, pE);
68470   db->suppressErr = savedSuppErr;
68471   if( rc ) return 0;
68472
68473   /* Try to match the ORDER BY expression against an expression
68474   ** in the result set.  Return an 1-based index of the matching
68475   ** result-set entry.
68476   */
68477   for(i=0; i<pEList->nExpr; i++){
68478     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
68479       return i+1;
68480     }
68481   }
68482
68483   /* If no match, return 0. */
68484   return 0;
68485 }
68486
68487 /*
68488 ** Generate an ORDER BY or GROUP BY term out-of-range error.
68489 */
68490 static void resolveOutOfRangeError(
68491   Parse *pParse,         /* The error context into which to write the error */
68492   const char *zType,     /* "ORDER" or "GROUP" */
68493   int i,                 /* The index (1-based) of the term out of range */
68494   int mx                 /* Largest permissible value of i */
68495 ){
68496   sqlite3ErrorMsg(pParse, 
68497     "%r %s BY term out of range - should be "
68498     "between 1 and %d", i, zType, mx);
68499 }
68500
68501 /*
68502 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
68503 ** each term of the ORDER BY clause is a constant integer between 1
68504 ** and N where N is the number of columns in the compound SELECT.
68505 **
68506 ** ORDER BY terms that are already an integer between 1 and N are
68507 ** unmodified.  ORDER BY terms that are integers outside the range of
68508 ** 1 through N generate an error.  ORDER BY terms that are expressions
68509 ** are matched against result set expressions of compound SELECT
68510 ** beginning with the left-most SELECT and working toward the right.
68511 ** At the first match, the ORDER BY expression is transformed into
68512 ** the integer column number.
68513 **
68514 ** Return the number of errors seen.
68515 */
68516 static int resolveCompoundOrderBy(
68517   Parse *pParse,        /* Parsing context.  Leave error messages here */
68518   Select *pSelect       /* The SELECT statement containing the ORDER BY */
68519 ){
68520   int i;
68521   ExprList *pOrderBy;
68522   ExprList *pEList;
68523   sqlite3 *db;
68524   int moreToDo = 1;
68525
68526   pOrderBy = pSelect->pOrderBy;
68527   if( pOrderBy==0 ) return 0;
68528   db = pParse->db;
68529 #if SQLITE_MAX_COLUMN
68530   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
68531     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
68532     return 1;
68533   }
68534 #endif
68535   for(i=0; i<pOrderBy->nExpr; i++){
68536     pOrderBy->a[i].done = 0;
68537   }
68538   pSelect->pNext = 0;
68539   while( pSelect->pPrior ){
68540     pSelect->pPrior->pNext = pSelect;
68541     pSelect = pSelect->pPrior;
68542   }
68543   while( pSelect && moreToDo ){
68544     struct ExprList_item *pItem;
68545     moreToDo = 0;
68546     pEList = pSelect->pEList;
68547     assert( pEList!=0 );
68548     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
68549       int iCol = -1;
68550       Expr *pE, *pDup;
68551       if( pItem->done ) continue;
68552       pE = pItem->pExpr;
68553       if( sqlite3ExprIsInteger(pE, &iCol) ){
68554         if( iCol<=0 || iCol>pEList->nExpr ){
68555           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
68556           return 1;
68557         }
68558       }else{
68559         iCol = resolveAsName(pParse, pEList, pE);
68560         if( iCol==0 ){
68561           pDup = sqlite3ExprDup(db, pE, 0);
68562           if( !db->mallocFailed ){
68563             assert(pDup);
68564             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
68565           }
68566           sqlite3ExprDelete(db, pDup);
68567         }
68568       }
68569       if( iCol>0 ){
68570         CollSeq *pColl = pE->pColl;
68571         int flags = pE->flags & EP_ExpCollate;
68572         sqlite3ExprDelete(db, pE);
68573         pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
68574         if( pE==0 ) return 1;
68575         pE->pColl = pColl;
68576         pE->flags |= EP_IntValue | flags;
68577         pE->u.iValue = iCol;
68578         pItem->iCol = (u16)iCol;
68579         pItem->done = 1;
68580       }else{
68581         moreToDo = 1;
68582       }
68583     }
68584     pSelect = pSelect->pNext;
68585   }
68586   for(i=0; i<pOrderBy->nExpr; i++){
68587     if( pOrderBy->a[i].done==0 ){
68588       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
68589             "column in the result set", i+1);
68590       return 1;
68591     }
68592   }
68593   return 0;
68594 }
68595
68596 /*
68597 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
68598 ** the SELECT statement pSelect.  If any term is reference to a
68599 ** result set expression (as determined by the ExprList.a.iCol field)
68600 ** then convert that term into a copy of the corresponding result set
68601 ** column.
68602 **
68603 ** If any errors are detected, add an error message to pParse and
68604 ** return non-zero.  Return zero if no errors are seen.
68605 */
68606 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
68607   Parse *pParse,        /* Parsing context.  Leave error messages here */
68608   Select *pSelect,      /* The SELECT statement containing the clause */
68609   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
68610   const char *zType     /* "ORDER" or "GROUP" */
68611 ){
68612   int i;
68613   sqlite3 *db = pParse->db;
68614   ExprList *pEList;
68615   struct ExprList_item *pItem;
68616
68617   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
68618 #if SQLITE_MAX_COLUMN
68619   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
68620     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
68621     return 1;
68622   }
68623 #endif
68624   pEList = pSelect->pEList;
68625   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
68626   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
68627     if( pItem->iCol ){
68628       if( pItem->iCol>pEList->nExpr ){
68629         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
68630         return 1;
68631       }
68632       resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
68633     }
68634   }
68635   return 0;
68636 }
68637
68638 /*
68639 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
68640 ** The Name context of the SELECT statement is pNC.  zType is either
68641 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
68642 **
68643 ** This routine resolves each term of the clause into an expression.
68644 ** If the order-by term is an integer I between 1 and N (where N is the
68645 ** number of columns in the result set of the SELECT) then the expression
68646 ** in the resolution is a copy of the I-th result-set expression.  If
68647 ** the order-by term is an identify that corresponds to the AS-name of
68648 ** a result-set expression, then the term resolves to a copy of the
68649 ** result-set expression.  Otherwise, the expression is resolved in
68650 ** the usual way - using sqlite3ResolveExprNames().
68651 **
68652 ** This routine returns the number of errors.  If errors occur, then
68653 ** an appropriate error message might be left in pParse.  (OOM errors
68654 ** excepted.)
68655 */
68656 static int resolveOrderGroupBy(
68657   NameContext *pNC,     /* The name context of the SELECT statement */
68658   Select *pSelect,      /* The SELECT statement holding pOrderBy */
68659   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
68660   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
68661 ){
68662   int i;                         /* Loop counter */
68663   int iCol;                      /* Column number */
68664   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
68665   Parse *pParse;                 /* Parsing context */
68666   int nResult;                   /* Number of terms in the result set */
68667
68668   if( pOrderBy==0 ) return 0;
68669   nResult = pSelect->pEList->nExpr;
68670   pParse = pNC->pParse;
68671   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
68672     Expr *pE = pItem->pExpr;
68673     iCol = resolveAsName(pParse, pSelect->pEList, pE);
68674     if( iCol>0 ){
68675       /* If an AS-name match is found, mark this ORDER BY column as being
68676       ** a copy of the iCol-th result-set column.  The subsequent call to
68677       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
68678       ** copy of the iCol-th result-set expression. */
68679       pItem->iCol = (u16)iCol;
68680       continue;
68681     }
68682     if( sqlite3ExprIsInteger(pE, &iCol) ){
68683       /* The ORDER BY term is an integer constant.  Again, set the column
68684       ** number so that sqlite3ResolveOrderGroupBy() will convert the
68685       ** order-by term to a copy of the result-set expression */
68686       if( iCol<1 ){
68687         resolveOutOfRangeError(pParse, zType, i+1, nResult);
68688         return 1;
68689       }
68690       pItem->iCol = (u16)iCol;
68691       continue;
68692     }
68693
68694     /* Otherwise, treat the ORDER BY term as an ordinary expression */
68695     pItem->iCol = 0;
68696     if( sqlite3ResolveExprNames(pNC, pE) ){
68697       return 1;
68698     }
68699   }
68700   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
68701 }
68702
68703 /*
68704 ** Resolve names in the SELECT statement p and all of its descendents.
68705 */
68706 static int resolveSelectStep(Walker *pWalker, Select *p){
68707   NameContext *pOuterNC;  /* Context that contains this SELECT */
68708   NameContext sNC;        /* Name context of this SELECT */
68709   int isCompound;         /* True if p is a compound select */
68710   int nCompound;          /* Number of compound terms processed so far */
68711   Parse *pParse;          /* Parsing context */
68712   ExprList *pEList;       /* Result set expression list */
68713   int i;                  /* Loop counter */
68714   ExprList *pGroupBy;     /* The GROUP BY clause */
68715   Select *pLeftmost;      /* Left-most of SELECT of a compound */
68716   sqlite3 *db;            /* Database connection */
68717   
68718
68719   assert( p!=0 );
68720   if( p->selFlags & SF_Resolved ){
68721     return WRC_Prune;
68722   }
68723   pOuterNC = pWalker->u.pNC;
68724   pParse = pWalker->pParse;
68725   db = pParse->db;
68726
68727   /* Normally sqlite3SelectExpand() will be called first and will have
68728   ** already expanded this SELECT.  However, if this is a subquery within
68729   ** an expression, sqlite3ResolveExprNames() will be called without a
68730   ** prior call to sqlite3SelectExpand().  When that happens, let
68731   ** sqlite3SelectPrep() do all of the processing for this SELECT.
68732   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
68733   ** this routine in the correct order.
68734   */
68735   if( (p->selFlags & SF_Expanded)==0 ){
68736     sqlite3SelectPrep(pParse, p, pOuterNC);
68737     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
68738   }
68739
68740   isCompound = p->pPrior!=0;
68741   nCompound = 0;
68742   pLeftmost = p;
68743   while( p ){
68744     assert( (p->selFlags & SF_Expanded)!=0 );
68745     assert( (p->selFlags & SF_Resolved)==0 );
68746     p->selFlags |= SF_Resolved;
68747
68748     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
68749     ** are not allowed to refer to any names, so pass an empty NameContext.
68750     */
68751     memset(&sNC, 0, sizeof(sNC));
68752     sNC.pParse = pParse;
68753     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
68754         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
68755       return WRC_Abort;
68756     }
68757   
68758     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
68759     ** resolve the result-set expression list.
68760     */
68761     sNC.allowAgg = 1;
68762     sNC.pSrcList = p->pSrc;
68763     sNC.pNext = pOuterNC;
68764   
68765     /* Resolve names in the result set. */
68766     pEList = p->pEList;
68767     assert( pEList!=0 );
68768     for(i=0; i<pEList->nExpr; i++){
68769       Expr *pX = pEList->a[i].pExpr;
68770       if( sqlite3ResolveExprNames(&sNC, pX) ){
68771         return WRC_Abort;
68772       }
68773     }
68774   
68775     /* Recursively resolve names in all subqueries
68776     */
68777     for(i=0; i<p->pSrc->nSrc; i++){
68778       struct SrcList_item *pItem = &p->pSrc->a[i];
68779       if( pItem->pSelect ){
68780         const char *zSavedContext = pParse->zAuthContext;
68781         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
68782         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
68783         pParse->zAuthContext = zSavedContext;
68784         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
68785       }
68786     }
68787   
68788     /* If there are no aggregate functions in the result-set, and no GROUP BY 
68789     ** expression, do not allow aggregates in any of the other expressions.
68790     */
68791     assert( (p->selFlags & SF_Aggregate)==0 );
68792     pGroupBy = p->pGroupBy;
68793     if( pGroupBy || sNC.hasAgg ){
68794       p->selFlags |= SF_Aggregate;
68795     }else{
68796       sNC.allowAgg = 0;
68797     }
68798   
68799     /* If a HAVING clause is present, then there must be a GROUP BY clause.
68800     */
68801     if( p->pHaving && !pGroupBy ){
68802       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
68803       return WRC_Abort;
68804     }
68805   
68806     /* Add the expression list to the name-context before parsing the
68807     ** other expressions in the SELECT statement. This is so that
68808     ** expressions in the WHERE clause (etc.) can refer to expressions by
68809     ** aliases in the result set.
68810     **
68811     ** Minor point: If this is the case, then the expression will be
68812     ** re-evaluated for each reference to it.
68813     */
68814     sNC.pEList = p->pEList;
68815     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
68816        sqlite3ResolveExprNames(&sNC, p->pHaving)
68817     ){
68818       return WRC_Abort;
68819     }
68820
68821     /* The ORDER BY and GROUP BY clauses may not refer to terms in
68822     ** outer queries 
68823     */
68824     sNC.pNext = 0;
68825     sNC.allowAgg = 1;
68826
68827     /* Process the ORDER BY clause for singleton SELECT statements.
68828     ** The ORDER BY clause for compounds SELECT statements is handled
68829     ** below, after all of the result-sets for all of the elements of
68830     ** the compound have been resolved.
68831     */
68832     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
68833       return WRC_Abort;
68834     }
68835     if( db->mallocFailed ){
68836       return WRC_Abort;
68837     }
68838   
68839     /* Resolve the GROUP BY clause.  At the same time, make sure 
68840     ** the GROUP BY clause does not contain aggregate functions.
68841     */
68842     if( pGroupBy ){
68843       struct ExprList_item *pItem;
68844     
68845       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
68846         return WRC_Abort;
68847       }
68848       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
68849         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
68850           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
68851               "the GROUP BY clause");
68852           return WRC_Abort;
68853         }
68854       }
68855     }
68856
68857     /* Advance to the next term of the compound
68858     */
68859     p = p->pPrior;
68860     nCompound++;
68861   }
68862
68863   /* Resolve the ORDER BY on a compound SELECT after all terms of
68864   ** the compound have been resolved.
68865   */
68866   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
68867     return WRC_Abort;
68868   }
68869
68870   return WRC_Prune;
68871 }
68872
68873 /*
68874 ** This routine walks an expression tree and resolves references to
68875 ** table columns and result-set columns.  At the same time, do error
68876 ** checking on function usage and set a flag if any aggregate functions
68877 ** are seen.
68878 **
68879 ** To resolve table columns references we look for nodes (or subtrees) of the 
68880 ** form X.Y.Z or Y.Z or just Z where
68881 **
68882 **      X:   The name of a database.  Ex:  "main" or "temp" or
68883 **           the symbolic name assigned to an ATTACH-ed database.
68884 **
68885 **      Y:   The name of a table in a FROM clause.  Or in a trigger
68886 **           one of the special names "old" or "new".
68887 **
68888 **      Z:   The name of a column in table Y.
68889 **
68890 ** The node at the root of the subtree is modified as follows:
68891 **
68892 **    Expr.op        Changed to TK_COLUMN
68893 **    Expr.pTab      Points to the Table object for X.Y
68894 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
68895 **    Expr.iTable    The VDBE cursor number for X.Y
68896 **
68897 **
68898 ** To resolve result-set references, look for expression nodes of the
68899 ** form Z (with no X and Y prefix) where the Z matches the right-hand
68900 ** size of an AS clause in the result-set of a SELECT.  The Z expression
68901 ** is replaced by a copy of the left-hand side of the result-set expression.
68902 ** Table-name and function resolution occurs on the substituted expression
68903 ** tree.  For example, in:
68904 **
68905 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
68906 **
68907 ** The "x" term of the order by is replaced by "a+b" to render:
68908 **
68909 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
68910 **
68911 ** Function calls are checked to make sure that the function is 
68912 ** defined and that the correct number of arguments are specified.
68913 ** If the function is an aggregate function, then the pNC->hasAgg is
68914 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
68915 ** If an expression contains aggregate functions then the EP_Agg
68916 ** property on the expression is set.
68917 **
68918 ** An error message is left in pParse if anything is amiss.  The number
68919 ** if errors is returned.
68920 */
68921 SQLITE_PRIVATE int sqlite3ResolveExprNames( 
68922   NameContext *pNC,       /* Namespace to resolve expressions in. */
68923   Expr *pExpr             /* The expression to be analyzed. */
68924 ){
68925   int savedHasAgg;
68926   Walker w;
68927
68928   if( pExpr==0 ) return 0;
68929 #if SQLITE_MAX_EXPR_DEPTH>0
68930   {
68931     Parse *pParse = pNC->pParse;
68932     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
68933       return 1;
68934     }
68935     pParse->nHeight += pExpr->nHeight;
68936   }
68937 #endif
68938   savedHasAgg = pNC->hasAgg;
68939   pNC->hasAgg = 0;
68940   w.xExprCallback = resolveExprStep;
68941   w.xSelectCallback = resolveSelectStep;
68942   w.pParse = pNC->pParse;
68943   w.u.pNC = pNC;
68944   sqlite3WalkExpr(&w, pExpr);
68945 #if SQLITE_MAX_EXPR_DEPTH>0
68946   pNC->pParse->nHeight -= pExpr->nHeight;
68947 #endif
68948   if( pNC->nErr>0 || w.pParse->nErr>0 ){
68949     ExprSetProperty(pExpr, EP_Error);
68950   }
68951   if( pNC->hasAgg ){
68952     ExprSetProperty(pExpr, EP_Agg);
68953   }else if( savedHasAgg ){
68954     pNC->hasAgg = 1;
68955   }
68956   return ExprHasProperty(pExpr, EP_Error);
68957 }
68958
68959
68960 /*
68961 ** Resolve all names in all expressions of a SELECT and in all
68962 ** decendents of the SELECT, including compounds off of p->pPrior,
68963 ** subqueries in expressions, and subqueries used as FROM clause
68964 ** terms.
68965 **
68966 ** See sqlite3ResolveExprNames() for a description of the kinds of
68967 ** transformations that occur.
68968 **
68969 ** All SELECT statements should have been expanded using
68970 ** sqlite3SelectExpand() prior to invoking this routine.
68971 */
68972 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
68973   Parse *pParse,         /* The parser context */
68974   Select *p,             /* The SELECT statement being coded. */
68975   NameContext *pOuterNC  /* Name context for parent SELECT statement */
68976 ){
68977   Walker w;
68978
68979   assert( p!=0 );
68980   w.xExprCallback = resolveExprStep;
68981   w.xSelectCallback = resolveSelectStep;
68982   w.pParse = pParse;
68983   w.u.pNC = pOuterNC;
68984   sqlite3WalkSelect(&w, p);
68985 }
68986
68987 /************** End of resolve.c *********************************************/
68988 /************** Begin file expr.c ********************************************/
68989 /*
68990 ** 2001 September 15
68991 **
68992 ** The author disclaims copyright to this source code.  In place of
68993 ** a legal notice, here is a blessing:
68994 **
68995 **    May you do good and not evil.
68996 **    May you find forgiveness for yourself and forgive others.
68997 **    May you share freely, never taking more than you give.
68998 **
68999 *************************************************************************
69000 ** This file contains routines used for analyzing expressions and
69001 ** for generating VDBE code that evaluates expressions in SQLite.
69002 */
69003
69004 /*
69005 ** Return the 'affinity' of the expression pExpr if any.
69006 **
69007 ** If pExpr is a column, a reference to a column via an 'AS' alias,
69008 ** or a sub-select with a column as the return value, then the 
69009 ** affinity of that column is returned. Otherwise, 0x00 is returned,
69010 ** indicating no affinity for the expression.
69011 **
69012 ** i.e. the WHERE clause expresssions in the following statements all
69013 ** have an affinity:
69014 **
69015 ** CREATE TABLE t1(a);
69016 ** SELECT * FROM t1 WHERE a;
69017 ** SELECT a AS b FROM t1 WHERE b;
69018 ** SELECT * FROM t1 WHERE (select a from t1);
69019 */
69020 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
69021   int op = pExpr->op;
69022   if( op==TK_SELECT ){
69023     assert( pExpr->flags&EP_xIsSelect );
69024     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
69025   }
69026 #ifndef SQLITE_OMIT_CAST
69027   if( op==TK_CAST ){
69028     assert( !ExprHasProperty(pExpr, EP_IntValue) );
69029     return sqlite3AffinityType(pExpr->u.zToken);
69030   }
69031 #endif
69032   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) 
69033    && pExpr->pTab!=0
69034   ){
69035     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
69036     ** a TK_COLUMN but was previously evaluated and cached in a register */
69037     int j = pExpr->iColumn;
69038     if( j<0 ) return SQLITE_AFF_INTEGER;
69039     assert( pExpr->pTab && j<pExpr->pTab->nCol );
69040     return pExpr->pTab->aCol[j].affinity;
69041   }
69042   return pExpr->affinity;
69043 }
69044
69045 /*
69046 ** Set the explicit collating sequence for an expression to the
69047 ** collating sequence supplied in the second argument.
69048 */
69049 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr *pExpr, CollSeq *pColl){
69050   if( pExpr && pColl ){
69051     pExpr->pColl = pColl;
69052     pExpr->flags |= EP_ExpCollate;
69053   }
69054   return pExpr;
69055 }
69056
69057 /*
69058 ** Set the collating sequence for expression pExpr to be the collating
69059 ** sequence named by pToken.   Return a pointer to the revised expression.
69060 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
69061 ** flag.  An explicit collating sequence will override implicit
69062 ** collating sequences.
69063 */
69064 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr *pExpr, Token *pCollName){
69065   char *zColl = 0;            /* Dequoted name of collation sequence */
69066   CollSeq *pColl;
69067   sqlite3 *db = pParse->db;
69068   zColl = sqlite3NameFromToken(db, pCollName);
69069   pColl = sqlite3LocateCollSeq(pParse, zColl);
69070   sqlite3ExprSetColl(pExpr, pColl);
69071   sqlite3DbFree(db, zColl);
69072   return pExpr;
69073 }
69074
69075 /*
69076 ** Return the default collation sequence for the expression pExpr. If
69077 ** there is no default collation type, return 0.
69078 */
69079 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
69080   CollSeq *pColl = 0;
69081   Expr *p = pExpr;
69082   while( ALWAYS(p) ){
69083     int op;
69084     pColl = p->pColl;
69085     if( pColl ) break;
69086     op = p->op;
69087     if( p->pTab!=0 && (
69088         op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
69089     )){
69090       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
69091       ** a TK_COLUMN but was previously evaluated and cached in a register */
69092       const char *zColl;
69093       int j = p->iColumn;
69094       if( j>=0 ){
69095         sqlite3 *db = pParse->db;
69096         zColl = p->pTab->aCol[j].zColl;
69097         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
69098         pExpr->pColl = pColl;
69099       }
69100       break;
69101     }
69102     if( op!=TK_CAST && op!=TK_UPLUS ){
69103       break;
69104     }
69105     p = p->pLeft;
69106   }
69107   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
69108     pColl = 0;
69109   }
69110   return pColl;
69111 }
69112
69113 /*
69114 ** pExpr is an operand of a comparison operator.  aff2 is the
69115 ** type affinity of the other operand.  This routine returns the
69116 ** type affinity that should be used for the comparison operator.
69117 */
69118 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
69119   char aff1 = sqlite3ExprAffinity(pExpr);
69120   if( aff1 && aff2 ){
69121     /* Both sides of the comparison are columns. If one has numeric
69122     ** affinity, use that. Otherwise use no affinity.
69123     */
69124     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
69125       return SQLITE_AFF_NUMERIC;
69126     }else{
69127       return SQLITE_AFF_NONE;
69128     }
69129   }else if( !aff1 && !aff2 ){
69130     /* Neither side of the comparison is a column.  Compare the
69131     ** results directly.
69132     */
69133     return SQLITE_AFF_NONE;
69134   }else{
69135     /* One side is a column, the other is not. Use the columns affinity. */
69136     assert( aff1==0 || aff2==0 );
69137     return (aff1 + aff2);
69138   }
69139 }
69140
69141 /*
69142 ** pExpr is a comparison operator.  Return the type affinity that should
69143 ** be applied to both operands prior to doing the comparison.
69144 */
69145 static char comparisonAffinity(Expr *pExpr){
69146   char aff;
69147   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
69148           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
69149           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
69150   assert( pExpr->pLeft );
69151   aff = sqlite3ExprAffinity(pExpr->pLeft);
69152   if( pExpr->pRight ){
69153     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
69154   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
69155     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
69156   }else if( !aff ){
69157     aff = SQLITE_AFF_NONE;
69158   }
69159   return aff;
69160 }
69161
69162 /*
69163 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
69164 ** idx_affinity is the affinity of an indexed column. Return true
69165 ** if the index with affinity idx_affinity may be used to implement
69166 ** the comparison in pExpr.
69167 */
69168 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
69169   char aff = comparisonAffinity(pExpr);
69170   switch( aff ){
69171     case SQLITE_AFF_NONE:
69172       return 1;
69173     case SQLITE_AFF_TEXT:
69174       return idx_affinity==SQLITE_AFF_TEXT;
69175     default:
69176       return sqlite3IsNumericAffinity(idx_affinity);
69177   }
69178 }
69179
69180 /*
69181 ** Return the P5 value that should be used for a binary comparison
69182 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
69183 */
69184 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
69185   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
69186   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
69187   return aff;
69188 }
69189
69190 /*
69191 ** Return a pointer to the collation sequence that should be used by
69192 ** a binary comparison operator comparing pLeft and pRight.
69193 **
69194 ** If the left hand expression has a collating sequence type, then it is
69195 ** used. Otherwise the collation sequence for the right hand expression
69196 ** is used, or the default (BINARY) if neither expression has a collating
69197 ** type.
69198 **
69199 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
69200 ** it is not considered.
69201 */
69202 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
69203   Parse *pParse, 
69204   Expr *pLeft, 
69205   Expr *pRight
69206 ){
69207   CollSeq *pColl;
69208   assert( pLeft );
69209   if( pLeft->flags & EP_ExpCollate ){
69210     assert( pLeft->pColl );
69211     pColl = pLeft->pColl;
69212   }else if( pRight && pRight->flags & EP_ExpCollate ){
69213     assert( pRight->pColl );
69214     pColl = pRight->pColl;
69215   }else{
69216     pColl = sqlite3ExprCollSeq(pParse, pLeft);
69217     if( !pColl ){
69218       pColl = sqlite3ExprCollSeq(pParse, pRight);
69219     }
69220   }
69221   return pColl;
69222 }
69223
69224 /*
69225 ** Generate code for a comparison operator.
69226 */
69227 static int codeCompare(
69228   Parse *pParse,    /* The parsing (and code generating) context */
69229   Expr *pLeft,      /* The left operand */
69230   Expr *pRight,     /* The right operand */
69231   int opcode,       /* The comparison opcode */
69232   int in1, int in2, /* Register holding operands */
69233   int dest,         /* Jump here if true.  */
69234   int jumpIfNull    /* If true, jump if either operand is NULL */
69235 ){
69236   int p5;
69237   int addr;
69238   CollSeq *p4;
69239
69240   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
69241   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
69242   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
69243                            (void*)p4, P4_COLLSEQ);
69244   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
69245   return addr;
69246 }
69247
69248 #if SQLITE_MAX_EXPR_DEPTH>0
69249 /*
69250 ** Check that argument nHeight is less than or equal to the maximum
69251 ** expression depth allowed. If it is not, leave an error message in
69252 ** pParse.
69253 */
69254 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
69255   int rc = SQLITE_OK;
69256   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
69257   if( nHeight>mxHeight ){
69258     sqlite3ErrorMsg(pParse, 
69259        "Expression tree is too large (maximum depth %d)", mxHeight
69260     );
69261     rc = SQLITE_ERROR;
69262   }
69263   return rc;
69264 }
69265
69266 /* The following three functions, heightOfExpr(), heightOfExprList()
69267 ** and heightOfSelect(), are used to determine the maximum height
69268 ** of any expression tree referenced by the structure passed as the
69269 ** first argument.
69270 **
69271 ** If this maximum height is greater than the current value pointed
69272 ** to by pnHeight, the second parameter, then set *pnHeight to that
69273 ** value.
69274 */
69275 static void heightOfExpr(Expr *p, int *pnHeight){
69276   if( p ){
69277     if( p->nHeight>*pnHeight ){
69278       *pnHeight = p->nHeight;
69279     }
69280   }
69281 }
69282 static void heightOfExprList(ExprList *p, int *pnHeight){
69283   if( p ){
69284     int i;
69285     for(i=0; i<p->nExpr; i++){
69286       heightOfExpr(p->a[i].pExpr, pnHeight);
69287     }
69288   }
69289 }
69290 static void heightOfSelect(Select *p, int *pnHeight){
69291   if( p ){
69292     heightOfExpr(p->pWhere, pnHeight);
69293     heightOfExpr(p->pHaving, pnHeight);
69294     heightOfExpr(p->pLimit, pnHeight);
69295     heightOfExpr(p->pOffset, pnHeight);
69296     heightOfExprList(p->pEList, pnHeight);
69297     heightOfExprList(p->pGroupBy, pnHeight);
69298     heightOfExprList(p->pOrderBy, pnHeight);
69299     heightOfSelect(p->pPrior, pnHeight);
69300   }
69301 }
69302
69303 /*
69304 ** Set the Expr.nHeight variable in the structure passed as an 
69305 ** argument. An expression with no children, Expr.pList or 
69306 ** Expr.pSelect member has a height of 1. Any other expression
69307 ** has a height equal to the maximum height of any other 
69308 ** referenced Expr plus one.
69309 */
69310 static void exprSetHeight(Expr *p){
69311   int nHeight = 0;
69312   heightOfExpr(p->pLeft, &nHeight);
69313   heightOfExpr(p->pRight, &nHeight);
69314   if( ExprHasProperty(p, EP_xIsSelect) ){
69315     heightOfSelect(p->x.pSelect, &nHeight);
69316   }else{
69317     heightOfExprList(p->x.pList, &nHeight);
69318   }
69319   p->nHeight = nHeight + 1;
69320 }
69321
69322 /*
69323 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
69324 ** the height is greater than the maximum allowed expression depth,
69325 ** leave an error in pParse.
69326 */
69327 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
69328   exprSetHeight(p);
69329   sqlite3ExprCheckHeight(pParse, p->nHeight);
69330 }
69331
69332 /*
69333 ** Return the maximum height of any expression tree referenced
69334 ** by the select statement passed as an argument.
69335 */
69336 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
69337   int nHeight = 0;
69338   heightOfSelect(p, &nHeight);
69339   return nHeight;
69340 }
69341 #else
69342   #define exprSetHeight(y)
69343 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
69344
69345 /*
69346 ** This routine is the core allocator for Expr nodes.
69347 **
69348 ** Construct a new expression node and return a pointer to it.  Memory
69349 ** for this node and for the pToken argument is a single allocation
69350 ** obtained from sqlite3DbMalloc().  The calling function
69351 ** is responsible for making sure the node eventually gets freed.
69352 **
69353 ** If dequote is true, then the token (if it exists) is dequoted.
69354 ** If dequote is false, no dequoting is performance.  The deQuote
69355 ** parameter is ignored if pToken is NULL or if the token does not
69356 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
69357 ** then the EP_DblQuoted flag is set on the expression node.
69358 **
69359 ** Special case:  If op==TK_INTEGER and pToken points to a string that
69360 ** can be translated into a 32-bit integer, then the token is not
69361 ** stored in u.zToken.  Instead, the integer values is written
69362 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
69363 ** is allocated to hold the integer text and the dequote flag is ignored.
69364 */
69365 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
69366   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
69367   int op,                 /* Expression opcode */
69368   const Token *pToken,    /* Token argument.  Might be NULL */
69369   int dequote             /* True to dequote */
69370 ){
69371   Expr *pNew;
69372   int nExtra = 0;
69373   int iValue = 0;
69374
69375   if( pToken ){
69376     if( op!=TK_INTEGER || pToken->z==0
69377           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
69378       nExtra = pToken->n+1;
69379     }
69380   }
69381   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
69382   if( pNew ){
69383     pNew->op = (u8)op;
69384     pNew->iAgg = -1;
69385     if( pToken ){
69386       if( nExtra==0 ){
69387         pNew->flags |= EP_IntValue;
69388         pNew->u.iValue = iValue;
69389       }else{
69390         int c;
69391         pNew->u.zToken = (char*)&pNew[1];
69392         memcpy(pNew->u.zToken, pToken->z, pToken->n);
69393         pNew->u.zToken[pToken->n] = 0;
69394         if( dequote && nExtra>=3 
69395              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
69396           sqlite3Dequote(pNew->u.zToken);
69397           if( c=='"' ) pNew->flags |= EP_DblQuoted;
69398         }
69399       }
69400     }
69401 #if SQLITE_MAX_EXPR_DEPTH>0
69402     pNew->nHeight = 1;
69403 #endif  
69404   }
69405   return pNew;
69406 }
69407
69408 /*
69409 ** Allocate a new expression node from a zero-terminated token that has
69410 ** already been dequoted.
69411 */
69412 SQLITE_PRIVATE Expr *sqlite3Expr(
69413   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
69414   int op,                 /* Expression opcode */
69415   const char *zToken      /* Token argument.  Might be NULL */
69416 ){
69417   Token x;
69418   x.z = zToken;
69419   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
69420   return sqlite3ExprAlloc(db, op, &x, 0);
69421 }
69422
69423 /*
69424 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
69425 **
69426 ** If pRoot==NULL that means that a memory allocation error has occurred.
69427 ** In that case, delete the subtrees pLeft and pRight.
69428 */
69429 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
69430   sqlite3 *db,
69431   Expr *pRoot,
69432   Expr *pLeft,
69433   Expr *pRight
69434 ){
69435   if( pRoot==0 ){
69436     assert( db->mallocFailed );
69437     sqlite3ExprDelete(db, pLeft);
69438     sqlite3ExprDelete(db, pRight);
69439   }else{
69440     if( pRight ){
69441       pRoot->pRight = pRight;
69442       if( pRight->flags & EP_ExpCollate ){
69443         pRoot->flags |= EP_ExpCollate;
69444         pRoot->pColl = pRight->pColl;
69445       }
69446     }
69447     if( pLeft ){
69448       pRoot->pLeft = pLeft;
69449       if( pLeft->flags & EP_ExpCollate ){
69450         pRoot->flags |= EP_ExpCollate;
69451         pRoot->pColl = pLeft->pColl;
69452       }
69453     }
69454     exprSetHeight(pRoot);
69455   }
69456 }
69457
69458 /*
69459 ** Allocate a Expr node which joins as many as two subtrees.
69460 **
69461 ** One or both of the subtrees can be NULL.  Return a pointer to the new
69462 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
69463 ** free the subtrees and return NULL.
69464 */
69465 SQLITE_PRIVATE Expr *sqlite3PExpr(
69466   Parse *pParse,          /* Parsing context */
69467   int op,                 /* Expression opcode */
69468   Expr *pLeft,            /* Left operand */
69469   Expr *pRight,           /* Right operand */
69470   const Token *pToken     /* Argument token */
69471 ){
69472   Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
69473   sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
69474   if( p ) {
69475     sqlite3ExprCheckHeight(pParse, p->nHeight);
69476   }
69477   return p;
69478 }
69479
69480 /*
69481 ** Join two expressions using an AND operator.  If either expression is
69482 ** NULL, then just return the other expression.
69483 */
69484 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
69485   if( pLeft==0 ){
69486     return pRight;
69487   }else if( pRight==0 ){
69488     return pLeft;
69489   }else{
69490     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
69491     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
69492     return pNew;
69493   }
69494 }
69495
69496 /*
69497 ** Construct a new expression node for a function with multiple
69498 ** arguments.
69499 */
69500 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
69501   Expr *pNew;
69502   sqlite3 *db = pParse->db;
69503   assert( pToken );
69504   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
69505   if( pNew==0 ){
69506     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
69507     return 0;
69508   }
69509   pNew->x.pList = pList;
69510   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
69511   sqlite3ExprSetHeight(pParse, pNew);
69512   return pNew;
69513 }
69514
69515 /*
69516 ** Assign a variable number to an expression that encodes a wildcard
69517 ** in the original SQL statement.  
69518 **
69519 ** Wildcards consisting of a single "?" are assigned the next sequential
69520 ** variable number.
69521 **
69522 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
69523 ** sure "nnn" is not too be to avoid a denial of service attack when
69524 ** the SQL statement comes from an external source.
69525 **
69526 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
69527 ** as the previous instance of the same wildcard.  Or if this is the first
69528 ** instance of the wildcard, the next sequenial variable number is
69529 ** assigned.
69530 */
69531 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
69532   sqlite3 *db = pParse->db;
69533   const char *z;
69534
69535   if( pExpr==0 ) return;
69536   assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
69537   z = pExpr->u.zToken;
69538   assert( z!=0 );
69539   assert( z[0]!=0 );
69540   if( z[1]==0 ){
69541     /* Wildcard of the form "?".  Assign the next variable number */
69542     assert( z[0]=='?' );
69543     pExpr->iColumn = (ynVar)(++pParse->nVar);
69544   }else if( z[0]=='?' ){
69545     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
69546     ** use it as the variable number */
69547     i64 i;
69548     int bOk = 0==sqlite3Atoi64(&z[1], &i, sqlite3Strlen30(&z[1]), SQLITE_UTF8);
69549     pExpr->iColumn = (ynVar)i;
69550     testcase( i==0 );
69551     testcase( i==1 );
69552     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
69553     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
69554     if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
69555       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
69556           db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
69557     }
69558     if( i>pParse->nVar ){
69559       pParse->nVar = (int)i;
69560     }
69561   }else{
69562     /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
69563     ** number as the prior appearance of the same name, or if the name
69564     ** has never appeared before, reuse the same variable number
69565     */
69566     int i;
69567     u32 n;
69568     n = sqlite3Strlen30(z);
69569     for(i=0; i<pParse->nVarExpr; i++){
69570       Expr *pE = pParse->apVarExpr[i];
69571       assert( pE!=0 );
69572       if( memcmp(pE->u.zToken, z, n)==0 && pE->u.zToken[n]==0 ){
69573         pExpr->iColumn = pE->iColumn;
69574         break;
69575       }
69576     }
69577     if( i>=pParse->nVarExpr ){
69578       pExpr->iColumn = (ynVar)(++pParse->nVar);
69579       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
69580         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
69581         pParse->apVarExpr =
69582             sqlite3DbReallocOrFree(
69583               db,
69584               pParse->apVarExpr,
69585               pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
69586             );
69587       }
69588       if( !db->mallocFailed ){
69589         assert( pParse->apVarExpr!=0 );
69590         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
69591       }
69592     }
69593   } 
69594   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
69595     sqlite3ErrorMsg(pParse, "too many SQL variables");
69596   }
69597 }
69598
69599 /*
69600 ** Recursively delete an expression tree.
69601 */
69602 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
69603   if( p==0 ) return;
69604   if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
69605     sqlite3ExprDelete(db, p->pLeft);
69606     sqlite3ExprDelete(db, p->pRight);
69607     if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
69608       sqlite3DbFree(db, p->u.zToken);
69609     }
69610     if( ExprHasProperty(p, EP_xIsSelect) ){
69611       sqlite3SelectDelete(db, p->x.pSelect);
69612     }else{
69613       sqlite3ExprListDelete(db, p->x.pList);
69614     }
69615   }
69616   if( !ExprHasProperty(p, EP_Static) ){
69617     sqlite3DbFree(db, p);
69618   }
69619 }
69620
69621 /*
69622 ** Return the number of bytes allocated for the expression structure 
69623 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
69624 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
69625 */
69626 static int exprStructSize(Expr *p){
69627   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
69628   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
69629   return EXPR_FULLSIZE;
69630 }
69631
69632 /*
69633 ** The dupedExpr*Size() routines each return the number of bytes required
69634 ** to store a copy of an expression or expression tree.  They differ in
69635 ** how much of the tree is measured.
69636 **
69637 **     dupedExprStructSize()     Size of only the Expr structure 
69638 **     dupedExprNodeSize()       Size of Expr + space for token
69639 **     dupedExprSize()           Expr + token + subtree components
69640 **
69641 ***************************************************************************
69642 **
69643 ** The dupedExprStructSize() function returns two values OR-ed together:  
69644 ** (1) the space required for a copy of the Expr structure only and 
69645 ** (2) the EP_xxx flags that indicate what the structure size should be.
69646 ** The return values is always one of:
69647 **
69648 **      EXPR_FULLSIZE
69649 **      EXPR_REDUCEDSIZE   | EP_Reduced
69650 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
69651 **
69652 ** The size of the structure can be found by masking the return value
69653 ** of this routine with 0xfff.  The flags can be found by masking the
69654 ** return value with EP_Reduced|EP_TokenOnly.
69655 **
69656 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
69657 ** (unreduced) Expr objects as they or originally constructed by the parser.
69658 ** During expression analysis, extra information is computed and moved into
69659 ** later parts of teh Expr object and that extra information might get chopped
69660 ** off if the expression is reduced.  Note also that it does not work to
69661 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
69662 ** to reduce a pristine expression tree from the parser.  The implementation
69663 ** of dupedExprStructSize() contain multiple assert() statements that attempt
69664 ** to enforce this constraint.
69665 */
69666 static int dupedExprStructSize(Expr *p, int flags){
69667   int nSize;
69668   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
69669   if( 0==(flags&EXPRDUP_REDUCE) ){
69670     nSize = EXPR_FULLSIZE;
69671   }else{
69672     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
69673     assert( !ExprHasProperty(p, EP_FromJoin) ); 
69674     assert( (p->flags2 & EP2_MallocedToken)==0 );
69675     assert( (p->flags2 & EP2_Irreducible)==0 );
69676     if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
69677       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
69678     }else{
69679       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
69680     }
69681   }
69682   return nSize;
69683 }
69684
69685 /*
69686 ** This function returns the space in bytes required to store the copy 
69687 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
69688 ** string is defined.)
69689 */
69690 static int dupedExprNodeSize(Expr *p, int flags){
69691   int nByte = dupedExprStructSize(p, flags) & 0xfff;
69692   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
69693     nByte += sqlite3Strlen30(p->u.zToken)+1;
69694   }
69695   return ROUND8(nByte);
69696 }
69697
69698 /*
69699 ** Return the number of bytes required to create a duplicate of the 
69700 ** expression passed as the first argument. The second argument is a
69701 ** mask containing EXPRDUP_XXX flags.
69702 **
69703 ** The value returned includes space to create a copy of the Expr struct
69704 ** itself and the buffer referred to by Expr.u.zToken, if any.
69705 **
69706 ** If the EXPRDUP_REDUCE flag is set, then the return value includes 
69707 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 
69708 ** and Expr.pRight variables (but not for any structures pointed to or 
69709 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
69710 */
69711 static int dupedExprSize(Expr *p, int flags){
69712   int nByte = 0;
69713   if( p ){
69714     nByte = dupedExprNodeSize(p, flags);
69715     if( flags&EXPRDUP_REDUCE ){
69716       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
69717     }
69718   }
69719   return nByte;
69720 }
69721
69722 /*
69723 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer 
69724 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough 
69725 ** to store the copy of expression p, the copies of p->u.zToken
69726 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
69727 ** if any. Before returning, *pzBuffer is set to the first byte passed the
69728 ** portion of the buffer copied into by this function.
69729 */
69730 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
69731   Expr *pNew = 0;                      /* Value to return */
69732   if( p ){
69733     const int isReduced = (flags&EXPRDUP_REDUCE);
69734     u8 *zAlloc;
69735     u32 staticFlag = 0;
69736
69737     assert( pzBuffer==0 || isReduced );
69738
69739     /* Figure out where to write the new Expr structure. */
69740     if( pzBuffer ){
69741       zAlloc = *pzBuffer;
69742       staticFlag = EP_Static;
69743     }else{
69744       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
69745     }
69746     pNew = (Expr *)zAlloc;
69747
69748     if( pNew ){
69749       /* Set nNewSize to the size allocated for the structure pointed to
69750       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
69751       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
69752       ** by the copy of the p->u.zToken string (if any).
69753       */
69754       const unsigned nStructSize = dupedExprStructSize(p, flags);
69755       const int nNewSize = nStructSize & 0xfff;
69756       int nToken;
69757       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
69758         nToken = sqlite3Strlen30(p->u.zToken) + 1;
69759       }else{
69760         nToken = 0;
69761       }
69762       if( isReduced ){
69763         assert( ExprHasProperty(p, EP_Reduced)==0 );
69764         memcpy(zAlloc, p, nNewSize);
69765       }else{
69766         int nSize = exprStructSize(p);
69767         memcpy(zAlloc, p, nSize);
69768         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
69769       }
69770
69771       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
69772       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
69773       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
69774       pNew->flags |= staticFlag;
69775
69776       /* Copy the p->u.zToken string, if any. */
69777       if( nToken ){
69778         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
69779         memcpy(zToken, p->u.zToken, nToken);
69780       }
69781
69782       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
69783         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
69784         if( ExprHasProperty(p, EP_xIsSelect) ){
69785           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
69786         }else{
69787           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
69788         }
69789       }
69790
69791       /* Fill in pNew->pLeft and pNew->pRight. */
69792       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
69793         zAlloc += dupedExprNodeSize(p, flags);
69794         if( ExprHasProperty(pNew, EP_Reduced) ){
69795           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
69796           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
69797         }
69798         if( pzBuffer ){
69799           *pzBuffer = zAlloc;
69800         }
69801       }else{
69802         pNew->flags2 = 0;
69803         if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
69804           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
69805           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
69806         }
69807       }
69808
69809     }
69810   }
69811   return pNew;
69812 }
69813
69814 /*
69815 ** The following group of routines make deep copies of expressions,
69816 ** expression lists, ID lists, and select statements.  The copies can
69817 ** be deleted (by being passed to their respective ...Delete() routines)
69818 ** without effecting the originals.
69819 **
69820 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
69821 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
69822 ** by subsequent calls to sqlite*ListAppend() routines.
69823 **
69824 ** Any tables that the SrcList might point to are not duplicated.
69825 **
69826 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
69827 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
69828 ** truncated version of the usual Expr structure that will be stored as
69829 ** part of the in-memory representation of the database schema.
69830 */
69831 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
69832   return exprDup(db, p, flags, 0);
69833 }
69834 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
69835   ExprList *pNew;
69836   struct ExprList_item *pItem, *pOldItem;
69837   int i;
69838   if( p==0 ) return 0;
69839   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
69840   if( pNew==0 ) return 0;
69841   pNew->iECursor = 0;
69842   pNew->nExpr = pNew->nAlloc = p->nExpr;
69843   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
69844   if( pItem==0 ){
69845     sqlite3DbFree(db, pNew);
69846     return 0;
69847   } 
69848   pOldItem = p->a;
69849   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
69850     Expr *pOldExpr = pOldItem->pExpr;
69851     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
69852     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
69853     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
69854     pItem->sortOrder = pOldItem->sortOrder;
69855     pItem->done = 0;
69856     pItem->iCol = pOldItem->iCol;
69857     pItem->iAlias = pOldItem->iAlias;
69858   }
69859   return pNew;
69860 }
69861
69862 /*
69863 ** If cursors, triggers, views and subqueries are all omitted from
69864 ** the build, then none of the following routines, except for 
69865 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
69866 ** called with a NULL argument.
69867 */
69868 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
69869  || !defined(SQLITE_OMIT_SUBQUERY)
69870 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
69871   SrcList *pNew;
69872   int i;
69873   int nByte;
69874   if( p==0 ) return 0;
69875   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
69876   pNew = sqlite3DbMallocRaw(db, nByte );
69877   if( pNew==0 ) return 0;
69878   pNew->nSrc = pNew->nAlloc = p->nSrc;
69879   for(i=0; i<p->nSrc; i++){
69880     struct SrcList_item *pNewItem = &pNew->a[i];
69881     struct SrcList_item *pOldItem = &p->a[i];
69882     Table *pTab;
69883     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
69884     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
69885     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
69886     pNewItem->jointype = pOldItem->jointype;
69887     pNewItem->iCursor = pOldItem->iCursor;
69888     pNewItem->isPopulated = pOldItem->isPopulated;
69889     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
69890     pNewItem->notIndexed = pOldItem->notIndexed;
69891     pNewItem->pIndex = pOldItem->pIndex;
69892     pTab = pNewItem->pTab = pOldItem->pTab;
69893     if( pTab ){
69894       pTab->nRef++;
69895     }
69896     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
69897     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
69898     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
69899     pNewItem->colUsed = pOldItem->colUsed;
69900   }
69901   return pNew;
69902 }
69903 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
69904   IdList *pNew;
69905   int i;
69906   if( p==0 ) return 0;
69907   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
69908   if( pNew==0 ) return 0;
69909   pNew->nId = pNew->nAlloc = p->nId;
69910   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
69911   if( pNew->a==0 ){
69912     sqlite3DbFree(db, pNew);
69913     return 0;
69914   }
69915   for(i=0; i<p->nId; i++){
69916     struct IdList_item *pNewItem = &pNew->a[i];
69917     struct IdList_item *pOldItem = &p->a[i];
69918     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
69919     pNewItem->idx = pOldItem->idx;
69920   }
69921   return pNew;
69922 }
69923 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
69924   Select *pNew;
69925   if( p==0 ) return 0;
69926   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
69927   if( pNew==0 ) return 0;
69928   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
69929   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
69930   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
69931   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
69932   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
69933   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
69934   pNew->op = p->op;
69935   pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
69936   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
69937   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
69938   pNew->iLimit = 0;
69939   pNew->iOffset = 0;
69940   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
69941   pNew->pRightmost = 0;
69942   pNew->addrOpenEphm[0] = -1;
69943   pNew->addrOpenEphm[1] = -1;
69944   pNew->addrOpenEphm[2] = -1;
69945   return pNew;
69946 }
69947 #else
69948 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
69949   assert( p==0 );
69950   return 0;
69951 }
69952 #endif
69953
69954
69955 /*
69956 ** Add a new element to the end of an expression list.  If pList is
69957 ** initially NULL, then create a new expression list.
69958 **
69959 ** If a memory allocation error occurs, the entire list is freed and
69960 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
69961 ** that the new entry was successfully appended.
69962 */
69963 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
69964   Parse *pParse,          /* Parsing context */
69965   ExprList *pList,        /* List to which to append. Might be NULL */
69966   Expr *pExpr             /* Expression to be appended. Might be NULL */
69967 ){
69968   sqlite3 *db = pParse->db;
69969   if( pList==0 ){
69970     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
69971     if( pList==0 ){
69972       goto no_mem;
69973     }
69974     assert( pList->nAlloc==0 );
69975   }
69976   if( pList->nAlloc<=pList->nExpr ){
69977     struct ExprList_item *a;
69978     int n = pList->nAlloc*2 + 4;
69979     a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
69980     if( a==0 ){
69981       goto no_mem;
69982     }
69983     pList->a = a;
69984     pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
69985   }
69986   assert( pList->a!=0 );
69987   if( 1 ){
69988     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
69989     memset(pItem, 0, sizeof(*pItem));
69990     pItem->pExpr = pExpr;
69991   }
69992   return pList;
69993
69994 no_mem:     
69995   /* Avoid leaking memory if malloc has failed. */
69996   sqlite3ExprDelete(db, pExpr);
69997   sqlite3ExprListDelete(db, pList);
69998   return 0;
69999 }
70000
70001 /*
70002 ** Set the ExprList.a[].zName element of the most recently added item
70003 ** on the expression list.
70004 **
70005 ** pList might be NULL following an OOM error.  But pName should never be
70006 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
70007 ** is set.
70008 */
70009 SQLITE_PRIVATE void sqlite3ExprListSetName(
70010   Parse *pParse,          /* Parsing context */
70011   ExprList *pList,        /* List to which to add the span. */
70012   Token *pName,           /* Name to be added */
70013   int dequote             /* True to cause the name to be dequoted */
70014 ){
70015   assert( pList!=0 || pParse->db->mallocFailed!=0 );
70016   if( pList ){
70017     struct ExprList_item *pItem;
70018     assert( pList->nExpr>0 );
70019     pItem = &pList->a[pList->nExpr-1];
70020     assert( pItem->zName==0 );
70021     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
70022     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
70023   }
70024 }
70025
70026 /*
70027 ** Set the ExprList.a[].zSpan element of the most recently added item
70028 ** on the expression list.
70029 **
70030 ** pList might be NULL following an OOM error.  But pSpan should never be
70031 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
70032 ** is set.
70033 */
70034 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
70035   Parse *pParse,          /* Parsing context */
70036   ExprList *pList,        /* List to which to add the span. */
70037   ExprSpan *pSpan         /* The span to be added */
70038 ){
70039   sqlite3 *db = pParse->db;
70040   assert( pList!=0 || db->mallocFailed!=0 );
70041   if( pList ){
70042     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
70043     assert( pList->nExpr>0 );
70044     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
70045     sqlite3DbFree(db, pItem->zSpan);
70046     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
70047                                     (int)(pSpan->zEnd - pSpan->zStart));
70048   }
70049 }
70050
70051 /*
70052 ** If the expression list pEList contains more than iLimit elements,
70053 ** leave an error message in pParse.
70054 */
70055 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
70056   Parse *pParse,
70057   ExprList *pEList,
70058   const char *zObject
70059 ){
70060   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
70061   testcase( pEList && pEList->nExpr==mx );
70062   testcase( pEList && pEList->nExpr==mx+1 );
70063   if( pEList && pEList->nExpr>mx ){
70064     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
70065   }
70066 }
70067
70068 /*
70069 ** Delete an entire expression list.
70070 */
70071 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
70072   int i;
70073   struct ExprList_item *pItem;
70074   if( pList==0 ) return;
70075   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
70076   assert( pList->nExpr<=pList->nAlloc );
70077   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
70078     sqlite3ExprDelete(db, pItem->pExpr);
70079     sqlite3DbFree(db, pItem->zName);
70080     sqlite3DbFree(db, pItem->zSpan);
70081   }
70082   sqlite3DbFree(db, pList->a);
70083   sqlite3DbFree(db, pList);
70084 }
70085
70086 /*
70087 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
70088 ** to an integer.  These routines are checking an expression to see
70089 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
70090 ** not constant.
70091 **
70092 ** These callback routines are used to implement the following:
70093 **
70094 **     sqlite3ExprIsConstant()
70095 **     sqlite3ExprIsConstantNotJoin()
70096 **     sqlite3ExprIsConstantOrFunction()
70097 **
70098 */
70099 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
70100
70101   /* If pWalker->u.i is 3 then any term of the expression that comes from
70102   ** the ON or USING clauses of a join disqualifies the expression
70103   ** from being considered constant. */
70104   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
70105     pWalker->u.i = 0;
70106     return WRC_Abort;
70107   }
70108
70109   switch( pExpr->op ){
70110     /* Consider functions to be constant if all their arguments are constant
70111     ** and pWalker->u.i==2 */
70112     case TK_FUNCTION:
70113       if( pWalker->u.i==2 ) return 0;
70114       /* Fall through */
70115     case TK_ID:
70116     case TK_COLUMN:
70117     case TK_AGG_FUNCTION:
70118     case TK_AGG_COLUMN:
70119       testcase( pExpr->op==TK_ID );
70120       testcase( pExpr->op==TK_COLUMN );
70121       testcase( pExpr->op==TK_AGG_FUNCTION );
70122       testcase( pExpr->op==TK_AGG_COLUMN );
70123       pWalker->u.i = 0;
70124       return WRC_Abort;
70125     default:
70126       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
70127       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
70128       return WRC_Continue;
70129   }
70130 }
70131 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
70132   UNUSED_PARAMETER(NotUsed);
70133   pWalker->u.i = 0;
70134   return WRC_Abort;
70135 }
70136 static int exprIsConst(Expr *p, int initFlag){
70137   Walker w;
70138   w.u.i = initFlag;
70139   w.xExprCallback = exprNodeIsConstant;
70140   w.xSelectCallback = selectNodeIsConstant;
70141   sqlite3WalkExpr(&w, p);
70142   return w.u.i;
70143 }
70144
70145 /*
70146 ** Walk an expression tree.  Return 1 if the expression is constant
70147 ** and 0 if it involves variables or function calls.
70148 **
70149 ** For the purposes of this function, a double-quoted string (ex: "abc")
70150 ** is considered a variable but a single-quoted string (ex: 'abc') is
70151 ** a constant.
70152 */
70153 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
70154   return exprIsConst(p, 1);
70155 }
70156
70157 /*
70158 ** Walk an expression tree.  Return 1 if the expression is constant
70159 ** that does no originate from the ON or USING clauses of a join.
70160 ** Return 0 if it involves variables or function calls or terms from
70161 ** an ON or USING clause.
70162 */
70163 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
70164   return exprIsConst(p, 3);
70165 }
70166
70167 /*
70168 ** Walk an expression tree.  Return 1 if the expression is constant
70169 ** or a function call with constant arguments.  Return and 0 if there
70170 ** are any variables.
70171 **
70172 ** For the purposes of this function, a double-quoted string (ex: "abc")
70173 ** is considered a variable but a single-quoted string (ex: 'abc') is
70174 ** a constant.
70175 */
70176 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
70177   return exprIsConst(p, 2);
70178 }
70179
70180 /*
70181 ** If the expression p codes a constant integer that is small enough
70182 ** to fit in a 32-bit integer, return 1 and put the value of the integer
70183 ** in *pValue.  If the expression is not an integer or if it is too big
70184 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
70185 */
70186 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
70187   int rc = 0;
70188   if( p->flags & EP_IntValue ){
70189     *pValue = p->u.iValue;
70190     return 1;
70191   }
70192   switch( p->op ){
70193     case TK_INTEGER: {
70194       rc = sqlite3GetInt32(p->u.zToken, pValue);
70195       assert( rc==0 );
70196       break;
70197     }
70198     case TK_UPLUS: {
70199       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
70200       break;
70201     }
70202     case TK_UMINUS: {
70203       int v;
70204       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
70205         *pValue = -v;
70206         rc = 1;
70207       }
70208       break;
70209     }
70210     default: break;
70211   }
70212   if( rc ){
70213     assert( ExprHasAnyProperty(p, EP_Reduced|EP_TokenOnly)
70214                || (p->flags2 & EP2_MallocedToken)==0 );
70215     p->op = TK_INTEGER;
70216     p->flags |= EP_IntValue;
70217     p->u.iValue = *pValue;
70218   }
70219   return rc;
70220 }
70221
70222 /*
70223 ** Return FALSE if there is no chance that the expression can be NULL.
70224 **
70225 ** If the expression might be NULL or if the expression is too complex
70226 ** to tell return TRUE.  
70227 **
70228 ** This routine is used as an optimization, to skip OP_IsNull opcodes
70229 ** when we know that a value cannot be NULL.  Hence, a false positive
70230 ** (returning TRUE when in fact the expression can never be NULL) might
70231 ** be a small performance hit but is otherwise harmless.  On the other
70232 ** hand, a false negative (returning FALSE when the result could be NULL)
70233 ** will likely result in an incorrect answer.  So when in doubt, return
70234 ** TRUE.
70235 */
70236 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
70237   u8 op;
70238   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
70239   op = p->op;
70240   if( op==TK_REGISTER ) op = p->op2;
70241   switch( op ){
70242     case TK_INTEGER:
70243     case TK_STRING:
70244     case TK_FLOAT:
70245     case TK_BLOB:
70246       return 0;
70247     default:
70248       return 1;
70249   }
70250 }
70251
70252 /*
70253 ** Generate an OP_IsNull instruction that tests register iReg and jumps
70254 ** to location iDest if the value in iReg is NULL.  The value in iReg 
70255 ** was computed by pExpr.  If we can look at pExpr at compile-time and
70256 ** determine that it can never generate a NULL, then the OP_IsNull operation
70257 ** can be omitted.
70258 */
70259 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
70260   Vdbe *v,            /* The VDBE under construction */
70261   const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
70262   int iReg,           /* Test the value in this register for NULL */
70263   int iDest           /* Jump here if the value is null */
70264 ){
70265   if( sqlite3ExprCanBeNull(pExpr) ){
70266     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
70267   }
70268 }
70269
70270 /*
70271 ** Return TRUE if the given expression is a constant which would be
70272 ** unchanged by OP_Affinity with the affinity given in the second
70273 ** argument.
70274 **
70275 ** This routine is used to determine if the OP_Affinity operation
70276 ** can be omitted.  When in doubt return FALSE.  A false negative
70277 ** is harmless.  A false positive, however, can result in the wrong
70278 ** answer.
70279 */
70280 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
70281   u8 op;
70282   if( aff==SQLITE_AFF_NONE ) return 1;
70283   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
70284   op = p->op;
70285   if( op==TK_REGISTER ) op = p->op2;
70286   switch( op ){
70287     case TK_INTEGER: {
70288       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
70289     }
70290     case TK_FLOAT: {
70291       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
70292     }
70293     case TK_STRING: {
70294       return aff==SQLITE_AFF_TEXT;
70295     }
70296     case TK_BLOB: {
70297       return 1;
70298     }
70299     case TK_COLUMN: {
70300       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
70301       return p->iColumn<0
70302           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
70303     }
70304     default: {
70305       return 0;
70306     }
70307   }
70308 }
70309
70310 /*
70311 ** Return TRUE if the given string is a row-id column name.
70312 */
70313 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
70314   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
70315   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
70316   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
70317   return 0;
70318 }
70319
70320 /*
70321 ** Return true if we are able to the IN operator optimization on a
70322 ** query of the form
70323 **
70324 **       x IN (SELECT ...)
70325 **
70326 ** Where the SELECT... clause is as specified by the parameter to this
70327 ** routine.
70328 **
70329 ** The Select object passed in has already been preprocessed and no
70330 ** errors have been found.
70331 */
70332 #ifndef SQLITE_OMIT_SUBQUERY
70333 static int isCandidateForInOpt(Select *p){
70334   SrcList *pSrc;
70335   ExprList *pEList;
70336   Table *pTab;
70337   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
70338   if( p->pPrior ) return 0;              /* Not a compound SELECT */
70339   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
70340     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
70341     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
70342     return 0; /* No DISTINCT keyword and no aggregate functions */
70343   }
70344   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
70345   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
70346   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
70347   if( p->pWhere ) return 0;              /* Has no WHERE clause */
70348   pSrc = p->pSrc;
70349   assert( pSrc!=0 );
70350   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
70351   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
70352   pTab = pSrc->a[0].pTab;
70353   if( NEVER(pTab==0) ) return 0;
70354   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
70355   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
70356   pEList = p->pEList;
70357   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
70358   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
70359   return 1;
70360 }
70361 #endif /* SQLITE_OMIT_SUBQUERY */
70362
70363 /*
70364 ** This function is used by the implementation of the IN (...) operator.
70365 ** It's job is to find or create a b-tree structure that may be used
70366 ** either to test for membership of the (...) set or to iterate through
70367 ** its members, skipping duplicates.
70368 **
70369 ** The index of the cursor opened on the b-tree (database table, database index 
70370 ** or ephermal table) is stored in pX->iTable before this function returns.
70371 ** The returned value of this function indicates the b-tree type, as follows:
70372 **
70373 **   IN_INDEX_ROWID - The cursor was opened on a database table.
70374 **   IN_INDEX_INDEX - The cursor was opened on a database index.
70375 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
70376 **                    populated epheremal table.
70377 **
70378 ** An existing b-tree may only be used if the SELECT is of the simple
70379 ** form:
70380 **
70381 **     SELECT <column> FROM <table>
70382 **
70383 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
70384 ** through the set members, skipping any duplicates. In this case an
70385 ** epheremal table must be used unless the selected <column> is guaranteed
70386 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
70387 ** has a UNIQUE constraint or UNIQUE index.
70388 **
70389 ** If the prNotFound parameter is not 0, then the b-tree will be used 
70390 ** for fast set membership tests. In this case an epheremal table must 
70391 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
70392 ** be found with <column> as its left-most column.
70393 **
70394 ** When the b-tree is being used for membership tests, the calling function
70395 ** needs to know whether or not the structure contains an SQL NULL 
70396 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
70397 ** If there is any chance that the (...) might contain a NULL value at
70398 ** runtime, then a register is allocated and the register number written
70399 ** to *prNotFound. If there is no chance that the (...) contains a
70400 ** NULL value, then *prNotFound is left unchanged.
70401 **
70402 ** If a register is allocated and its location stored in *prNotFound, then
70403 ** its initial value is NULL.  If the (...) does not remain constant
70404 ** for the duration of the query (i.e. the SELECT within the (...)
70405 ** is a correlated subquery) then the value of the allocated register is
70406 ** reset to NULL each time the subquery is rerun. This allows the
70407 ** caller to use vdbe code equivalent to the following:
70408 **
70409 **   if( register==NULL ){
70410 **     has_null = <test if data structure contains null>
70411 **     register = 1
70412 **   }
70413 **
70414 ** in order to avoid running the <test if data structure contains null>
70415 ** test more often than is necessary.
70416 */
70417 #ifndef SQLITE_OMIT_SUBQUERY
70418 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
70419   Select *p;                            /* SELECT to the right of IN operator */
70420   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
70421   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
70422   int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
70423
70424   assert( pX->op==TK_IN );
70425
70426   /* Check to see if an existing table or index can be used to
70427   ** satisfy the query.  This is preferable to generating a new 
70428   ** ephemeral table.
70429   */
70430   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
70431   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
70432     sqlite3 *db = pParse->db;              /* Database connection */
70433     Expr *pExpr = p->pEList->a[0].pExpr;   /* Expression <column> */
70434     int iCol = pExpr->iColumn;             /* Index of column <column> */
70435     Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
70436     Table *pTab = p->pSrc->a[0].pTab;      /* Table <table>. */
70437     int iDb;                               /* Database idx for pTab */
70438    
70439     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
70440     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
70441     sqlite3CodeVerifySchema(pParse, iDb);
70442     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
70443
70444     /* This function is only called from two places. In both cases the vdbe
70445     ** has already been allocated. So assume sqlite3GetVdbe() is always
70446     ** successful here.
70447     */
70448     assert(v);
70449     if( iCol<0 ){
70450       int iMem = ++pParse->nMem;
70451       int iAddr;
70452
70453       iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
70454       sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
70455
70456       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
70457       eType = IN_INDEX_ROWID;
70458
70459       sqlite3VdbeJumpHere(v, iAddr);
70460     }else{
70461       Index *pIdx;                         /* Iterator variable */
70462
70463       /* The collation sequence used by the comparison. If an index is to
70464       ** be used in place of a temp-table, it must be ordered according
70465       ** to this collation sequence.  */
70466       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
70467
70468       /* Check that the affinity that will be used to perform the 
70469       ** comparison is the same as the affinity of the column. If
70470       ** it is not, it is not possible to use any index.
70471       */
70472       char aff = comparisonAffinity(pX);
70473       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
70474
70475       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
70476         if( (pIdx->aiColumn[0]==iCol)
70477          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
70478          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
70479         ){
70480           int iMem = ++pParse->nMem;
70481           int iAddr;
70482           char *pKey;
70483   
70484           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
70485           iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
70486           sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
70487   
70488           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
70489                                pKey,P4_KEYINFO_HANDOFF);
70490           VdbeComment((v, "%s", pIdx->zName));
70491           eType = IN_INDEX_INDEX;
70492
70493           sqlite3VdbeJumpHere(v, iAddr);
70494           if( prNotFound && !pTab->aCol[iCol].notNull ){
70495             *prNotFound = ++pParse->nMem;
70496           }
70497         }
70498       }
70499     }
70500   }
70501
70502   if( eType==0 ){
70503     /* Could not found an existing table or index to use as the RHS b-tree.
70504     ** We will have to generate an ephemeral table to do the job.
70505     */
70506     double savedNQueryLoop = pParse->nQueryLoop;
70507     int rMayHaveNull = 0;
70508     eType = IN_INDEX_EPH;
70509     if( prNotFound ){
70510       *prNotFound = rMayHaveNull = ++pParse->nMem;
70511     }else{
70512       testcase( pParse->nQueryLoop>(double)1 );
70513       pParse->nQueryLoop = (double)1;
70514       if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
70515         eType = IN_INDEX_ROWID;
70516       }
70517     }
70518     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
70519     pParse->nQueryLoop = savedNQueryLoop;
70520   }else{
70521     pX->iTable = iTab;
70522   }
70523   return eType;
70524 }
70525 #endif
70526
70527 /*
70528 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
70529 ** or IN operators.  Examples:
70530 **
70531 **     (SELECT a FROM b)          -- subquery
70532 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
70533 **     x IN (4,5,11)              -- IN operator with list on right-hand side
70534 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
70535 **
70536 ** The pExpr parameter describes the expression that contains the IN
70537 ** operator or subquery.
70538 **
70539 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
70540 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
70541 ** to some integer key column of a table B-Tree. In this case, use an
70542 ** intkey B-Tree to store the set of IN(...) values instead of the usual
70543 ** (slower) variable length keys B-Tree.
70544 **
70545 ** If rMayHaveNull is non-zero, that means that the operation is an IN
70546 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
70547 ** Furthermore, the IN is in a WHERE clause and that we really want
70548 ** to iterate over the RHS of the IN operator in order to quickly locate
70549 ** all corresponding LHS elements.  All this routine does is initialize
70550 ** the register given by rMayHaveNull to NULL.  Calling routines will take
70551 ** care of changing this register value to non-NULL if the RHS is NULL-free.
70552 **
70553 ** If rMayHaveNull is zero, that means that the subquery is being used
70554 ** for membership testing only.  There is no need to initialize any
70555 ** registers to indicate the presense or absence of NULLs on the RHS.
70556 **
70557 ** For a SELECT or EXISTS operator, return the register that holds the
70558 ** result.  For IN operators or if an error occurs, the return value is 0.
70559 */
70560 #ifndef SQLITE_OMIT_SUBQUERY
70561 SQLITE_PRIVATE int sqlite3CodeSubselect(
70562   Parse *pParse,          /* Parsing context */
70563   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
70564   int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
70565   int isRowid             /* If true, LHS of IN operator is a rowid */
70566 ){
70567   int testAddr = 0;                       /* One-time test address */
70568   int rReg = 0;                           /* Register storing resulting */
70569   Vdbe *v = sqlite3GetVdbe(pParse);
70570   if( NEVER(v==0) ) return 0;
70571   sqlite3ExprCachePush(pParse);
70572
70573   /* This code must be run in its entirety every time it is encountered
70574   ** if any of the following is true:
70575   **
70576   **    *  The right-hand side is a correlated subquery
70577   **    *  The right-hand side is an expression list containing variables
70578   **    *  We are inside a trigger
70579   **
70580   ** If all of the above are false, then we can run this code just once
70581   ** save the results, and reuse the same result on subsequent invocations.
70582   */
70583   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
70584     int mem = ++pParse->nMem;
70585     sqlite3VdbeAddOp1(v, OP_If, mem);
70586     testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
70587     assert( testAddr>0 || pParse->db->mallocFailed );
70588   }
70589
70590 #ifndef SQLITE_OMIT_EXPLAIN
70591   if( pParse->explain==2 ){
70592     char *zMsg = sqlite3MPrintf(
70593         pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr?"":"CORRELATED ",
70594         pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
70595     );
70596     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
70597   }
70598 #endif
70599
70600   switch( pExpr->op ){
70601     case TK_IN: {
70602       char affinity;              /* Affinity of the LHS of the IN */
70603       KeyInfo keyInfo;            /* Keyinfo for the generated table */
70604       int addr;                   /* Address of OP_OpenEphemeral instruction */
70605       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
70606
70607       if( rMayHaveNull ){
70608         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
70609       }
70610
70611       affinity = sqlite3ExprAffinity(pLeft);
70612
70613       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
70614       ** expression it is handled the same way.  An ephemeral table is 
70615       ** filled with single-field index keys representing the results
70616       ** from the SELECT or the <exprlist>.
70617       **
70618       ** If the 'x' expression is a column value, or the SELECT...
70619       ** statement returns a column value, then the affinity of that
70620       ** column is used to build the index keys. If both 'x' and the
70621       ** SELECT... statement are columns, then numeric affinity is used
70622       ** if either column has NUMERIC or INTEGER affinity. If neither
70623       ** 'x' nor the SELECT... statement are columns, then numeric affinity
70624       ** is used.
70625       */
70626       pExpr->iTable = pParse->nTab++;
70627       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
70628       if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
70629       memset(&keyInfo, 0, sizeof(keyInfo));
70630       keyInfo.nField = 1;
70631
70632       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
70633         /* Case 1:     expr IN (SELECT ...)
70634         **
70635         ** Generate code to write the results of the select into the temporary
70636         ** table allocated and opened above.
70637         */
70638         SelectDest dest;
70639         ExprList *pEList;
70640
70641         assert( !isRowid );
70642         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
70643         dest.affinity = (u8)affinity;
70644         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
70645         pExpr->x.pSelect->iLimit = 0;
70646         if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
70647           return 0;
70648         }
70649         pEList = pExpr->x.pSelect->pEList;
70650         if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){ 
70651           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
70652               pEList->a[0].pExpr);
70653         }
70654       }else if( ALWAYS(pExpr->x.pList!=0) ){
70655         /* Case 2:     expr IN (exprlist)
70656         **
70657         ** For each expression, build an index key from the evaluation and
70658         ** store it in the temporary table. If <expr> is a column, then use
70659         ** that columns affinity when building index keys. If <expr> is not
70660         ** a column, use numeric affinity.
70661         */
70662         int i;
70663         ExprList *pList = pExpr->x.pList;
70664         struct ExprList_item *pItem;
70665         int r1, r2, r3;
70666
70667         if( !affinity ){
70668           affinity = SQLITE_AFF_NONE;
70669         }
70670         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
70671
70672         /* Loop through each expression in <exprlist>. */
70673         r1 = sqlite3GetTempReg(pParse);
70674         r2 = sqlite3GetTempReg(pParse);
70675         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
70676         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
70677           Expr *pE2 = pItem->pExpr;
70678           int iValToIns;
70679
70680           /* If the expression is not constant then we will need to
70681           ** disable the test that was generated above that makes sure
70682           ** this code only executes once.  Because for a non-constant
70683           ** expression we need to rerun this code each time.
70684           */
70685           if( testAddr && !sqlite3ExprIsConstant(pE2) ){
70686             sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
70687             testAddr = 0;
70688           }
70689
70690           /* Evaluate the expression and insert it into the temp table */
70691           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
70692             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
70693           }else{
70694             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
70695             if( isRowid ){
70696               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
70697                                 sqlite3VdbeCurrentAddr(v)+2);
70698               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
70699             }else{
70700               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
70701               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
70702               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
70703             }
70704           }
70705         }
70706         sqlite3ReleaseTempReg(pParse, r1);
70707         sqlite3ReleaseTempReg(pParse, r2);
70708       }
70709       if( !isRowid ){
70710         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
70711       }
70712       break;
70713     }
70714
70715     case TK_EXISTS:
70716     case TK_SELECT:
70717     default: {
70718       /* If this has to be a scalar SELECT.  Generate code to put the
70719       ** value of this select in a memory cell and record the number
70720       ** of the memory cell in iColumn.  If this is an EXISTS, write
70721       ** an integer 0 (not exists) or 1 (exists) into a memory cell
70722       ** and record that memory cell in iColumn.
70723       */
70724       Select *pSel;                         /* SELECT statement to encode */
70725       SelectDest dest;                      /* How to deal with SELECt result */
70726
70727       testcase( pExpr->op==TK_EXISTS );
70728       testcase( pExpr->op==TK_SELECT );
70729       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
70730
70731       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
70732       pSel = pExpr->x.pSelect;
70733       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
70734       if( pExpr->op==TK_SELECT ){
70735         dest.eDest = SRT_Mem;
70736         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
70737         VdbeComment((v, "Init subquery result"));
70738       }else{
70739         dest.eDest = SRT_Exists;
70740         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
70741         VdbeComment((v, "Init EXISTS result"));
70742       }
70743       sqlite3ExprDelete(pParse->db, pSel->pLimit);
70744       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
70745                                   &sqlite3IntTokens[1]);
70746       pSel->iLimit = 0;
70747       if( sqlite3Select(pParse, pSel, &dest) ){
70748         return 0;
70749       }
70750       rReg = dest.iParm;
70751       ExprSetIrreducible(pExpr);
70752       break;
70753     }
70754   }
70755
70756   if( testAddr ){
70757     sqlite3VdbeJumpHere(v, testAddr-1);
70758   }
70759   sqlite3ExprCachePop(pParse, 1);
70760
70761   return rReg;
70762 }
70763 #endif /* SQLITE_OMIT_SUBQUERY */
70764
70765 #ifndef SQLITE_OMIT_SUBQUERY
70766 /*
70767 ** Generate code for an IN expression.
70768 **
70769 **      x IN (SELECT ...)
70770 **      x IN (value, value, ...)
70771 **
70772 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
70773 ** is an array of zero or more values.  The expression is true if the LHS is
70774 ** contained within the RHS.  The value of the expression is unknown (NULL)
70775 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
70776 ** RHS contains one or more NULL values.
70777 **
70778 ** This routine generates code will jump to destIfFalse if the LHS is not 
70779 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
70780 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
70781 ** within the RHS then fall through.
70782 */
70783 static void sqlite3ExprCodeIN(
70784   Parse *pParse,        /* Parsing and code generating context */
70785   Expr *pExpr,          /* The IN expression */
70786   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
70787   int destIfNull        /* Jump here if the results are unknown due to NULLs */
70788 ){
70789   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
70790   char affinity;        /* Comparison affinity to use */
70791   int eType;            /* Type of the RHS */
70792   int r1;               /* Temporary use register */
70793   Vdbe *v;              /* Statement under construction */
70794
70795   /* Compute the RHS.   After this step, the table with cursor
70796   ** pExpr->iTable will contains the values that make up the RHS.
70797   */
70798   v = pParse->pVdbe;
70799   assert( v!=0 );       /* OOM detected prior to this routine */
70800   VdbeNoopComment((v, "begin IN expr"));
70801   eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
70802
70803   /* Figure out the affinity to use to create a key from the results
70804   ** of the expression. affinityStr stores a static string suitable for
70805   ** P4 of OP_MakeRecord.
70806   */
70807   affinity = comparisonAffinity(pExpr);
70808
70809   /* Code the LHS, the <expr> from "<expr> IN (...)".
70810   */
70811   sqlite3ExprCachePush(pParse);
70812   r1 = sqlite3GetTempReg(pParse);
70813   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
70814
70815   /* If the LHS is NULL, then the result is either false or NULL depending
70816   ** on whether the RHS is empty or not, respectively.
70817   */
70818   if( destIfNull==destIfFalse ){
70819     /* Shortcut for the common case where the false and NULL outcomes are
70820     ** the same. */
70821     sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
70822   }else{
70823     int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
70824     sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
70825     sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
70826     sqlite3VdbeJumpHere(v, addr1);
70827   }
70828
70829   if( eType==IN_INDEX_ROWID ){
70830     /* In this case, the RHS is the ROWID of table b-tree
70831     */
70832     sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
70833     sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
70834   }else{
70835     /* In this case, the RHS is an index b-tree.
70836     */
70837     sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
70838
70839     /* If the set membership test fails, then the result of the 
70840     ** "x IN (...)" expression must be either 0 or NULL. If the set
70841     ** contains no NULL values, then the result is 0. If the set 
70842     ** contains one or more NULL values, then the result of the
70843     ** expression is also NULL.
70844     */
70845     if( rRhsHasNull==0 || destIfFalse==destIfNull ){
70846       /* This branch runs if it is known at compile time that the RHS
70847       ** cannot contain NULL values. This happens as the result
70848       ** of a "NOT NULL" constraint in the database schema.
70849       **
70850       ** Also run this branch if NULL is equivalent to FALSE
70851       ** for this particular IN operator.
70852       */
70853       sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
70854
70855     }else{
70856       /* In this branch, the RHS of the IN might contain a NULL and
70857       ** the presence of a NULL on the RHS makes a difference in the
70858       ** outcome.
70859       */
70860       int j1, j2, j3;
70861
70862       /* First check to see if the LHS is contained in the RHS.  If so,
70863       ** then the presence of NULLs in the RHS does not matter, so jump
70864       ** over all of the code that follows.
70865       */
70866       j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
70867
70868       /* Here we begin generating code that runs if the LHS is not
70869       ** contained within the RHS.  Generate additional code that
70870       ** tests the RHS for NULLs.  If the RHS contains a NULL then
70871       ** jump to destIfNull.  If there are no NULLs in the RHS then
70872       ** jump to destIfFalse.
70873       */
70874       j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
70875       j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
70876       sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
70877       sqlite3VdbeJumpHere(v, j3);
70878       sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
70879       sqlite3VdbeJumpHere(v, j2);
70880
70881       /* Jump to the appropriate target depending on whether or not
70882       ** the RHS contains a NULL
70883       */
70884       sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
70885       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
70886
70887       /* The OP_Found at the top of this branch jumps here when true, 
70888       ** causing the overall IN expression evaluation to fall through.
70889       */
70890       sqlite3VdbeJumpHere(v, j1);
70891     }
70892   }
70893   sqlite3ReleaseTempReg(pParse, r1);
70894   sqlite3ExprCachePop(pParse, 1);
70895   VdbeComment((v, "end IN expr"));
70896 }
70897 #endif /* SQLITE_OMIT_SUBQUERY */
70898
70899 /*
70900 ** Duplicate an 8-byte value
70901 */
70902 static char *dup8bytes(Vdbe *v, const char *in){
70903   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
70904   if( out ){
70905     memcpy(out, in, 8);
70906   }
70907   return out;
70908 }
70909
70910 #ifndef SQLITE_OMIT_FLOATING_POINT
70911 /*
70912 ** Generate an instruction that will put the floating point
70913 ** value described by z[0..n-1] into register iMem.
70914 **
70915 ** The z[] string will probably not be zero-terminated.  But the 
70916 ** z[n] character is guaranteed to be something that does not look
70917 ** like the continuation of the number.
70918 */
70919 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
70920   if( ALWAYS(z!=0) ){
70921     double value;
70922     char *zV;
70923     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
70924     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
70925     if( negateFlag ) value = -value;
70926     zV = dup8bytes(v, (char*)&value);
70927     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
70928   }
70929 }
70930 #endif
70931
70932
70933 /*
70934 ** Generate an instruction that will put the integer describe by
70935 ** text z[0..n-1] into register iMem.
70936 **
70937 ** Expr.u.zToken is always UTF8 and zero-terminated.
70938 */
70939 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
70940   Vdbe *v = pParse->pVdbe;
70941   if( pExpr->flags & EP_IntValue ){
70942     int i = pExpr->u.iValue;
70943     if( negFlag ) i = -i;
70944     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
70945   }else{
70946     int c;
70947     i64 value;
70948     const char *z = pExpr->u.zToken;
70949     assert( z!=0 );
70950     c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
70951     if( c==0 || (c==2 && negFlag) ){
70952       char *zV;
70953       if( negFlag ){ value = -value; }
70954       zV = dup8bytes(v, (char*)&value);
70955       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
70956     }else{
70957 #ifdef SQLITE_OMIT_FLOATING_POINT
70958       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
70959 #else
70960       codeReal(v, z, negFlag, iMem);
70961 #endif
70962     }
70963   }
70964 }
70965
70966 /*
70967 ** Clear a cache entry.
70968 */
70969 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
70970   if( p->tempReg ){
70971     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
70972       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
70973     }
70974     p->tempReg = 0;
70975   }
70976 }
70977
70978
70979 /*
70980 ** Record in the column cache that a particular column from a
70981 ** particular table is stored in a particular register.
70982 */
70983 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
70984   int i;
70985   int minLru;
70986   int idxLru;
70987   struct yColCache *p;
70988
70989   assert( iReg>0 );  /* Register numbers are always positive */
70990   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
70991
70992   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
70993   ** for testing only - to verify that SQLite always gets the same answer
70994   ** with and without the column cache.
70995   */
70996   if( pParse->db->flags & SQLITE_ColumnCache ) return;
70997
70998   /* First replace any existing entry.
70999   **
71000   ** Actually, the way the column cache is currently used, we are guaranteed
71001   ** that the object will never already be in cache.  Verify this guarantee.
71002   */
71003 #ifndef NDEBUG
71004   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
71005 #if 0 /* This code wold remove the entry from the cache if it existed */
71006     if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
71007       cacheEntryClear(pParse, p);
71008       p->iLevel = pParse->iCacheLevel;
71009       p->iReg = iReg;
71010       p->lru = pParse->iCacheCnt++;
71011       return;
71012     }
71013 #endif
71014     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
71015   }
71016 #endif
71017
71018   /* Find an empty slot and replace it */
71019   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
71020     if( p->iReg==0 ){
71021       p->iLevel = pParse->iCacheLevel;
71022       p->iTable = iTab;
71023       p->iColumn = iCol;
71024       p->iReg = iReg;
71025       p->tempReg = 0;
71026       p->lru = pParse->iCacheCnt++;
71027       return;
71028     }
71029   }
71030
71031   /* Replace the last recently used */
71032   minLru = 0x7fffffff;
71033   idxLru = -1;
71034   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
71035     if( p->lru<minLru ){
71036       idxLru = i;
71037       minLru = p->lru;
71038     }
71039   }
71040   if( ALWAYS(idxLru>=0) ){
71041     p = &pParse->aColCache[idxLru];
71042     p->iLevel = pParse->iCacheLevel;
71043     p->iTable = iTab;
71044     p->iColumn = iCol;
71045     p->iReg = iReg;
71046     p->tempReg = 0;
71047     p->lru = pParse->iCacheCnt++;
71048     return;
71049   }
71050 }
71051
71052 /*
71053 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
71054 ** Purge the range of registers from the column cache.
71055 */
71056 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
71057   int i;
71058   int iLast = iReg + nReg - 1;
71059   struct yColCache *p;
71060   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
71061     int r = p->iReg;
71062     if( r>=iReg && r<=iLast ){
71063       cacheEntryClear(pParse, p);
71064       p->iReg = 0;
71065     }
71066   }
71067 }
71068
71069 /*
71070 ** Remember the current column cache context.  Any new entries added
71071 ** added to the column cache after this call are removed when the
71072 ** corresponding pop occurs.
71073 */
71074 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
71075   pParse->iCacheLevel++;
71076 }
71077
71078 /*
71079 ** Remove from the column cache any entries that were added since the
71080 ** the previous N Push operations.  In other words, restore the cache
71081 ** to the state it was in N Pushes ago.
71082 */
71083 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
71084   int i;
71085   struct yColCache *p;
71086   assert( N>0 );
71087   assert( pParse->iCacheLevel>=N );
71088   pParse->iCacheLevel -= N;
71089   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
71090     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
71091       cacheEntryClear(pParse, p);
71092       p->iReg = 0;
71093     }
71094   }
71095 }
71096
71097 /*
71098 ** When a cached column is reused, make sure that its register is
71099 ** no longer available as a temp register.  ticket #3879:  that same
71100 ** register might be in the cache in multiple places, so be sure to
71101 ** get them all.
71102 */
71103 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
71104   int i;
71105   struct yColCache *p;
71106   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
71107     if( p->iReg==iReg ){
71108       p->tempReg = 0;
71109     }
71110   }
71111 }
71112
71113 /*
71114 ** Generate code to extract the value of the iCol-th column of a table.
71115 */
71116 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
71117   Vdbe *v,        /* The VDBE under construction */
71118   Table *pTab,    /* The table containing the value */
71119   int iTabCur,    /* The cursor for this table */
71120   int iCol,       /* Index of the column to extract */
71121   int regOut      /* Extract the valud into this register */
71122 ){
71123   if( iCol<0 || iCol==pTab->iPKey ){
71124     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
71125   }else{
71126     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
71127     sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
71128   }
71129   if( iCol>=0 ){
71130     sqlite3ColumnDefault(v, pTab, iCol, regOut);
71131   }
71132 }
71133
71134 /*
71135 ** Generate code that will extract the iColumn-th column from
71136 ** table pTab and store the column value in a register.  An effort
71137 ** is made to store the column value in register iReg, but this is
71138 ** not guaranteed.  The location of the column value is returned.
71139 **
71140 ** There must be an open cursor to pTab in iTable when this routine
71141 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
71142 */
71143 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
71144   Parse *pParse,   /* Parsing and code generating context */
71145   Table *pTab,     /* Description of the table we are reading from */
71146   int iColumn,     /* Index of the table column */
71147   int iTable,      /* The cursor pointing to the table */
71148   int iReg         /* Store results here */
71149 ){
71150   Vdbe *v = pParse->pVdbe;
71151   int i;
71152   struct yColCache *p;
71153
71154   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
71155     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
71156       p->lru = pParse->iCacheCnt++;
71157       sqlite3ExprCachePinRegister(pParse, p->iReg);
71158       return p->iReg;
71159     }
71160   }  
71161   assert( v!=0 );
71162   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
71163   sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
71164   return iReg;
71165 }
71166
71167 /*
71168 ** Clear all column cache entries.
71169 */
71170 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
71171   int i;
71172   struct yColCache *p;
71173
71174   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
71175     if( p->iReg ){
71176       cacheEntryClear(pParse, p);
71177       p->iReg = 0;
71178     }
71179   }
71180 }
71181
71182 /*
71183 ** Record the fact that an affinity change has occurred on iCount
71184 ** registers starting with iStart.
71185 */
71186 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
71187   sqlite3ExprCacheRemove(pParse, iStart, iCount);
71188 }
71189
71190 /*
71191 ** Generate code to move content from registers iFrom...iFrom+nReg-1
71192 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
71193 */
71194 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
71195   int i;
71196   struct yColCache *p;
71197   if( NEVER(iFrom==iTo) ) return;
71198   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
71199   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
71200     int x = p->iReg;
71201     if( x>=iFrom && x<iFrom+nReg ){
71202       p->iReg += iTo-iFrom;
71203     }
71204   }
71205 }
71206
71207 /*
71208 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
71209 ** over to iTo..iTo+nReg-1.
71210 */
71211 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
71212   int i;
71213   if( NEVER(iFrom==iTo) ) return;
71214   for(i=0; i<nReg; i++){
71215     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
71216   }
71217 }
71218
71219 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
71220 /*
71221 ** Return true if any register in the range iFrom..iTo (inclusive)
71222 ** is used as part of the column cache.
71223 **
71224 ** This routine is used within assert() and testcase() macros only
71225 ** and does not appear in a normal build.
71226 */
71227 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
71228   int i;
71229   struct yColCache *p;
71230   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
71231     int r = p->iReg;
71232     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
71233   }
71234   return 0;
71235 }
71236 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
71237
71238 /*
71239 ** Generate code into the current Vdbe to evaluate the given
71240 ** expression.  Attempt to store the results in register "target".
71241 ** Return the register where results are stored.
71242 **
71243 ** With this routine, there is no guarantee that results will
71244 ** be stored in target.  The result might be stored in some other
71245 ** register if it is convenient to do so.  The calling function
71246 ** must check the return code and move the results to the desired
71247 ** register.
71248 */
71249 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
71250   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
71251   int op;                   /* The opcode being coded */
71252   int inReg = target;       /* Results stored in register inReg */
71253   int regFree1 = 0;         /* If non-zero free this temporary register */
71254   int regFree2 = 0;         /* If non-zero free this temporary register */
71255   int r1, r2, r3, r4;       /* Various register numbers */
71256   sqlite3 *db = pParse->db; /* The database connection */
71257
71258   assert( target>0 && target<=pParse->nMem );
71259   if( v==0 ){
71260     assert( pParse->db->mallocFailed );
71261     return 0;
71262   }
71263
71264   if( pExpr==0 ){
71265     op = TK_NULL;
71266   }else{
71267     op = pExpr->op;
71268   }
71269   switch( op ){
71270     case TK_AGG_COLUMN: {
71271       AggInfo *pAggInfo = pExpr->pAggInfo;
71272       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
71273       if( !pAggInfo->directMode ){
71274         assert( pCol->iMem>0 );
71275         inReg = pCol->iMem;
71276         break;
71277       }else if( pAggInfo->useSortingIdx ){
71278         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
71279                               pCol->iSorterColumn, target);
71280         break;
71281       }
71282       /* Otherwise, fall thru into the TK_COLUMN case */
71283     }
71284     case TK_COLUMN: {
71285       if( pExpr->iTable<0 ){
71286         /* This only happens when coding check constraints */
71287         assert( pParse->ckBase>0 );
71288         inReg = pExpr->iColumn + pParse->ckBase;
71289       }else{
71290         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
71291                                  pExpr->iColumn, pExpr->iTable, target);
71292       }
71293       break;
71294     }
71295     case TK_INTEGER: {
71296       codeInteger(pParse, pExpr, 0, target);
71297       break;
71298     }
71299 #ifndef SQLITE_OMIT_FLOATING_POINT
71300     case TK_FLOAT: {
71301       assert( !ExprHasProperty(pExpr, EP_IntValue) );
71302       codeReal(v, pExpr->u.zToken, 0, target);
71303       break;
71304     }
71305 #endif
71306     case TK_STRING: {
71307       assert( !ExprHasProperty(pExpr, EP_IntValue) );
71308       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
71309       break;
71310     }
71311     case TK_NULL: {
71312       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
71313       break;
71314     }
71315 #ifndef SQLITE_OMIT_BLOB_LITERAL
71316     case TK_BLOB: {
71317       int n;
71318       const char *z;
71319       char *zBlob;
71320       assert( !ExprHasProperty(pExpr, EP_IntValue) );
71321       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
71322       assert( pExpr->u.zToken[1]=='\'' );
71323       z = &pExpr->u.zToken[2];
71324       n = sqlite3Strlen30(z) - 1;
71325       assert( z[n]=='\'' );
71326       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
71327       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
71328       break;
71329     }
71330 #endif
71331     case TK_VARIABLE: {
71332       assert( !ExprHasProperty(pExpr, EP_IntValue) );
71333       assert( pExpr->u.zToken!=0 );
71334       assert( pExpr->u.zToken[0]!=0 );
71335       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
71336       if( pExpr->u.zToken[1]!=0 ){
71337         sqlite3VdbeChangeP4(v, -1, pExpr->u.zToken, 0);
71338       }
71339       break;
71340     }
71341     case TK_REGISTER: {
71342       inReg = pExpr->iTable;
71343       break;
71344     }
71345     case TK_AS: {
71346       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
71347       break;
71348     }
71349 #ifndef SQLITE_OMIT_CAST
71350     case TK_CAST: {
71351       /* Expressions of the form:   CAST(pLeft AS token) */
71352       int aff, to_op;
71353       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
71354       assert( !ExprHasProperty(pExpr, EP_IntValue) );
71355       aff = sqlite3AffinityType(pExpr->u.zToken);
71356       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
71357       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
71358       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
71359       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
71360       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
71361       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
71362       testcase( to_op==OP_ToText );
71363       testcase( to_op==OP_ToBlob );
71364       testcase( to_op==OP_ToNumeric );
71365       testcase( to_op==OP_ToInt );
71366       testcase( to_op==OP_ToReal );
71367       if( inReg!=target ){
71368         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
71369         inReg = target;
71370       }
71371       sqlite3VdbeAddOp1(v, to_op, inReg);
71372       testcase( usedAsColumnCache(pParse, inReg, inReg) );
71373       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
71374       break;
71375     }
71376 #endif /* SQLITE_OMIT_CAST */
71377     case TK_LT:
71378     case TK_LE:
71379     case TK_GT:
71380     case TK_GE:
71381     case TK_NE:
71382     case TK_EQ: {
71383       assert( TK_LT==OP_Lt );
71384       assert( TK_LE==OP_Le );
71385       assert( TK_GT==OP_Gt );
71386       assert( TK_GE==OP_Ge );
71387       assert( TK_EQ==OP_Eq );
71388       assert( TK_NE==OP_Ne );
71389       testcase( op==TK_LT );
71390       testcase( op==TK_LE );
71391       testcase( op==TK_GT );
71392       testcase( op==TK_GE );
71393       testcase( op==TK_EQ );
71394       testcase( op==TK_NE );
71395       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
71396       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
71397       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
71398                   r1, r2, inReg, SQLITE_STOREP2);
71399       testcase( regFree1==0 );
71400       testcase( regFree2==0 );
71401       break;
71402     }
71403     case TK_IS:
71404     case TK_ISNOT: {
71405       testcase( op==TK_IS );
71406       testcase( op==TK_ISNOT );
71407       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
71408       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
71409       op = (op==TK_IS) ? TK_EQ : TK_NE;
71410       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
71411                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
71412       testcase( regFree1==0 );
71413       testcase( regFree2==0 );
71414       break;
71415     }
71416     case TK_AND:
71417     case TK_OR:
71418     case TK_PLUS:
71419     case TK_STAR:
71420     case TK_MINUS:
71421     case TK_REM:
71422     case TK_BITAND:
71423     case TK_BITOR:
71424     case TK_SLASH:
71425     case TK_LSHIFT:
71426     case TK_RSHIFT: 
71427     case TK_CONCAT: {
71428       assert( TK_AND==OP_And );
71429       assert( TK_OR==OP_Or );
71430       assert( TK_PLUS==OP_Add );
71431       assert( TK_MINUS==OP_Subtract );
71432       assert( TK_REM==OP_Remainder );
71433       assert( TK_BITAND==OP_BitAnd );
71434       assert( TK_BITOR==OP_BitOr );
71435       assert( TK_SLASH==OP_Divide );
71436       assert( TK_LSHIFT==OP_ShiftLeft );
71437       assert( TK_RSHIFT==OP_ShiftRight );
71438       assert( TK_CONCAT==OP_Concat );
71439       testcase( op==TK_AND );
71440       testcase( op==TK_OR );
71441       testcase( op==TK_PLUS );
71442       testcase( op==TK_MINUS );
71443       testcase( op==TK_REM );
71444       testcase( op==TK_BITAND );
71445       testcase( op==TK_BITOR );
71446       testcase( op==TK_SLASH );
71447       testcase( op==TK_LSHIFT );
71448       testcase( op==TK_RSHIFT );
71449       testcase( op==TK_CONCAT );
71450       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
71451       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
71452       sqlite3VdbeAddOp3(v, op, r2, r1, target);
71453       testcase( regFree1==0 );
71454       testcase( regFree2==0 );
71455       break;
71456     }
71457     case TK_UMINUS: {
71458       Expr *pLeft = pExpr->pLeft;
71459       assert( pLeft );
71460       if( pLeft->op==TK_INTEGER ){
71461         codeInteger(pParse, pLeft, 1, target);
71462 #ifndef SQLITE_OMIT_FLOATING_POINT
71463       }else if( pLeft->op==TK_FLOAT ){
71464         assert( !ExprHasProperty(pExpr, EP_IntValue) );
71465         codeReal(v, pLeft->u.zToken, 1, target);
71466 #endif
71467       }else{
71468         regFree1 = r1 = sqlite3GetTempReg(pParse);
71469         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
71470         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
71471         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
71472         testcase( regFree2==0 );
71473       }
71474       inReg = target;
71475       break;
71476     }
71477     case TK_BITNOT:
71478     case TK_NOT: {
71479       assert( TK_BITNOT==OP_BitNot );
71480       assert( TK_NOT==OP_Not );
71481       testcase( op==TK_BITNOT );
71482       testcase( op==TK_NOT );
71483       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
71484       testcase( regFree1==0 );
71485       inReg = target;
71486       sqlite3VdbeAddOp2(v, op, r1, inReg);
71487       break;
71488     }
71489     case TK_ISNULL:
71490     case TK_NOTNULL: {
71491       int addr;
71492       assert( TK_ISNULL==OP_IsNull );
71493       assert( TK_NOTNULL==OP_NotNull );
71494       testcase( op==TK_ISNULL );
71495       testcase( op==TK_NOTNULL );
71496       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
71497       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
71498       testcase( regFree1==0 );
71499       addr = sqlite3VdbeAddOp1(v, op, r1);
71500       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
71501       sqlite3VdbeJumpHere(v, addr);
71502       break;
71503     }
71504     case TK_AGG_FUNCTION: {
71505       AggInfo *pInfo = pExpr->pAggInfo;
71506       if( pInfo==0 ){
71507         assert( !ExprHasProperty(pExpr, EP_IntValue) );
71508         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
71509       }else{
71510         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
71511       }
71512       break;
71513     }
71514     case TK_CONST_FUNC:
71515     case TK_FUNCTION: {
71516       ExprList *pFarg;       /* List of function arguments */
71517       int nFarg;             /* Number of function arguments */
71518       FuncDef *pDef;         /* The function definition object */
71519       int nId;               /* Length of the function name in bytes */
71520       const char *zId;       /* The function name */
71521       int constMask = 0;     /* Mask of function arguments that are constant */
71522       int i;                 /* Loop counter */
71523       u8 enc = ENC(db);      /* The text encoding used by this database */
71524       CollSeq *pColl = 0;    /* A collating sequence */
71525
71526       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
71527       testcase( op==TK_CONST_FUNC );
71528       testcase( op==TK_FUNCTION );
71529       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
71530         pFarg = 0;
71531       }else{
71532         pFarg = pExpr->x.pList;
71533       }
71534       nFarg = pFarg ? pFarg->nExpr : 0;
71535       assert( !ExprHasProperty(pExpr, EP_IntValue) );
71536       zId = pExpr->u.zToken;
71537       nId = sqlite3Strlen30(zId);
71538       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
71539       if( pDef==0 ){
71540         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
71541         break;
71542       }
71543
71544       /* Attempt a direct implementation of the built-in COALESCE() and
71545       ** IFNULL() functions.  This avoids unnecessary evalation of
71546       ** arguments past the first non-NULL argument.
71547       */
71548       if( pDef->flags & SQLITE_FUNC_COALESCE ){
71549         int endCoalesce = sqlite3VdbeMakeLabel(v);
71550         assert( nFarg>=2 );
71551         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
71552         for(i=1; i<nFarg; i++){
71553           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
71554           sqlite3ExprCacheRemove(pParse, target, 1);
71555           sqlite3ExprCachePush(pParse);
71556           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
71557           sqlite3ExprCachePop(pParse, 1);
71558         }
71559         sqlite3VdbeResolveLabel(v, endCoalesce);
71560         break;
71561       }
71562
71563
71564       if( pFarg ){
71565         r1 = sqlite3GetTempRange(pParse, nFarg);
71566         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
71567         sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
71568         sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
71569       }else{
71570         r1 = 0;
71571       }
71572 #ifndef SQLITE_OMIT_VIRTUALTABLE
71573       /* Possibly overload the function if the first argument is
71574       ** a virtual table column.
71575       **
71576       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
71577       ** second argument, not the first, as the argument to test to
71578       ** see if it is a column in a virtual table.  This is done because
71579       ** the left operand of infix functions (the operand we want to
71580       ** control overloading) ends up as the second argument to the
71581       ** function.  The expression "A glob B" is equivalent to 
71582       ** "glob(B,A).  We want to use the A in "A glob B" to test
71583       ** for function overloading.  But we use the B term in "glob(B,A)".
71584       */
71585       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
71586         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
71587       }else if( nFarg>0 ){
71588         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
71589       }
71590 #endif
71591       for(i=0; i<nFarg; i++){
71592         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
71593           constMask |= (1<<i);
71594         }
71595         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
71596           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
71597         }
71598       }
71599       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
71600         if( !pColl ) pColl = db->pDfltColl; 
71601         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
71602       }
71603       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
71604                         (char*)pDef, P4_FUNCDEF);
71605       sqlite3VdbeChangeP5(v, (u8)nFarg);
71606       if( nFarg ){
71607         sqlite3ReleaseTempRange(pParse, r1, nFarg);
71608       }
71609       break;
71610     }
71611 #ifndef SQLITE_OMIT_SUBQUERY
71612     case TK_EXISTS:
71613     case TK_SELECT: {
71614       testcase( op==TK_EXISTS );
71615       testcase( op==TK_SELECT );
71616       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
71617       break;
71618     }
71619     case TK_IN: {
71620       int destIfFalse = sqlite3VdbeMakeLabel(v);
71621       int destIfNull = sqlite3VdbeMakeLabel(v);
71622       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
71623       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
71624       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
71625       sqlite3VdbeResolveLabel(v, destIfFalse);
71626       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
71627       sqlite3VdbeResolveLabel(v, destIfNull);
71628       break;
71629     }
71630 #endif /* SQLITE_OMIT_SUBQUERY */
71631
71632
71633     /*
71634     **    x BETWEEN y AND z
71635     **
71636     ** This is equivalent to
71637     **
71638     **    x>=y AND x<=z
71639     **
71640     ** X is stored in pExpr->pLeft.
71641     ** Y is stored in pExpr->pList->a[0].pExpr.
71642     ** Z is stored in pExpr->pList->a[1].pExpr.
71643     */
71644     case TK_BETWEEN: {
71645       Expr *pLeft = pExpr->pLeft;
71646       struct ExprList_item *pLItem = pExpr->x.pList->a;
71647       Expr *pRight = pLItem->pExpr;
71648
71649       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
71650       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
71651       testcase( regFree1==0 );
71652       testcase( regFree2==0 );
71653       r3 = sqlite3GetTempReg(pParse);
71654       r4 = sqlite3GetTempReg(pParse);
71655       codeCompare(pParse, pLeft, pRight, OP_Ge,
71656                   r1, r2, r3, SQLITE_STOREP2);
71657       pLItem++;
71658       pRight = pLItem->pExpr;
71659       sqlite3ReleaseTempReg(pParse, regFree2);
71660       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
71661       testcase( regFree2==0 );
71662       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
71663       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
71664       sqlite3ReleaseTempReg(pParse, r3);
71665       sqlite3ReleaseTempReg(pParse, r4);
71666       break;
71667     }
71668     case TK_UPLUS: {
71669       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
71670       break;
71671     }
71672
71673     case TK_TRIGGER: {
71674       /* If the opcode is TK_TRIGGER, then the expression is a reference
71675       ** to a column in the new.* or old.* pseudo-tables available to
71676       ** trigger programs. In this case Expr.iTable is set to 1 for the
71677       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
71678       ** is set to the column of the pseudo-table to read, or to -1 to
71679       ** read the rowid field.
71680       **
71681       ** The expression is implemented using an OP_Param opcode. The p1
71682       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
71683       ** to reference another column of the old.* pseudo-table, where 
71684       ** i is the index of the column. For a new.rowid reference, p1 is
71685       ** set to (n+1), where n is the number of columns in each pseudo-table.
71686       ** For a reference to any other column in the new.* pseudo-table, p1
71687       ** is set to (n+2+i), where n and i are as defined previously. For
71688       ** example, if the table on which triggers are being fired is
71689       ** declared as:
71690       **
71691       **   CREATE TABLE t1(a, b);
71692       **
71693       ** Then p1 is interpreted as follows:
71694       **
71695       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
71696       **   p1==1   ->    old.a         p1==4   ->    new.a
71697       **   p1==2   ->    old.b         p1==5   ->    new.b       
71698       */
71699       Table *pTab = pExpr->pTab;
71700       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
71701
71702       assert( pExpr->iTable==0 || pExpr->iTable==1 );
71703       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
71704       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
71705       assert( p1>=0 && p1<(pTab->nCol*2+2) );
71706
71707       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
71708       VdbeComment((v, "%s.%s -> $%d",
71709         (pExpr->iTable ? "new" : "old"),
71710         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
71711         target
71712       ));
71713
71714 #ifndef SQLITE_OMIT_FLOATING_POINT
71715       /* If the column has REAL affinity, it may currently be stored as an
71716       ** integer. Use OP_RealAffinity to make sure it is really real.  */
71717       if( pExpr->iColumn>=0 
71718        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
71719       ){
71720         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
71721       }
71722 #endif
71723       break;
71724     }
71725
71726
71727     /*
71728     ** Form A:
71729     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
71730     **
71731     ** Form B:
71732     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
71733     **
71734     ** Form A is can be transformed into the equivalent form B as follows:
71735     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
71736     **        WHEN x=eN THEN rN ELSE y END
71737     **
71738     ** X (if it exists) is in pExpr->pLeft.
71739     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
71740     ** ELSE clause and no other term matches, then the result of the
71741     ** exprssion is NULL.
71742     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
71743     **
71744     ** The result of the expression is the Ri for the first matching Ei,
71745     ** or if there is no matching Ei, the ELSE term Y, or if there is
71746     ** no ELSE term, NULL.
71747     */
71748     default: assert( op==TK_CASE ); {
71749       int endLabel;                     /* GOTO label for end of CASE stmt */
71750       int nextCase;                     /* GOTO label for next WHEN clause */
71751       int nExpr;                        /* 2x number of WHEN terms */
71752       int i;                            /* Loop counter */
71753       ExprList *pEList;                 /* List of WHEN terms */
71754       struct ExprList_item *aListelem;  /* Array of WHEN terms */
71755       Expr opCompare;                   /* The X==Ei expression */
71756       Expr cacheX;                      /* Cached expression X */
71757       Expr *pX;                         /* The X expression */
71758       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
71759       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
71760
71761       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
71762       assert((pExpr->x.pList->nExpr % 2) == 0);
71763       assert(pExpr->x.pList->nExpr > 0);
71764       pEList = pExpr->x.pList;
71765       aListelem = pEList->a;
71766       nExpr = pEList->nExpr;
71767       endLabel = sqlite3VdbeMakeLabel(v);
71768       if( (pX = pExpr->pLeft)!=0 ){
71769         cacheX = *pX;
71770         testcase( pX->op==TK_COLUMN );
71771         testcase( pX->op==TK_REGISTER );
71772         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
71773         testcase( regFree1==0 );
71774         cacheX.op = TK_REGISTER;
71775         opCompare.op = TK_EQ;
71776         opCompare.pLeft = &cacheX;
71777         pTest = &opCompare;
71778         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
71779         ** The value in regFree1 might get SCopy-ed into the file result.
71780         ** So make sure that the regFree1 register is not reused for other
71781         ** purposes and possibly overwritten.  */
71782         regFree1 = 0;
71783       }
71784       for(i=0; i<nExpr; i=i+2){
71785         sqlite3ExprCachePush(pParse);
71786         if( pX ){
71787           assert( pTest!=0 );
71788           opCompare.pRight = aListelem[i].pExpr;
71789         }else{
71790           pTest = aListelem[i].pExpr;
71791         }
71792         nextCase = sqlite3VdbeMakeLabel(v);
71793         testcase( pTest->op==TK_COLUMN );
71794         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
71795         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
71796         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
71797         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
71798         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
71799         sqlite3ExprCachePop(pParse, 1);
71800         sqlite3VdbeResolveLabel(v, nextCase);
71801       }
71802       if( pExpr->pRight ){
71803         sqlite3ExprCachePush(pParse);
71804         sqlite3ExprCode(pParse, pExpr->pRight, target);
71805         sqlite3ExprCachePop(pParse, 1);
71806       }else{
71807         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
71808       }
71809       assert( db->mallocFailed || pParse->nErr>0 
71810            || pParse->iCacheLevel==iCacheLevel );
71811       sqlite3VdbeResolveLabel(v, endLabel);
71812       break;
71813     }
71814 #ifndef SQLITE_OMIT_TRIGGER
71815     case TK_RAISE: {
71816       assert( pExpr->affinity==OE_Rollback 
71817            || pExpr->affinity==OE_Abort
71818            || pExpr->affinity==OE_Fail
71819            || pExpr->affinity==OE_Ignore
71820       );
71821       if( !pParse->pTriggerTab ){
71822         sqlite3ErrorMsg(pParse,
71823                        "RAISE() may only be used within a trigger-program");
71824         return 0;
71825       }
71826       if( pExpr->affinity==OE_Abort ){
71827         sqlite3MayAbort(pParse);
71828       }
71829       assert( !ExprHasProperty(pExpr, EP_IntValue) );
71830       if( pExpr->affinity==OE_Ignore ){
71831         sqlite3VdbeAddOp4(
71832             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
71833       }else{
71834         sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
71835       }
71836
71837       break;
71838     }
71839 #endif
71840   }
71841   sqlite3ReleaseTempReg(pParse, regFree1);
71842   sqlite3ReleaseTempReg(pParse, regFree2);
71843   return inReg;
71844 }
71845
71846 /*
71847 ** Generate code to evaluate an expression and store the results
71848 ** into a register.  Return the register number where the results
71849 ** are stored.
71850 **
71851 ** If the register is a temporary register that can be deallocated,
71852 ** then write its number into *pReg.  If the result register is not
71853 ** a temporary, then set *pReg to zero.
71854 */
71855 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
71856   int r1 = sqlite3GetTempReg(pParse);
71857   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
71858   if( r2==r1 ){
71859     *pReg = r1;
71860   }else{
71861     sqlite3ReleaseTempReg(pParse, r1);
71862     *pReg = 0;
71863   }
71864   return r2;
71865 }
71866
71867 /*
71868 ** Generate code that will evaluate expression pExpr and store the
71869 ** results in register target.  The results are guaranteed to appear
71870 ** in register target.
71871 */
71872 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
71873   int inReg;
71874
71875   assert( target>0 && target<=pParse->nMem );
71876   if( pExpr && pExpr->op==TK_REGISTER ){
71877     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
71878   }else{
71879     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
71880     assert( pParse->pVdbe || pParse->db->mallocFailed );
71881     if( inReg!=target && pParse->pVdbe ){
71882       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
71883     }
71884   }
71885   return target;
71886 }
71887
71888 /*
71889 ** Generate code that evalutes the given expression and puts the result
71890 ** in register target.
71891 **
71892 ** Also make a copy of the expression results into another "cache" register
71893 ** and modify the expression so that the next time it is evaluated,
71894 ** the result is a copy of the cache register.
71895 **
71896 ** This routine is used for expressions that are used multiple 
71897 ** times.  They are evaluated once and the results of the expression
71898 ** are reused.
71899 */
71900 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
71901   Vdbe *v = pParse->pVdbe;
71902   int inReg;
71903   inReg = sqlite3ExprCode(pParse, pExpr, target);
71904   assert( target>0 );
71905   /* This routine is called for terms to INSERT or UPDATE.  And the only
71906   ** other place where expressions can be converted into TK_REGISTER is
71907   ** in WHERE clause processing.  So as currently implemented, there is
71908   ** no way for a TK_REGISTER to exist here.  But it seems prudent to
71909   ** keep the ALWAYS() in case the conditions above change with future
71910   ** modifications or enhancements. */
71911   if( ALWAYS(pExpr->op!=TK_REGISTER) ){  
71912     int iMem;
71913     iMem = ++pParse->nMem;
71914     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
71915     pExpr->iTable = iMem;
71916     pExpr->op2 = pExpr->op;
71917     pExpr->op = TK_REGISTER;
71918   }
71919   return inReg;
71920 }
71921
71922 /*
71923 ** Return TRUE if pExpr is an constant expression that is appropriate
71924 ** for factoring out of a loop.  Appropriate expressions are:
71925 **
71926 **    *  Any expression that evaluates to two or more opcodes.
71927 **
71928 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
71929 **       or OP_Variable that does not need to be placed in a 
71930 **       specific register.
71931 **
71932 ** There is no point in factoring out single-instruction constant
71933 ** expressions that need to be placed in a particular register.  
71934 ** We could factor them out, but then we would end up adding an
71935 ** OP_SCopy instruction to move the value into the correct register
71936 ** later.  We might as well just use the original instruction and
71937 ** avoid the OP_SCopy.
71938 */
71939 static int isAppropriateForFactoring(Expr *p){
71940   if( !sqlite3ExprIsConstantNotJoin(p) ){
71941     return 0;  /* Only constant expressions are appropriate for factoring */
71942   }
71943   if( (p->flags & EP_FixedDest)==0 ){
71944     return 1;  /* Any constant without a fixed destination is appropriate */
71945   }
71946   while( p->op==TK_UPLUS ) p = p->pLeft;
71947   switch( p->op ){
71948 #ifndef SQLITE_OMIT_BLOB_LITERAL
71949     case TK_BLOB:
71950 #endif
71951     case TK_VARIABLE:
71952     case TK_INTEGER:
71953     case TK_FLOAT:
71954     case TK_NULL:
71955     case TK_STRING: {
71956       testcase( p->op==TK_BLOB );
71957       testcase( p->op==TK_VARIABLE );
71958       testcase( p->op==TK_INTEGER );
71959       testcase( p->op==TK_FLOAT );
71960       testcase( p->op==TK_NULL );
71961       testcase( p->op==TK_STRING );
71962       /* Single-instruction constants with a fixed destination are
71963       ** better done in-line.  If we factor them, they will just end
71964       ** up generating an OP_SCopy to move the value to the destination
71965       ** register. */
71966       return 0;
71967     }
71968     case TK_UMINUS: {
71969       if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
71970         return 0;
71971       }
71972       break;
71973     }
71974     default: {
71975       break;
71976     }
71977   }
71978   return 1;
71979 }
71980
71981 /*
71982 ** If pExpr is a constant expression that is appropriate for
71983 ** factoring out of a loop, then evaluate the expression
71984 ** into a register and convert the expression into a TK_REGISTER
71985 ** expression.
71986 */
71987 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
71988   Parse *pParse = pWalker->pParse;
71989   switch( pExpr->op ){
71990     case TK_IN:
71991     case TK_REGISTER: {
71992       return WRC_Prune;
71993     }
71994     case TK_FUNCTION:
71995     case TK_AGG_FUNCTION:
71996     case TK_CONST_FUNC: {
71997       /* The arguments to a function have a fixed destination.
71998       ** Mark them this way to avoid generated unneeded OP_SCopy
71999       ** instructions. 
72000       */
72001       ExprList *pList = pExpr->x.pList;
72002       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
72003       if( pList ){
72004         int i = pList->nExpr;
72005         struct ExprList_item *pItem = pList->a;
72006         for(; i>0; i--, pItem++){
72007           if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
72008         }
72009       }
72010       break;
72011     }
72012   }
72013   if( isAppropriateForFactoring(pExpr) ){
72014     int r1 = ++pParse->nMem;
72015     int r2;
72016     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
72017     if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
72018     pExpr->op2 = pExpr->op;
72019     pExpr->op = TK_REGISTER;
72020     pExpr->iTable = r2;
72021     return WRC_Prune;
72022   }
72023   return WRC_Continue;
72024 }
72025
72026 /*
72027 ** Preevaluate constant subexpressions within pExpr and store the
72028 ** results in registers.  Modify pExpr so that the constant subexpresions
72029 ** are TK_REGISTER opcodes that refer to the precomputed values.
72030 **
72031 ** This routine is a no-op if the jump to the cookie-check code has
72032 ** already occur.  Since the cookie-check jump is generated prior to
72033 ** any other serious processing, this check ensures that there is no
72034 ** way to accidently bypass the constant initializations.
72035 **
72036 ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
72037 ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
72038 ** interface.  This allows test logic to verify that the same answer is
72039 ** obtained for queries regardless of whether or not constants are
72040 ** precomputed into registers or if they are inserted in-line.
72041 */
72042 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
72043   Walker w;
72044   if( pParse->cookieGoto ) return;
72045   if( (pParse->db->flags & SQLITE_FactorOutConst)!=0 ) return;
72046   w.xExprCallback = evalConstExpr;
72047   w.xSelectCallback = 0;
72048   w.pParse = pParse;
72049   sqlite3WalkExpr(&w, pExpr);
72050 }
72051
72052
72053 /*
72054 ** Generate code that pushes the value of every element of the given
72055 ** expression list into a sequence of registers beginning at target.
72056 **
72057 ** Return the number of elements evaluated.
72058 */
72059 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
72060   Parse *pParse,     /* Parsing context */
72061   ExprList *pList,   /* The expression list to be coded */
72062   int target,        /* Where to write results */
72063   int doHardCopy     /* Make a hard copy of every element */
72064 ){
72065   struct ExprList_item *pItem;
72066   int i, n;
72067   assert( pList!=0 );
72068   assert( target>0 );
72069   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
72070   n = pList->nExpr;
72071   for(pItem=pList->a, i=0; i<n; i++, pItem++){
72072     Expr *pExpr = pItem->pExpr;
72073     int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
72074     if( inReg!=target+i ){
72075       sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
72076                         inReg, target+i);
72077     }
72078   }
72079   return n;
72080 }
72081
72082 /*
72083 ** Generate code for a BETWEEN operator.
72084 **
72085 **    x BETWEEN y AND z
72086 **
72087 ** The above is equivalent to 
72088 **
72089 **    x>=y AND x<=z
72090 **
72091 ** Code it as such, taking care to do the common subexpression
72092 ** elementation of x.
72093 */
72094 static void exprCodeBetween(
72095   Parse *pParse,    /* Parsing and code generating context */
72096   Expr *pExpr,      /* The BETWEEN expression */
72097   int dest,         /* Jump here if the jump is taken */
72098   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
72099   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
72100 ){
72101   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
72102   Expr compLeft;    /* The  x>=y  term */
72103   Expr compRight;   /* The  x<=z  term */
72104   Expr exprX;       /* The  x  subexpression */
72105   int regFree1 = 0; /* Temporary use register */
72106
72107   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
72108   exprX = *pExpr->pLeft;
72109   exprAnd.op = TK_AND;
72110   exprAnd.pLeft = &compLeft;
72111   exprAnd.pRight = &compRight;
72112   compLeft.op = TK_GE;
72113   compLeft.pLeft = &exprX;
72114   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
72115   compRight.op = TK_LE;
72116   compRight.pLeft = &exprX;
72117   compRight.pRight = pExpr->x.pList->a[1].pExpr;
72118   exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
72119   exprX.op = TK_REGISTER;
72120   if( jumpIfTrue ){
72121     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
72122   }else{
72123     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
72124   }
72125   sqlite3ReleaseTempReg(pParse, regFree1);
72126
72127   /* Ensure adequate test coverage */
72128   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
72129   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
72130   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
72131   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
72132   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
72133   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
72134   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
72135   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
72136 }
72137
72138 /*
72139 ** Generate code for a boolean expression such that a jump is made
72140 ** to the label "dest" if the expression is true but execution
72141 ** continues straight thru if the expression is false.
72142 **
72143 ** If the expression evaluates to NULL (neither true nor false), then
72144 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
72145 **
72146 ** This code depends on the fact that certain token values (ex: TK_EQ)
72147 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
72148 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
72149 ** the make process cause these values to align.  Assert()s in the code
72150 ** below verify that the numbers are aligned correctly.
72151 */
72152 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
72153   Vdbe *v = pParse->pVdbe;
72154   int op = 0;
72155   int regFree1 = 0;
72156   int regFree2 = 0;
72157   int r1, r2;
72158
72159   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
72160   if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
72161   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
72162   op = pExpr->op;
72163   switch( op ){
72164     case TK_AND: {
72165       int d2 = sqlite3VdbeMakeLabel(v);
72166       testcase( jumpIfNull==0 );
72167       sqlite3ExprCachePush(pParse);
72168       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
72169       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
72170       sqlite3VdbeResolveLabel(v, d2);
72171       sqlite3ExprCachePop(pParse, 1);
72172       break;
72173     }
72174     case TK_OR: {
72175       testcase( jumpIfNull==0 );
72176       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
72177       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
72178       break;
72179     }
72180     case TK_NOT: {
72181       testcase( jumpIfNull==0 );
72182       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
72183       break;
72184     }
72185     case TK_LT:
72186     case TK_LE:
72187     case TK_GT:
72188     case TK_GE:
72189     case TK_NE:
72190     case TK_EQ: {
72191       assert( TK_LT==OP_Lt );
72192       assert( TK_LE==OP_Le );
72193       assert( TK_GT==OP_Gt );
72194       assert( TK_GE==OP_Ge );
72195       assert( TK_EQ==OP_Eq );
72196       assert( TK_NE==OP_Ne );
72197       testcase( op==TK_LT );
72198       testcase( op==TK_LE );
72199       testcase( op==TK_GT );
72200       testcase( op==TK_GE );
72201       testcase( op==TK_EQ );
72202       testcase( op==TK_NE );
72203       testcase( jumpIfNull==0 );
72204       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
72205       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
72206       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
72207                   r1, r2, dest, jumpIfNull);
72208       testcase( regFree1==0 );
72209       testcase( regFree2==0 );
72210       break;
72211     }
72212     case TK_IS:
72213     case TK_ISNOT: {
72214       testcase( op==TK_IS );
72215       testcase( op==TK_ISNOT );
72216       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
72217       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
72218       op = (op==TK_IS) ? TK_EQ : TK_NE;
72219       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
72220                   r1, r2, dest, SQLITE_NULLEQ);
72221       testcase( regFree1==0 );
72222       testcase( regFree2==0 );
72223       break;
72224     }
72225     case TK_ISNULL:
72226     case TK_NOTNULL: {
72227       assert( TK_ISNULL==OP_IsNull );
72228       assert( TK_NOTNULL==OP_NotNull );
72229       testcase( op==TK_ISNULL );
72230       testcase( op==TK_NOTNULL );
72231       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
72232       sqlite3VdbeAddOp2(v, op, r1, dest);
72233       testcase( regFree1==0 );
72234       break;
72235     }
72236     case TK_BETWEEN: {
72237       testcase( jumpIfNull==0 );
72238       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
72239       break;
72240     }
72241     case TK_IN: {
72242       int destIfFalse = sqlite3VdbeMakeLabel(v);
72243       int destIfNull = jumpIfNull ? dest : destIfFalse;
72244       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
72245       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
72246       sqlite3VdbeResolveLabel(v, destIfFalse);
72247       break;
72248     }
72249     default: {
72250       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
72251       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
72252       testcase( regFree1==0 );
72253       testcase( jumpIfNull==0 );
72254       break;
72255     }
72256   }
72257   sqlite3ReleaseTempReg(pParse, regFree1);
72258   sqlite3ReleaseTempReg(pParse, regFree2);  
72259 }
72260
72261 /*
72262 ** Generate code for a boolean expression such that a jump is made
72263 ** to the label "dest" if the expression is false but execution
72264 ** continues straight thru if the expression is true.
72265 **
72266 ** If the expression evaluates to NULL (neither true nor false) then
72267 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
72268 ** is 0.
72269 */
72270 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
72271   Vdbe *v = pParse->pVdbe;
72272   int op = 0;
72273   int regFree1 = 0;
72274   int regFree2 = 0;
72275   int r1, r2;
72276
72277   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
72278   if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
72279   if( pExpr==0 )    return;
72280
72281   /* The value of pExpr->op and op are related as follows:
72282   **
72283   **       pExpr->op            op
72284   **       ---------          ----------
72285   **       TK_ISNULL          OP_NotNull
72286   **       TK_NOTNULL         OP_IsNull
72287   **       TK_NE              OP_Eq
72288   **       TK_EQ              OP_Ne
72289   **       TK_GT              OP_Le
72290   **       TK_LE              OP_Gt
72291   **       TK_GE              OP_Lt
72292   **       TK_LT              OP_Ge
72293   **
72294   ** For other values of pExpr->op, op is undefined and unused.
72295   ** The value of TK_ and OP_ constants are arranged such that we
72296   ** can compute the mapping above using the following expression.
72297   ** Assert()s verify that the computation is correct.
72298   */
72299   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
72300
72301   /* Verify correct alignment of TK_ and OP_ constants
72302   */
72303   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
72304   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
72305   assert( pExpr->op!=TK_NE || op==OP_Eq );
72306   assert( pExpr->op!=TK_EQ || op==OP_Ne );
72307   assert( pExpr->op!=TK_LT || op==OP_Ge );
72308   assert( pExpr->op!=TK_LE || op==OP_Gt );
72309   assert( pExpr->op!=TK_GT || op==OP_Le );
72310   assert( pExpr->op!=TK_GE || op==OP_Lt );
72311
72312   switch( pExpr->op ){
72313     case TK_AND: {
72314       testcase( jumpIfNull==0 );
72315       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
72316       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
72317       break;
72318     }
72319     case TK_OR: {
72320       int d2 = sqlite3VdbeMakeLabel(v);
72321       testcase( jumpIfNull==0 );
72322       sqlite3ExprCachePush(pParse);
72323       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
72324       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
72325       sqlite3VdbeResolveLabel(v, d2);
72326       sqlite3ExprCachePop(pParse, 1);
72327       break;
72328     }
72329     case TK_NOT: {
72330       testcase( jumpIfNull==0 );
72331       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
72332       break;
72333     }
72334     case TK_LT:
72335     case TK_LE:
72336     case TK_GT:
72337     case TK_GE:
72338     case TK_NE:
72339     case TK_EQ: {
72340       testcase( op==TK_LT );
72341       testcase( op==TK_LE );
72342       testcase( op==TK_GT );
72343       testcase( op==TK_GE );
72344       testcase( op==TK_EQ );
72345       testcase( op==TK_NE );
72346       testcase( jumpIfNull==0 );
72347       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
72348       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
72349       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
72350                   r1, r2, dest, jumpIfNull);
72351       testcase( regFree1==0 );
72352       testcase( regFree2==0 );
72353       break;
72354     }
72355     case TK_IS:
72356     case TK_ISNOT: {
72357       testcase( pExpr->op==TK_IS );
72358       testcase( pExpr->op==TK_ISNOT );
72359       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
72360       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
72361       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
72362       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
72363                   r1, r2, dest, SQLITE_NULLEQ);
72364       testcase( regFree1==0 );
72365       testcase( regFree2==0 );
72366       break;
72367     }
72368     case TK_ISNULL:
72369     case TK_NOTNULL: {
72370       testcase( op==TK_ISNULL );
72371       testcase( op==TK_NOTNULL );
72372       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
72373       sqlite3VdbeAddOp2(v, op, r1, dest);
72374       testcase( regFree1==0 );
72375       break;
72376     }
72377     case TK_BETWEEN: {
72378       testcase( jumpIfNull==0 );
72379       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
72380       break;
72381     }
72382     case TK_IN: {
72383       if( jumpIfNull ){
72384         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
72385       }else{
72386         int destIfNull = sqlite3VdbeMakeLabel(v);
72387         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
72388         sqlite3VdbeResolveLabel(v, destIfNull);
72389       }
72390       break;
72391     }
72392     default: {
72393       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
72394       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
72395       testcase( regFree1==0 );
72396       testcase( jumpIfNull==0 );
72397       break;
72398     }
72399   }
72400   sqlite3ReleaseTempReg(pParse, regFree1);
72401   sqlite3ReleaseTempReg(pParse, regFree2);
72402 }
72403
72404 /*
72405 ** Do a deep comparison of two expression trees.  Return 0 if the two
72406 ** expressions are completely identical.  Return 1 if they differ only
72407 ** by a COLLATE operator at the top level.  Return 2 if there are differences
72408 ** other than the top-level COLLATE operator.
72409 **
72410 ** Sometimes this routine will return 2 even if the two expressions
72411 ** really are equivalent.  If we cannot prove that the expressions are
72412 ** identical, we return 2 just to be safe.  So if this routine
72413 ** returns 2, then you do not really know for certain if the two
72414 ** expressions are the same.  But if you get a 0 or 1 return, then you
72415 ** can be sure the expressions are the same.  In the places where
72416 ** this routine is used, it does not hurt to get an extra 2 - that
72417 ** just might result in some slightly slower code.  But returning
72418 ** an incorrect 0 or 1 could lead to a malfunction.
72419 */
72420 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
72421   if( pA==0||pB==0 ){
72422     return pB==pA ? 0 : 2;
72423   }
72424   assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
72425   assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
72426   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
72427     return 2;
72428   }
72429   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
72430   if( pA->op!=pB->op ) return 2;
72431   if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
72432   if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
72433   if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
72434   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
72435   if( ExprHasProperty(pA, EP_IntValue) ){
72436     if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
72437       return 2;
72438     }
72439   }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
72440     if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
72441     if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ){
72442       return 2;
72443     }
72444   }
72445   if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
72446   if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
72447   return 0;
72448 }
72449
72450 /*
72451 ** Compare two ExprList objects.  Return 0 if they are identical and 
72452 ** non-zero if they differ in any way.
72453 **
72454 ** This routine might return non-zero for equivalent ExprLists.  The
72455 ** only consequence will be disabled optimizations.  But this routine
72456 ** must never return 0 if the two ExprList objects are different, or
72457 ** a malfunction will result.
72458 **
72459 ** Two NULL pointers are considered to be the same.  But a NULL pointer
72460 ** always differs from a non-NULL pointer.
72461 */
72462 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
72463   int i;
72464   if( pA==0 && pB==0 ) return 0;
72465   if( pA==0 || pB==0 ) return 1;
72466   if( pA->nExpr!=pB->nExpr ) return 1;
72467   for(i=0; i<pA->nExpr; i++){
72468     Expr *pExprA = pA->a[i].pExpr;
72469     Expr *pExprB = pB->a[i].pExpr;
72470     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
72471     if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
72472   }
72473   return 0;
72474 }
72475
72476 /*
72477 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
72478 ** the new element.  Return a negative number if malloc fails.
72479 */
72480 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
72481   int i;
72482   pInfo->aCol = sqlite3ArrayAllocate(
72483        db,
72484        pInfo->aCol,
72485        sizeof(pInfo->aCol[0]),
72486        3,
72487        &pInfo->nColumn,
72488        &pInfo->nColumnAlloc,
72489        &i
72490   );
72491   return i;
72492 }    
72493
72494 /*
72495 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
72496 ** the new element.  Return a negative number if malloc fails.
72497 */
72498 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
72499   int i;
72500   pInfo->aFunc = sqlite3ArrayAllocate(
72501        db, 
72502        pInfo->aFunc,
72503        sizeof(pInfo->aFunc[0]),
72504        3,
72505        &pInfo->nFunc,
72506        &pInfo->nFuncAlloc,
72507        &i
72508   );
72509   return i;
72510 }    
72511
72512 /*
72513 ** This is the xExprCallback for a tree walker.  It is used to
72514 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
72515 ** for additional information.
72516 */
72517 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
72518   int i;
72519   NameContext *pNC = pWalker->u.pNC;
72520   Parse *pParse = pNC->pParse;
72521   SrcList *pSrcList = pNC->pSrcList;
72522   AggInfo *pAggInfo = pNC->pAggInfo;
72523
72524   switch( pExpr->op ){
72525     case TK_AGG_COLUMN:
72526     case TK_COLUMN: {
72527       testcase( pExpr->op==TK_AGG_COLUMN );
72528       testcase( pExpr->op==TK_COLUMN );
72529       /* Check to see if the column is in one of the tables in the FROM
72530       ** clause of the aggregate query */
72531       if( ALWAYS(pSrcList!=0) ){
72532         struct SrcList_item *pItem = pSrcList->a;
72533         for(i=0; i<pSrcList->nSrc; i++, pItem++){
72534           struct AggInfo_col *pCol;
72535           assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
72536           if( pExpr->iTable==pItem->iCursor ){
72537             /* If we reach this point, it means that pExpr refers to a table
72538             ** that is in the FROM clause of the aggregate query.  
72539             **
72540             ** Make an entry for the column in pAggInfo->aCol[] if there
72541             ** is not an entry there already.
72542             */
72543             int k;
72544             pCol = pAggInfo->aCol;
72545             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
72546               if( pCol->iTable==pExpr->iTable &&
72547                   pCol->iColumn==pExpr->iColumn ){
72548                 break;
72549               }
72550             }
72551             if( (k>=pAggInfo->nColumn)
72552              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
72553             ){
72554               pCol = &pAggInfo->aCol[k];
72555               pCol->pTab = pExpr->pTab;
72556               pCol->iTable = pExpr->iTable;
72557               pCol->iColumn = pExpr->iColumn;
72558               pCol->iMem = ++pParse->nMem;
72559               pCol->iSorterColumn = -1;
72560               pCol->pExpr = pExpr;
72561               if( pAggInfo->pGroupBy ){
72562                 int j, n;
72563                 ExprList *pGB = pAggInfo->pGroupBy;
72564                 struct ExprList_item *pTerm = pGB->a;
72565                 n = pGB->nExpr;
72566                 for(j=0; j<n; j++, pTerm++){
72567                   Expr *pE = pTerm->pExpr;
72568                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
72569                       pE->iColumn==pExpr->iColumn ){
72570                     pCol->iSorterColumn = j;
72571                     break;
72572                   }
72573                 }
72574               }
72575               if( pCol->iSorterColumn<0 ){
72576                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
72577               }
72578             }
72579             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
72580             ** because it was there before or because we just created it).
72581             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
72582             ** pAggInfo->aCol[] entry.
72583             */
72584             ExprSetIrreducible(pExpr);
72585             pExpr->pAggInfo = pAggInfo;
72586             pExpr->op = TK_AGG_COLUMN;
72587             pExpr->iAgg = (i16)k;
72588             break;
72589           } /* endif pExpr->iTable==pItem->iCursor */
72590         } /* end loop over pSrcList */
72591       }
72592       return WRC_Prune;
72593     }
72594     case TK_AGG_FUNCTION: {
72595       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
72596       ** to be ignored */
72597       if( pNC->nDepth==0 ){
72598         /* Check to see if pExpr is a duplicate of another aggregate 
72599         ** function that is already in the pAggInfo structure
72600         */
72601         struct AggInfo_func *pItem = pAggInfo->aFunc;
72602         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
72603           if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
72604             break;
72605           }
72606         }
72607         if( i>=pAggInfo->nFunc ){
72608           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
72609           */
72610           u8 enc = ENC(pParse->db);
72611           i = addAggInfoFunc(pParse->db, pAggInfo);
72612           if( i>=0 ){
72613             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
72614             pItem = &pAggInfo->aFunc[i];
72615             pItem->pExpr = pExpr;
72616             pItem->iMem = ++pParse->nMem;
72617             assert( !ExprHasProperty(pExpr, EP_IntValue) );
72618             pItem->pFunc = sqlite3FindFunction(pParse->db,
72619                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
72620                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
72621             if( pExpr->flags & EP_Distinct ){
72622               pItem->iDistinct = pParse->nTab++;
72623             }else{
72624               pItem->iDistinct = -1;
72625             }
72626           }
72627         }
72628         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
72629         */
72630         assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
72631         ExprSetIrreducible(pExpr);
72632         pExpr->iAgg = (i16)i;
72633         pExpr->pAggInfo = pAggInfo;
72634         return WRC_Prune;
72635       }
72636     }
72637   }
72638   return WRC_Continue;
72639 }
72640 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
72641   NameContext *pNC = pWalker->u.pNC;
72642   if( pNC->nDepth==0 ){
72643     pNC->nDepth++;
72644     sqlite3WalkSelect(pWalker, pSelect);
72645     pNC->nDepth--;
72646     return WRC_Prune;
72647   }else{
72648     return WRC_Continue;
72649   }
72650 }
72651
72652 /*
72653 ** Analyze the given expression looking for aggregate functions and
72654 ** for variables that need to be added to the pParse->aAgg[] array.
72655 ** Make additional entries to the pParse->aAgg[] array as necessary.
72656 **
72657 ** This routine should only be called after the expression has been
72658 ** analyzed by sqlite3ResolveExprNames().
72659 */
72660 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
72661   Walker w;
72662   w.xExprCallback = analyzeAggregate;
72663   w.xSelectCallback = analyzeAggregatesInSelect;
72664   w.u.pNC = pNC;
72665   assert( pNC->pSrcList!=0 );
72666   sqlite3WalkExpr(&w, pExpr);
72667 }
72668
72669 /*
72670 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
72671 ** expression list.  Return the number of errors.
72672 **
72673 ** If an error is found, the analysis is cut short.
72674 */
72675 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
72676   struct ExprList_item *pItem;
72677   int i;
72678   if( pList ){
72679     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
72680       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
72681     }
72682   }
72683 }
72684
72685 /*
72686 ** Allocate a single new register for use to hold some intermediate result.
72687 */
72688 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
72689   if( pParse->nTempReg==0 ){
72690     return ++pParse->nMem;
72691   }
72692   return pParse->aTempReg[--pParse->nTempReg];
72693 }
72694
72695 /*
72696 ** Deallocate a register, making available for reuse for some other
72697 ** purpose.
72698 **
72699 ** If a register is currently being used by the column cache, then
72700 ** the dallocation is deferred until the column cache line that uses
72701 ** the register becomes stale.
72702 */
72703 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
72704   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
72705     int i;
72706     struct yColCache *p;
72707     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72708       if( p->iReg==iReg ){
72709         p->tempReg = 1;
72710         return;
72711       }
72712     }
72713     pParse->aTempReg[pParse->nTempReg++] = iReg;
72714   }
72715 }
72716
72717 /*
72718 ** Allocate or deallocate a block of nReg consecutive registers
72719 */
72720 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
72721   int i, n;
72722   i = pParse->iRangeReg;
72723   n = pParse->nRangeReg;
72724   if( nReg<=n ){
72725     assert( !usedAsColumnCache(pParse, i, i+n-1) );
72726     pParse->iRangeReg += nReg;
72727     pParse->nRangeReg -= nReg;
72728   }else{
72729     i = pParse->nMem+1;
72730     pParse->nMem += nReg;
72731   }
72732   return i;
72733 }
72734 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
72735   sqlite3ExprCacheRemove(pParse, iReg, nReg);
72736   if( nReg>pParse->nRangeReg ){
72737     pParse->nRangeReg = nReg;
72738     pParse->iRangeReg = iReg;
72739   }
72740 }
72741
72742 /************** End of expr.c ************************************************/
72743 /************** Begin file alter.c *******************************************/
72744 /*
72745 ** 2005 February 15
72746 **
72747 ** The author disclaims copyright to this source code.  In place of
72748 ** a legal notice, here is a blessing:
72749 **
72750 **    May you do good and not evil.
72751 **    May you find forgiveness for yourself and forgive others.
72752 **    May you share freely, never taking more than you give.
72753 **
72754 *************************************************************************
72755 ** This file contains C code routines that used to generate VDBE code
72756 ** that implements the ALTER TABLE command.
72757 */
72758
72759 /*
72760 ** The code in this file only exists if we are not omitting the
72761 ** ALTER TABLE logic from the build.
72762 */
72763 #ifndef SQLITE_OMIT_ALTERTABLE
72764
72765
72766 /*
72767 ** This function is used by SQL generated to implement the 
72768 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
72769 ** CREATE INDEX command. The second is a table name. The table name in 
72770 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
72771 ** argument and the result returned. Examples:
72772 **
72773 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
72774 **     -> 'CREATE TABLE def(a, b, c)'
72775 **
72776 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
72777 **     -> 'CREATE INDEX i ON def(a, b, c)'
72778 */
72779 static void renameTableFunc(
72780   sqlite3_context *context,
72781   int NotUsed,
72782   sqlite3_value **argv
72783 ){
72784   unsigned char const *zSql = sqlite3_value_text(argv[0]);
72785   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
72786
72787   int token;
72788   Token tname;
72789   unsigned char const *zCsr = zSql;
72790   int len = 0;
72791   char *zRet;
72792
72793   sqlite3 *db = sqlite3_context_db_handle(context);
72794
72795   UNUSED_PARAMETER(NotUsed);
72796
72797   /* The principle used to locate the table name in the CREATE TABLE 
72798   ** statement is that the table name is the first non-space token that
72799   ** is immediately followed by a TK_LP or TK_USING token.
72800   */
72801   if( zSql ){
72802     do {
72803       if( !*zCsr ){
72804         /* Ran out of input before finding an opening bracket. Return NULL. */
72805         return;
72806       }
72807
72808       /* Store the token that zCsr points to in tname. */
72809       tname.z = (char*)zCsr;
72810       tname.n = len;
72811
72812       /* Advance zCsr to the next token. Store that token type in 'token',
72813       ** and its length in 'len' (to be used next iteration of this loop).
72814       */
72815       do {
72816         zCsr += len;
72817         len = sqlite3GetToken(zCsr, &token);
72818       } while( token==TK_SPACE );
72819       assert( len>0 );
72820     } while( token!=TK_LP && token!=TK_USING );
72821
72822     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
72823        zTableName, tname.z+tname.n);
72824     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
72825   }
72826 }
72827
72828 /*
72829 ** This C function implements an SQL user function that is used by SQL code
72830 ** generated by the ALTER TABLE ... RENAME command to modify the definition
72831 ** of any foreign key constraints that use the table being renamed as the 
72832 ** parent table. It is passed three arguments:
72833 **
72834 **   1) The complete text of the CREATE TABLE statement being modified,
72835 **   2) The old name of the table being renamed, and
72836 **   3) The new name of the table being renamed.
72837 **
72838 ** It returns the new CREATE TABLE statement. For example:
72839 **
72840 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
72841 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
72842 */
72843 #ifndef SQLITE_OMIT_FOREIGN_KEY
72844 static void renameParentFunc(
72845   sqlite3_context *context,
72846   int NotUsed,
72847   sqlite3_value **argv
72848 ){
72849   sqlite3 *db = sqlite3_context_db_handle(context);
72850   char *zOutput = 0;
72851   char *zResult;
72852   unsigned char const *zInput = sqlite3_value_text(argv[0]);
72853   unsigned char const *zOld = sqlite3_value_text(argv[1]);
72854   unsigned char const *zNew = sqlite3_value_text(argv[2]);
72855
72856   unsigned const char *z;         /* Pointer to token */
72857   int n;                          /* Length of token z */
72858   int token;                      /* Type of token */
72859
72860   UNUSED_PARAMETER(NotUsed);
72861   for(z=zInput; *z; z=z+n){
72862     n = sqlite3GetToken(z, &token);
72863     if( token==TK_REFERENCES ){
72864       char *zParent;
72865       do {
72866         z += n;
72867         n = sqlite3GetToken(z, &token);
72868       }while( token==TK_SPACE );
72869
72870       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
72871       if( zParent==0 ) break;
72872       sqlite3Dequote(zParent);
72873       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
72874         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"", 
72875             (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
72876         );
72877         sqlite3DbFree(db, zOutput);
72878         zOutput = zOut;
72879         zInput = &z[n];
72880       }
72881       sqlite3DbFree(db, zParent);
72882     }
72883   }
72884
72885   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), 
72886   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
72887   sqlite3DbFree(db, zOutput);
72888 }
72889 #endif
72890
72891 #ifndef SQLITE_OMIT_TRIGGER
72892 /* This function is used by SQL generated to implement the
72893 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
72894 ** statement. The second is a table name. The table name in the CREATE 
72895 ** TRIGGER statement is replaced with the third argument and the result 
72896 ** returned. This is analagous to renameTableFunc() above, except for CREATE
72897 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
72898 */
72899 static void renameTriggerFunc(
72900   sqlite3_context *context,
72901   int NotUsed,
72902   sqlite3_value **argv
72903 ){
72904   unsigned char const *zSql = sqlite3_value_text(argv[0]);
72905   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
72906
72907   int token;
72908   Token tname;
72909   int dist = 3;
72910   unsigned char const *zCsr = zSql;
72911   int len = 0;
72912   char *zRet;
72913   sqlite3 *db = sqlite3_context_db_handle(context);
72914
72915   UNUSED_PARAMETER(NotUsed);
72916
72917   /* The principle used to locate the table name in the CREATE TRIGGER 
72918   ** statement is that the table name is the first token that is immediatedly
72919   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
72920   ** of TK_WHEN, TK_BEGIN or TK_FOR.
72921   */
72922   if( zSql ){
72923     do {
72924
72925       if( !*zCsr ){
72926         /* Ran out of input before finding the table name. Return NULL. */
72927         return;
72928       }
72929
72930       /* Store the token that zCsr points to in tname. */
72931       tname.z = (char*)zCsr;
72932       tname.n = len;
72933
72934       /* Advance zCsr to the next token. Store that token type in 'token',
72935       ** and its length in 'len' (to be used next iteration of this loop).
72936       */
72937       do {
72938         zCsr += len;
72939         len = sqlite3GetToken(zCsr, &token);
72940       }while( token==TK_SPACE );
72941       assert( len>0 );
72942
72943       /* Variable 'dist' stores the number of tokens read since the most
72944       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
72945       ** token is read and 'dist' equals 2, the condition stated above
72946       ** to be met.
72947       **
72948       ** Note that ON cannot be a database, table or column name, so
72949       ** there is no need to worry about syntax like 
72950       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
72951       */
72952       dist++;
72953       if( token==TK_DOT || token==TK_ON ){
72954         dist = 0;
72955       }
72956     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
72957
72958     /* Variable tname now contains the token that is the old table-name
72959     ** in the CREATE TRIGGER statement.
72960     */
72961     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
72962        zTableName, tname.z+tname.n);
72963     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
72964   }
72965 }
72966 #endif   /* !SQLITE_OMIT_TRIGGER */
72967
72968 /*
72969 ** Register built-in functions used to help implement ALTER TABLE
72970 */
72971 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
72972   static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
72973     FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
72974 #ifndef SQLITE_OMIT_TRIGGER
72975     FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
72976 #endif
72977 #ifndef SQLITE_OMIT_FOREIGN_KEY
72978     FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
72979 #endif
72980   };
72981   int i;
72982   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
72983   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
72984
72985   for(i=0; i<ArraySize(aAlterTableFuncs); i++){
72986     sqlite3FuncDefInsert(pHash, &aFunc[i]);
72987   }
72988 }
72989
72990 /*
72991 ** This function is used to create the text of expressions of the form:
72992 **
72993 **   name=<constant1> OR name=<constant2> OR ...
72994 **
72995 ** If argument zWhere is NULL, then a pointer string containing the text 
72996 ** "name=<constant>" is returned, where <constant> is the quoted version
72997 ** of the string passed as argument zConstant. The returned buffer is
72998 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
72999 ** caller to ensure that it is eventually freed.
73000 **
73001 ** If argument zWhere is not NULL, then the string returned is 
73002 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
73003 ** In this case zWhere is passed to sqlite3DbFree() before returning.
73004 ** 
73005 */
73006 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
73007   char *zNew;
73008   if( !zWhere ){
73009     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
73010   }else{
73011     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
73012     sqlite3DbFree(db, zWhere);
73013   }
73014   return zNew;
73015 }
73016
73017 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
73018 /*
73019 ** Generate the text of a WHERE expression which can be used to select all
73020 ** tables that have foreign key constraints that refer to table pTab (i.e.
73021 ** constraints for which pTab is the parent table) from the sqlite_master
73022 ** table.
73023 */
73024 static char *whereForeignKeys(Parse *pParse, Table *pTab){
73025   FKey *p;
73026   char *zWhere = 0;
73027   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
73028     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
73029   }
73030   return zWhere;
73031 }
73032 #endif
73033
73034 /*
73035 ** Generate the text of a WHERE expression which can be used to select all
73036 ** temporary triggers on table pTab from the sqlite_temp_master table. If
73037 ** table pTab has no temporary triggers, or is itself stored in the 
73038 ** temporary database, NULL is returned.
73039 */
73040 static char *whereTempTriggers(Parse *pParse, Table *pTab){
73041   Trigger *pTrig;
73042   char *zWhere = 0;
73043   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
73044
73045   /* If the table is not located in the temp-db (in which case NULL is 
73046   ** returned, loop through the tables list of triggers. For each trigger
73047   ** that is not part of the temp-db schema, add a clause to the WHERE 
73048   ** expression being built up in zWhere.
73049   */
73050   if( pTab->pSchema!=pTempSchema ){
73051     sqlite3 *db = pParse->db;
73052     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
73053       if( pTrig->pSchema==pTempSchema ){
73054         zWhere = whereOrName(db, zWhere, pTrig->zName);
73055       }
73056     }
73057   }
73058   if( zWhere ){
73059     char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
73060     sqlite3DbFree(pParse->db, zWhere);
73061     zWhere = zNew;
73062   }
73063   return zWhere;
73064 }
73065
73066 /*
73067 ** Generate code to drop and reload the internal representation of table
73068 ** pTab from the database, including triggers and temporary triggers.
73069 ** Argument zName is the name of the table in the database schema at
73070 ** the time the generated code is executed. This can be different from
73071 ** pTab->zName if this function is being called to code part of an 
73072 ** "ALTER TABLE RENAME TO" statement.
73073 */
73074 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
73075   Vdbe *v;
73076   char *zWhere;
73077   int iDb;                   /* Index of database containing pTab */
73078 #ifndef SQLITE_OMIT_TRIGGER
73079   Trigger *pTrig;
73080 #endif
73081
73082   v = sqlite3GetVdbe(pParse);
73083   if( NEVER(v==0) ) return;
73084   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
73085   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
73086   assert( iDb>=0 );
73087
73088 #ifndef SQLITE_OMIT_TRIGGER
73089   /* Drop any table triggers from the internal schema. */
73090   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
73091     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
73092     assert( iTrigDb==iDb || iTrigDb==1 );
73093     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
73094   }
73095 #endif
73096
73097   /* Drop the table and index from the internal schema.  */
73098   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
73099
73100   /* Reload the table, index and permanent trigger schemas. */
73101   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
73102   if( !zWhere ) return;
73103   sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
73104
73105 #ifndef SQLITE_OMIT_TRIGGER
73106   /* Now, if the table is not stored in the temp database, reload any temp 
73107   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
73108   */
73109   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
73110     sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
73111   }
73112 #endif
73113 }
73114
73115 /*
73116 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
73117 ** command. 
73118 */
73119 SQLITE_PRIVATE void sqlite3AlterRenameTable(
73120   Parse *pParse,            /* Parser context. */
73121   SrcList *pSrc,            /* The table to rename. */
73122   Token *pName              /* The new table name. */
73123 ){
73124   int iDb;                  /* Database that contains the table */
73125   char *zDb;                /* Name of database iDb */
73126   Table *pTab;              /* Table being renamed */
73127   char *zName = 0;          /* NULL-terminated version of pName */ 
73128   sqlite3 *db = pParse->db; /* Database connection */
73129   int nTabName;             /* Number of UTF-8 characters in zTabName */
73130   const char *zTabName;     /* Original name of the table */
73131   Vdbe *v;
73132 #ifndef SQLITE_OMIT_TRIGGER
73133   char *zWhere = 0;         /* Where clause to locate temp triggers */
73134 #endif
73135   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
73136   int savedDbFlags;         /* Saved value of db->flags */
73137
73138   savedDbFlags = db->flags;  
73139   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
73140   assert( pSrc->nSrc==1 );
73141   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
73142
73143   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
73144   if( !pTab ) goto exit_rename_table;
73145   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
73146   zDb = db->aDb[iDb].zName;
73147   db->flags |= SQLITE_PreferBuiltin;
73148
73149   /* Get a NULL terminated version of the new table name. */
73150   zName = sqlite3NameFromToken(db, pName);
73151   if( !zName ) goto exit_rename_table;
73152
73153   /* Check that a table or index named 'zName' does not already exist
73154   ** in database iDb. If so, this is an error.
73155   */
73156   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
73157     sqlite3ErrorMsg(pParse, 
73158         "there is already another table or index with this name: %s", zName);
73159     goto exit_rename_table;
73160   }
73161
73162   /* Make sure it is not a system table being altered, or a reserved name
73163   ** that the table is being renamed to.
73164   */
73165   if( sqlite3Strlen30(pTab->zName)>6 
73166    && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
73167   ){
73168     sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
73169     goto exit_rename_table;
73170   }
73171   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
73172     goto exit_rename_table;
73173   }
73174
73175 #ifndef SQLITE_OMIT_VIEW
73176   if( pTab->pSelect ){
73177     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
73178     goto exit_rename_table;
73179   }
73180 #endif
73181
73182 #ifndef SQLITE_OMIT_AUTHORIZATION
73183   /* Invoke the authorization callback. */
73184   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
73185     goto exit_rename_table;
73186   }
73187 #endif
73188
73189 #ifndef SQLITE_OMIT_VIRTUALTABLE
73190   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
73191     goto exit_rename_table;
73192   }
73193   if( IsVirtual(pTab) ){
73194     pVTab = sqlite3GetVTable(db, pTab);
73195     if( pVTab->pVtab->pModule->xRename==0 ){
73196       pVTab = 0;
73197     }
73198   }
73199 #endif
73200
73201   /* Begin a transaction and code the VerifyCookie for database iDb. 
73202   ** Then modify the schema cookie (since the ALTER TABLE modifies the
73203   ** schema). Open a statement transaction if the table is a virtual
73204   ** table.
73205   */
73206   v = sqlite3GetVdbe(pParse);
73207   if( v==0 ){
73208     goto exit_rename_table;
73209   }
73210   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
73211   sqlite3ChangeCookie(pParse, iDb);
73212
73213   /* If this is a virtual table, invoke the xRename() function if
73214   ** one is defined. The xRename() callback will modify the names
73215   ** of any resources used by the v-table implementation (including other
73216   ** SQLite tables) that are identified by the name of the virtual table.
73217   */
73218 #ifndef SQLITE_OMIT_VIRTUALTABLE
73219   if( pVTab ){
73220     int i = ++pParse->nMem;
73221     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
73222     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
73223     sqlite3MayAbort(pParse);
73224   }
73225 #endif
73226
73227   /* figure out how many UTF-8 characters are in zName */
73228   zTabName = pTab->zName;
73229   nTabName = sqlite3Utf8CharLen(zTabName, -1);
73230
73231 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
73232   if( db->flags&SQLITE_ForeignKeys ){
73233     /* If foreign-key support is enabled, rewrite the CREATE TABLE 
73234     ** statements corresponding to all child tables of foreign key constraints
73235     ** for which the renamed table is the parent table.  */
73236     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
73237       sqlite3NestedParse(pParse, 
73238           "UPDATE \"%w\".%s SET "
73239               "sql = sqlite_rename_parent(sql, %Q, %Q) "
73240               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
73241       sqlite3DbFree(db, zWhere);
73242     }
73243   }
73244 #endif
73245
73246   /* Modify the sqlite_master table to use the new table name. */
73247   sqlite3NestedParse(pParse,
73248       "UPDATE %Q.%s SET "
73249 #ifdef SQLITE_OMIT_TRIGGER
73250           "sql = sqlite_rename_table(sql, %Q), "
73251 #else
73252           "sql = CASE "
73253             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
73254             "ELSE sqlite_rename_table(sql, %Q) END, "
73255 #endif
73256           "tbl_name = %Q, "
73257           "name = CASE "
73258             "WHEN type='table' THEN %Q "
73259             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
73260              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
73261             "ELSE name END "
73262       "WHERE tbl_name=%Q AND "
73263           "(type='table' OR type='index' OR type='trigger');", 
73264       zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
73265 #ifndef SQLITE_OMIT_TRIGGER
73266       zName,
73267 #endif
73268       zName, nTabName, zTabName
73269   );
73270
73271 #ifndef SQLITE_OMIT_AUTOINCREMENT
73272   /* If the sqlite_sequence table exists in this database, then update 
73273   ** it with the new table name.
73274   */
73275   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
73276     sqlite3NestedParse(pParse,
73277         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
73278         zDb, zName, pTab->zName);
73279   }
73280 #endif
73281
73282 #ifndef SQLITE_OMIT_TRIGGER
73283   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
73284   ** table. Don't do this if the table being ALTERed is itself located in
73285   ** the temp database.
73286   */
73287   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
73288     sqlite3NestedParse(pParse, 
73289         "UPDATE sqlite_temp_master SET "
73290             "sql = sqlite_rename_trigger(sql, %Q), "
73291             "tbl_name = %Q "
73292             "WHERE %s;", zName, zName, zWhere);
73293     sqlite3DbFree(db, zWhere);
73294   }
73295 #endif
73296
73297 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
73298   if( db->flags&SQLITE_ForeignKeys ){
73299     FKey *p;
73300     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
73301       Table *pFrom = p->pFrom;
73302       if( pFrom!=pTab ){
73303         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
73304       }
73305     }
73306   }
73307 #endif
73308
73309   /* Drop and reload the internal table schema. */
73310   reloadTableSchema(pParse, pTab, zName);
73311
73312 exit_rename_table:
73313   sqlite3SrcListDelete(db, pSrc);
73314   sqlite3DbFree(db, zName);
73315   db->flags = savedDbFlags;
73316 }
73317
73318
73319 /*
73320 ** Generate code to make sure the file format number is at least minFormat.
73321 ** The generated code will increase the file format number if necessary.
73322 */
73323 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
73324   Vdbe *v;
73325   v = sqlite3GetVdbe(pParse);
73326   /* The VDBE should have been allocated before this routine is called.
73327   ** If that allocation failed, we would have quit before reaching this
73328   ** point */
73329   if( ALWAYS(v) ){
73330     int r1 = sqlite3GetTempReg(pParse);
73331     int r2 = sqlite3GetTempReg(pParse);
73332     int j1;
73333     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
73334     sqlite3VdbeUsesBtree(v, iDb);
73335     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
73336     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
73337     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
73338     sqlite3VdbeJumpHere(v, j1);
73339     sqlite3ReleaseTempReg(pParse, r1);
73340     sqlite3ReleaseTempReg(pParse, r2);
73341   }
73342 }
73343
73344 /*
73345 ** This function is called after an "ALTER TABLE ... ADD" statement
73346 ** has been parsed. Argument pColDef contains the text of the new
73347 ** column definition.
73348 **
73349 ** The Table structure pParse->pNewTable was extended to include
73350 ** the new column during parsing.
73351 */
73352 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
73353   Table *pNew;              /* Copy of pParse->pNewTable */
73354   Table *pTab;              /* Table being altered */
73355   int iDb;                  /* Database number */
73356   const char *zDb;          /* Database name */
73357   const char *zTab;         /* Table name */
73358   char *zCol;               /* Null-terminated column definition */
73359   Column *pCol;             /* The new column */
73360   Expr *pDflt;              /* Default value for the new column */
73361   sqlite3 *db;              /* The database connection; */
73362
73363   db = pParse->db;
73364   if( pParse->nErr || db->mallocFailed ) return;
73365   pNew = pParse->pNewTable;
73366   assert( pNew );
73367
73368   assert( sqlite3BtreeHoldsAllMutexes(db) );
73369   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
73370   zDb = db->aDb[iDb].zName;
73371   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
73372   pCol = &pNew->aCol[pNew->nCol-1];
73373   pDflt = pCol->pDflt;
73374   pTab = sqlite3FindTable(db, zTab, zDb);
73375   assert( pTab );
73376
73377 #ifndef SQLITE_OMIT_AUTHORIZATION
73378   /* Invoke the authorization callback. */
73379   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
73380     return;
73381   }
73382 #endif
73383
73384   /* If the default value for the new column was specified with a 
73385   ** literal NULL, then set pDflt to 0. This simplifies checking
73386   ** for an SQL NULL default below.
73387   */
73388   if( pDflt && pDflt->op==TK_NULL ){
73389     pDflt = 0;
73390   }
73391
73392   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
73393   ** If there is a NOT NULL constraint, then the default value for the
73394   ** column must not be NULL.
73395   */
73396   if( pCol->isPrimKey ){
73397     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
73398     return;
73399   }
73400   if( pNew->pIndex ){
73401     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
73402     return;
73403   }
73404   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
73405     sqlite3ErrorMsg(pParse, 
73406         "Cannot add a REFERENCES column with non-NULL default value");
73407     return;
73408   }
73409   if( pCol->notNull && !pDflt ){
73410     sqlite3ErrorMsg(pParse, 
73411         "Cannot add a NOT NULL column with default value NULL");
73412     return;
73413   }
73414
73415   /* Ensure the default expression is something that sqlite3ValueFromExpr()
73416   ** can handle (i.e. not CURRENT_TIME etc.)
73417   */
73418   if( pDflt ){
73419     sqlite3_value *pVal;
73420     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
73421       db->mallocFailed = 1;
73422       return;
73423     }
73424     if( !pVal ){
73425       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
73426       return;
73427     }
73428     sqlite3ValueFree(pVal);
73429   }
73430
73431   /* Modify the CREATE TABLE statement. */
73432   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
73433   if( zCol ){
73434     char *zEnd = &zCol[pColDef->n-1];
73435     int savedDbFlags = db->flags;
73436     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
73437       *zEnd-- = '\0';
73438     }
73439     db->flags |= SQLITE_PreferBuiltin;
73440     sqlite3NestedParse(pParse, 
73441         "UPDATE \"%w\".%s SET "
73442           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
73443         "WHERE type = 'table' AND name = %Q", 
73444       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
73445       zTab
73446     );
73447     sqlite3DbFree(db, zCol);
73448     db->flags = savedDbFlags;
73449   }
73450
73451   /* If the default value of the new column is NULL, then set the file
73452   ** format to 2. If the default value of the new column is not NULL,
73453   ** the file format becomes 3.
73454   */
73455   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
73456
73457   /* Reload the schema of the modified table. */
73458   reloadTableSchema(pParse, pTab, pTab->zName);
73459 }
73460
73461 /*
73462 ** This function is called by the parser after the table-name in
73463 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
73464 ** pSrc is the full-name of the table being altered.
73465 **
73466 ** This routine makes a (partial) copy of the Table structure
73467 ** for the table being altered and sets Parse.pNewTable to point
73468 ** to it. Routines called by the parser as the column definition
73469 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
73470 ** the copy. The copy of the Table structure is deleted by tokenize.c 
73471 ** after parsing is finished.
73472 **
73473 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
73474 ** coding the "ALTER TABLE ... ADD" statement.
73475 */
73476 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
73477   Table *pNew;
73478   Table *pTab;
73479   Vdbe *v;
73480   int iDb;
73481   int i;
73482   int nAlloc;
73483   sqlite3 *db = pParse->db;
73484
73485   /* Look up the table being altered. */
73486   assert( pParse->pNewTable==0 );
73487   assert( sqlite3BtreeHoldsAllMutexes(db) );
73488   if( db->mallocFailed ) goto exit_begin_add_column;
73489   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
73490   if( !pTab ) goto exit_begin_add_column;
73491
73492 #ifndef SQLITE_OMIT_VIRTUALTABLE
73493   if( IsVirtual(pTab) ){
73494     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
73495     goto exit_begin_add_column;
73496   }
73497 #endif
73498
73499   /* Make sure this is not an attempt to ALTER a view. */
73500   if( pTab->pSelect ){
73501     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
73502     goto exit_begin_add_column;
73503   }
73504
73505   assert( pTab->addColOffset>0 );
73506   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
73507
73508   /* Put a copy of the Table struct in Parse.pNewTable for the
73509   ** sqlite3AddColumn() function and friends to modify.  But modify
73510   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
73511   ** prefix, we insure that the name will not collide with an existing
73512   ** table because user table are not allowed to have the "sqlite_"
73513   ** prefix on their name.
73514   */
73515   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
73516   if( !pNew ) goto exit_begin_add_column;
73517   pParse->pNewTable = pNew;
73518   pNew->nRef = 1;
73519   pNew->nCol = pTab->nCol;
73520   assert( pNew->nCol>0 );
73521   nAlloc = (((pNew->nCol-1)/8)*8)+8;
73522   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
73523   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
73524   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
73525   if( !pNew->aCol || !pNew->zName ){
73526     db->mallocFailed = 1;
73527     goto exit_begin_add_column;
73528   }
73529   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
73530   for(i=0; i<pNew->nCol; i++){
73531     Column *pCol = &pNew->aCol[i];
73532     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
73533     pCol->zColl = 0;
73534     pCol->zType = 0;
73535     pCol->pDflt = 0;
73536     pCol->zDflt = 0;
73537   }
73538   pNew->pSchema = db->aDb[iDb].pSchema;
73539   pNew->addColOffset = pTab->addColOffset;
73540   pNew->nRef = 1;
73541
73542   /* Begin a transaction and increment the schema cookie.  */
73543   sqlite3BeginWriteOperation(pParse, 0, iDb);
73544   v = sqlite3GetVdbe(pParse);
73545   if( !v ) goto exit_begin_add_column;
73546   sqlite3ChangeCookie(pParse, iDb);
73547
73548 exit_begin_add_column:
73549   sqlite3SrcListDelete(db, pSrc);
73550   return;
73551 }
73552 #endif  /* SQLITE_ALTER_TABLE */
73553
73554 /************** End of alter.c ***********************************************/
73555 /************** Begin file analyze.c *****************************************/
73556 /*
73557 ** 2005 July 8
73558 **
73559 ** The author disclaims copyright to this source code.  In place of
73560 ** a legal notice, here is a blessing:
73561 **
73562 **    May you do good and not evil.
73563 **    May you find forgiveness for yourself and forgive others.
73564 **    May you share freely, never taking more than you give.
73565 **
73566 *************************************************************************
73567 ** This file contains code associated with the ANALYZE command.
73568 */
73569 #ifndef SQLITE_OMIT_ANALYZE
73570
73571 /*
73572 ** This routine generates code that opens the sqlite_stat1 table for
73573 ** writing with cursor iStatCur. If the library was built with the
73574 ** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
73575 ** opened for writing using cursor (iStatCur+1)
73576 **
73577 ** If the sqlite_stat1 tables does not previously exist, it is created.
73578 ** Similarly, if the sqlite_stat2 table does not exist and the library
73579 ** is compiled with SQLITE_ENABLE_STAT2 defined, it is created. 
73580 **
73581 ** Argument zWhere may be a pointer to a buffer containing a table name,
73582 ** or it may be a NULL pointer. If it is not NULL, then all entries in
73583 ** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
73584 ** with the named table are deleted. If zWhere==0, then code is generated
73585 ** to delete all stat table entries.
73586 */
73587 static void openStatTable(
73588   Parse *pParse,          /* Parsing context */
73589   int iDb,                /* The database we are looking in */
73590   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
73591   const char *zWhere      /* Delete entries associated with this table */
73592 ){
73593   static const struct {
73594     const char *zName;
73595     const char *zCols;
73596   } aTable[] = {
73597     { "sqlite_stat1", "tbl,idx,stat" },
73598 #ifdef SQLITE_ENABLE_STAT2
73599     { "sqlite_stat2", "tbl,idx,sampleno,sample" },
73600 #endif
73601   };
73602
73603   int aRoot[] = {0, 0};
73604   u8 aCreateTbl[] = {0, 0};
73605
73606   int i;
73607   sqlite3 *db = pParse->db;
73608   Db *pDb;
73609   Vdbe *v = sqlite3GetVdbe(pParse);
73610   if( v==0 ) return;
73611   assert( sqlite3BtreeHoldsAllMutexes(db) );
73612   assert( sqlite3VdbeDb(v)==db );
73613   pDb = &db->aDb[iDb];
73614
73615   for(i=0; i<ArraySize(aTable); i++){
73616     const char *zTab = aTable[i].zName;
73617     Table *pStat;
73618     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
73619       /* The sqlite_stat[12] table does not exist. Create it. Note that a 
73620       ** side-effect of the CREATE TABLE statement is to leave the rootpage 
73621       ** of the new table in register pParse->regRoot. This is important 
73622       ** because the OpenWrite opcode below will be needing it. */
73623       sqlite3NestedParse(pParse,
73624           "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
73625       );
73626       aRoot[i] = pParse->regRoot;
73627       aCreateTbl[i] = 1;
73628     }else{
73629       /* The table already exists. If zWhere is not NULL, delete all entries 
73630       ** associated with the table zWhere. If zWhere is NULL, delete the
73631       ** entire contents of the table. */
73632       aRoot[i] = pStat->tnum;
73633       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
73634       if( zWhere ){
73635         sqlite3NestedParse(pParse,
73636            "DELETE FROM %Q.%s WHERE tbl=%Q", pDb->zName, zTab, zWhere
73637         );
73638       }else{
73639         /* The sqlite_stat[12] table already exists.  Delete all rows. */
73640         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
73641       }
73642     }
73643   }
73644
73645   /* Open the sqlite_stat[12] tables for writing. */
73646   for(i=0; i<ArraySize(aTable); i++){
73647     sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
73648     sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
73649     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
73650   }
73651 }
73652
73653 /*
73654 ** Generate code to do an analysis of all indices associated with
73655 ** a single table.
73656 */
73657 static void analyzeOneTable(
73658   Parse *pParse,   /* Parser context */
73659   Table *pTab,     /* Table whose indices are to be analyzed */
73660   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
73661   int iMem         /* Available memory locations begin here */
73662 ){
73663   sqlite3 *db = pParse->db;    /* Database handle */
73664   Index *pIdx;                 /* An index to being analyzed */
73665   int iIdxCur;                 /* Cursor open on index being analyzed */
73666   Vdbe *v;                     /* The virtual machine being built up */
73667   int i;                       /* Loop counter */
73668   int topOfLoop;               /* The top of the loop */
73669   int endOfLoop;               /* The end of the loop */
73670   int addr = 0;                /* The address of an instruction */
73671   int jZeroRows = 0;           /* Jump from here if number of rows is zero */
73672   int iDb;                     /* Index of database containing pTab */
73673   int regTabname = iMem++;     /* Register containing table name */
73674   int regIdxname = iMem++;     /* Register containing index name */
73675   int regSampleno = iMem++;    /* Register containing next sample number */
73676   int regCol = iMem++;         /* Content of a column analyzed table */
73677   int regRec = iMem++;         /* Register holding completed record */
73678   int regTemp = iMem++;        /* Temporary use register */
73679   int regRowid = iMem++;       /* Rowid for the inserted record */
73680
73681 #ifdef SQLITE_ENABLE_STAT2
73682   int regTemp2 = iMem++;       /* Temporary use register */
73683   int regSamplerecno = iMem++; /* Index of next sample to record */
73684   int regRecno = iMem++;       /* Current sample index */
73685   int regLast = iMem++;        /* Index of last sample to record */
73686   int regFirst = iMem++;       /* Index of first sample to record */
73687 #endif
73688
73689   v = sqlite3GetVdbe(pParse);
73690   if( v==0 || NEVER(pTab==0) ){
73691     return;
73692   }
73693   if( pTab->tnum==0 ){
73694     /* Do not gather statistics on views or virtual tables */
73695     return;
73696   }
73697   if( memcmp(pTab->zName, "sqlite_", 7)==0 ){
73698     /* Do not gather statistics on system tables */
73699     return;
73700   }
73701   assert( sqlite3BtreeHoldsAllMutexes(db) );
73702   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
73703   assert( iDb>=0 );
73704 #ifndef SQLITE_OMIT_AUTHORIZATION
73705   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
73706       db->aDb[iDb].zName ) ){
73707     return;
73708   }
73709 #endif
73710
73711   /* Establish a read-lock on the table at the shared-cache level. */
73712   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
73713
73714   iIdxCur = pParse->nTab++;
73715   sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
73716   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
73717     int nCol = pIdx->nColumn;
73718     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
73719
73720     if( iMem+1+(nCol*2)>pParse->nMem ){
73721       pParse->nMem = iMem+1+(nCol*2);
73722     }
73723
73724     /* Open a cursor to the index to be analyzed. */
73725     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
73726     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
73727         (char *)pKey, P4_KEYINFO_HANDOFF);
73728     VdbeComment((v, "%s", pIdx->zName));
73729
73730     /* Populate the register containing the index name. */
73731     sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
73732
73733 #ifdef SQLITE_ENABLE_STAT2
73734
73735     /* If this iteration of the loop is generating code to analyze the
73736     ** first index in the pTab->pIndex list, then register regLast has
73737     ** not been populated. In this case populate it now.  */
73738     if( pTab->pIndex==pIdx ){
73739       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno);
73740       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2-1, regTemp);
73741       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2, regTemp2);
73742
73743       sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regLast);
73744       sqlite3VdbeAddOp2(v, OP_Null, 0, regFirst);
73745       addr = sqlite3VdbeAddOp3(v, OP_Lt, regSamplerecno, 0, regLast);
73746       sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regLast, regFirst);
73747       sqlite3VdbeAddOp3(v, OP_Multiply, regLast, regTemp, regLast);
73748       sqlite3VdbeAddOp2(v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES*2-2);
73749       sqlite3VdbeAddOp3(v, OP_Divide,  regTemp2, regLast, regLast);
73750       sqlite3VdbeJumpHere(v, addr);
73751     }
73752
73753     /* Zero the regSampleno and regRecno registers. */
73754     sqlite3VdbeAddOp2(v, OP_Integer, 0, regSampleno);
73755     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRecno);
73756     sqlite3VdbeAddOp2(v, OP_Copy, regFirst, regSamplerecno);
73757 #endif
73758
73759     /* The block of memory cells initialized here is used as follows.
73760     **
73761     **    iMem:                
73762     **        The total number of rows in the table.
73763     **
73764     **    iMem+1 .. iMem+nCol: 
73765     **        Number of distinct entries in index considering the 
73766     **        left-most N columns only, where N is between 1 and nCol, 
73767     **        inclusive.
73768     **
73769     **    iMem+nCol+1 .. Mem+2*nCol:  
73770     **        Previous value of indexed columns, from left to right.
73771     **
73772     ** Cells iMem through iMem+nCol are initialized to 0. The others are 
73773     ** initialized to contain an SQL NULL.
73774     */
73775     for(i=0; i<=nCol; i++){
73776       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
73777     }
73778     for(i=0; i<nCol; i++){
73779       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
73780     }
73781
73782     /* Start the analysis loop. This loop runs through all the entries in
73783     ** the index b-tree.  */
73784     endOfLoop = sqlite3VdbeMakeLabel(v);
73785     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
73786     topOfLoop = sqlite3VdbeCurrentAddr(v);
73787     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
73788
73789     for(i=0; i<nCol; i++){
73790       CollSeq *pColl;
73791       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
73792       if( i==0 ){
73793 #ifdef SQLITE_ENABLE_STAT2
73794         /* Check if the record that cursor iIdxCur points to contains a
73795         ** value that should be stored in the sqlite_stat2 table. If so,
73796         ** store it.  */
73797         int ne = sqlite3VdbeAddOp3(v, OP_Ne, regRecno, 0, regSamplerecno);
73798         assert( regTabname+1==regIdxname 
73799              && regTabname+2==regSampleno
73800              && regTabname+3==regCol
73801         );
73802         sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
73803         sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0);
73804         sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regRowid);
73805         sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regRowid);
73806
73807         /* Calculate new values for regSamplerecno and regSampleno.
73808         **
73809         **   sampleno = sampleno + 1
73810         **   samplerecno = samplerecno+(remaining records)/(remaining samples)
73811         */
73812         sqlite3VdbeAddOp2(v, OP_AddImm, regSampleno, 1);
73813         sqlite3VdbeAddOp3(v, OP_Subtract, regRecno, regLast, regTemp);
73814         sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
73815         sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2);
73816         sqlite3VdbeAddOp3(v, OP_Subtract, regSampleno, regTemp2, regTemp2);
73817         sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regTemp, regTemp);
73818         sqlite3VdbeAddOp3(v, OP_Add, regSamplerecno, regTemp, regSamplerecno);
73819
73820         sqlite3VdbeJumpHere(v, ne);
73821         sqlite3VdbeAddOp2(v, OP_AddImm, regRecno, 1);
73822 #endif
73823
73824         /* Always record the very first row */
73825         sqlite3VdbeAddOp1(v, OP_IfNot, iMem+1);
73826       }
73827       assert( pIdx->azColl!=0 );
73828       assert( pIdx->azColl[i]!=0 );
73829       pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
73830       sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,
73831                        (char*)pColl, P4_COLLSEQ);
73832       sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
73833     }
73834     if( db->mallocFailed ){
73835       /* If a malloc failure has occurred, then the result of the expression 
73836       ** passed as the second argument to the call to sqlite3VdbeJumpHere() 
73837       ** below may be negative. Which causes an assert() to fail (or an
73838       ** out-of-bounds write if SQLITE_DEBUG is not defined).  */
73839       return;
73840     }
73841     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
73842     for(i=0; i<nCol; i++){
73843       int addr2 = sqlite3VdbeCurrentAddr(v) - (nCol*2);
73844       if( i==0 ){
73845         sqlite3VdbeJumpHere(v, addr2-1);  /* Set jump dest for the OP_IfNot */
73846       }
73847       sqlite3VdbeJumpHere(v, addr2);      /* Set jump dest for the OP_Ne */
73848       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
73849       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
73850     }
73851
73852     /* End of the analysis loop. */
73853     sqlite3VdbeResolveLabel(v, endOfLoop);
73854     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
73855     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
73856
73857     /* Store the results in sqlite_stat1.
73858     **
73859     ** The result is a single row of the sqlite_stat1 table.  The first
73860     ** two columns are the names of the table and index.  The third column
73861     ** is a string composed of a list of integer statistics about the
73862     ** index.  The first integer in the list is the total number of entries
73863     ** in the index.  There is one additional integer in the list for each
73864     ** column of the table.  This additional integer is a guess of how many
73865     ** rows of the table the index will select.  If D is the count of distinct
73866     ** values and K is the total number of rows, then the integer is computed
73867     ** as:
73868     **
73869     **        I = (K+D-1)/D
73870     **
73871     ** If K==0 then no entry is made into the sqlite_stat1 table.  
73872     ** If K>0 then it is always the case the D>0 so division by zero
73873     ** is never possible.
73874     */
73875     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
73876     if( jZeroRows==0 ){
73877       jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
73878     }
73879     for(i=0; i<nCol; i++){
73880       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
73881       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
73882       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
73883       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
73884       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
73885       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
73886       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
73887     }
73888     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
73889     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
73890     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
73891     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
73892   }
73893
73894   /* If the table has no indices, create a single sqlite_stat1 entry
73895   ** containing NULL as the index name and the row count as the content.
73896   */
73897   if( pTab->pIndex==0 ){
73898     sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
73899     VdbeComment((v, "%s", pTab->zName));
73900     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regSampleno);
73901     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
73902   }else{
73903     assert( jZeroRows>0 );
73904     addr = sqlite3VdbeAddOp0(v, OP_Goto);
73905     sqlite3VdbeJumpHere(v, jZeroRows);
73906   }
73907   sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
73908   sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
73909   sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
73910   sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
73911   sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
73912   if( pParse->nMem<regRec ) pParse->nMem = regRec;
73913   if( jZeroRows ){
73914     sqlite3VdbeJumpHere(v, addr);
73915   }
73916 }
73917
73918 /*
73919 ** Generate code that will cause the most recent index analysis to
73920 ** be loaded into internal hash tables where is can be used.
73921 */
73922 static void loadAnalysis(Parse *pParse, int iDb){
73923   Vdbe *v = sqlite3GetVdbe(pParse);
73924   if( v ){
73925     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
73926   }
73927 }
73928
73929 /*
73930 ** Generate code that will do an analysis of an entire database
73931 */
73932 static void analyzeDatabase(Parse *pParse, int iDb){
73933   sqlite3 *db = pParse->db;
73934   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
73935   HashElem *k;
73936   int iStatCur;
73937   int iMem;
73938
73939   sqlite3BeginWriteOperation(pParse, 0, iDb);
73940   iStatCur = pParse->nTab;
73941   pParse->nTab += 2;
73942   openStatTable(pParse, iDb, iStatCur, 0);
73943   iMem = pParse->nMem+1;
73944   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
73945     Table *pTab = (Table*)sqliteHashData(k);
73946     analyzeOneTable(pParse, pTab, iStatCur, iMem);
73947   }
73948   loadAnalysis(pParse, iDb);
73949 }
73950
73951 /*
73952 ** Generate code that will do an analysis of a single table in
73953 ** a database.
73954 */
73955 static void analyzeTable(Parse *pParse, Table *pTab){
73956   int iDb;
73957   int iStatCur;
73958
73959   assert( pTab!=0 );
73960   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
73961   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
73962   sqlite3BeginWriteOperation(pParse, 0, iDb);
73963   iStatCur = pParse->nTab;
73964   pParse->nTab += 2;
73965   openStatTable(pParse, iDb, iStatCur, pTab->zName);
73966   analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1);
73967   loadAnalysis(pParse, iDb);
73968 }
73969
73970 /*
73971 ** Generate code for the ANALYZE command.  The parser calls this routine
73972 ** when it recognizes an ANALYZE command.
73973 **
73974 **        ANALYZE                            -- 1
73975 **        ANALYZE  <database>                -- 2
73976 **        ANALYZE  ?<database>.?<tablename>  -- 3
73977 **
73978 ** Form 1 causes all indices in all attached databases to be analyzed.
73979 ** Form 2 analyzes all indices the single database named.
73980 ** Form 3 analyzes all indices associated with the named table.
73981 */
73982 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
73983   sqlite3 *db = pParse->db;
73984   int iDb;
73985   int i;
73986   char *z, *zDb;
73987   Table *pTab;
73988   Token *pTableName;
73989
73990   /* Read the database schema. If an error occurs, leave an error message
73991   ** and code in pParse and return NULL. */
73992   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
73993   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
73994     return;
73995   }
73996
73997   assert( pName2!=0 || pName1==0 );
73998   if( pName1==0 ){
73999     /* Form 1:  Analyze everything */
74000     for(i=0; i<db->nDb; i++){
74001       if( i==1 ) continue;  /* Do not analyze the TEMP database */
74002       analyzeDatabase(pParse, i);
74003     }
74004   }else if( pName2->n==0 ){
74005     /* Form 2:  Analyze the database or table named */
74006     iDb = sqlite3FindDb(db, pName1);
74007     if( iDb>=0 ){
74008       analyzeDatabase(pParse, iDb);
74009     }else{
74010       z = sqlite3NameFromToken(db, pName1);
74011       if( z ){
74012         pTab = sqlite3LocateTable(pParse, 0, z, 0);
74013         sqlite3DbFree(db, z);
74014         if( pTab ){
74015           analyzeTable(pParse, pTab);
74016         }
74017       }
74018     }
74019   }else{
74020     /* Form 3: Analyze the fully qualified table name */
74021     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
74022     if( iDb>=0 ){
74023       zDb = db->aDb[iDb].zName;
74024       z = sqlite3NameFromToken(db, pTableName);
74025       if( z ){
74026         pTab = sqlite3LocateTable(pParse, 0, z, zDb);
74027         sqlite3DbFree(db, z);
74028         if( pTab ){
74029           analyzeTable(pParse, pTab);
74030         }
74031       }
74032     }   
74033   }
74034 }
74035
74036 /*
74037 ** Used to pass information from the analyzer reader through to the
74038 ** callback routine.
74039 */
74040 typedef struct analysisInfo analysisInfo;
74041 struct analysisInfo {
74042   sqlite3 *db;
74043   const char *zDatabase;
74044 };
74045
74046 /*
74047 ** This callback is invoked once for each index when reading the
74048 ** sqlite_stat1 table.  
74049 **
74050 **     argv[0] = name of the table
74051 **     argv[1] = name of the index (might be NULL)
74052 **     argv[2] = results of analysis - on integer for each column
74053 **
74054 ** Entries for which argv[1]==NULL simply record the number of rows in
74055 ** the table.
74056 */
74057 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
74058   analysisInfo *pInfo = (analysisInfo*)pData;
74059   Index *pIndex;
74060   Table *pTable;
74061   int i, c, n;
74062   unsigned int v;
74063   const char *z;
74064
74065   assert( argc==3 );
74066   UNUSED_PARAMETER2(NotUsed, argc);
74067
74068   if( argv==0 || argv[0]==0 || argv[2]==0 ){
74069     return 0;
74070   }
74071   pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
74072   if( pTable==0 ){
74073     return 0;
74074   }
74075   if( argv[1] ){
74076     pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
74077   }else{
74078     pIndex = 0;
74079   }
74080   n = pIndex ? pIndex->nColumn : 0;
74081   z = argv[2];
74082   for(i=0; *z && i<=n; i++){
74083     v = 0;
74084     while( (c=z[0])>='0' && c<='9' ){
74085       v = v*10 + c - '0';
74086       z++;
74087     }
74088     if( i==0 ) pTable->nRowEst = v;
74089     if( pIndex==0 ) break;
74090     pIndex->aiRowEst[i] = v;
74091     if( *z==' ' ) z++;
74092   }
74093   return 0;
74094 }
74095
74096 /*
74097 ** If the Index.aSample variable is not NULL, delete the aSample[] array
74098 ** and its contents.
74099 */
74100 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
74101 #ifdef SQLITE_ENABLE_STAT2
74102   if( pIdx->aSample ){
74103     int j;
74104     for(j=0; j<SQLITE_INDEX_SAMPLES; j++){
74105       IndexSample *p = &pIdx->aSample[j];
74106       if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
74107         sqlite3DbFree(db, p->u.z);
74108       }
74109     }
74110     sqlite3DbFree(db, pIdx->aSample);
74111   }
74112 #else
74113   UNUSED_PARAMETER(db);
74114   UNUSED_PARAMETER(pIdx);
74115 #endif
74116 }
74117
74118 /*
74119 ** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
74120 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
74121 ** arrays. The contents of sqlite_stat2 are used to populate the
74122 ** Index.aSample[] arrays.
74123 **
74124 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
74125 ** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined 
74126 ** during compilation and the sqlite_stat2 table is present, no data is 
74127 ** read from it.
74128 **
74129 ** If SQLITE_ENABLE_STAT2 was defined during compilation and the 
74130 ** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
74131 ** returned. However, in this case, data is read from the sqlite_stat1
74132 ** table (if it is present) before returning.
74133 **
74134 ** If an OOM error occurs, this function always sets db->mallocFailed.
74135 ** This means if the caller does not care about other errors, the return
74136 ** code may be ignored.
74137 */
74138 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
74139   analysisInfo sInfo;
74140   HashElem *i;
74141   char *zSql;
74142   int rc;
74143
74144   assert( iDb>=0 && iDb<db->nDb );
74145   assert( db->aDb[iDb].pBt!=0 );
74146   assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
74147
74148   /* Clear any prior statistics */
74149   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
74150     Index *pIdx = sqliteHashData(i);
74151     sqlite3DefaultRowEst(pIdx);
74152     sqlite3DeleteIndexSamples(db, pIdx);
74153     pIdx->aSample = 0;
74154   }
74155
74156   /* Check to make sure the sqlite_stat1 table exists */
74157   sInfo.db = db;
74158   sInfo.zDatabase = db->aDb[iDb].zName;
74159   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
74160     return SQLITE_ERROR;
74161   }
74162
74163   /* Load new statistics out of the sqlite_stat1 table */
74164   zSql = sqlite3MPrintf(db, 
74165       "SELECT tbl, idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
74166   if( zSql==0 ){
74167     rc = SQLITE_NOMEM;
74168   }else{
74169     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
74170     sqlite3DbFree(db, zSql);
74171   }
74172
74173
74174   /* Load the statistics from the sqlite_stat2 table. */
74175 #ifdef SQLITE_ENABLE_STAT2
74176   if( rc==SQLITE_OK && !sqlite3FindTable(db, "sqlite_stat2", sInfo.zDatabase) ){
74177     rc = SQLITE_ERROR;
74178   }
74179   if( rc==SQLITE_OK ){
74180     sqlite3_stmt *pStmt = 0;
74181
74182     zSql = sqlite3MPrintf(db, 
74183         "SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase);
74184     if( !zSql ){
74185       rc = SQLITE_NOMEM;
74186     }else{
74187       rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
74188       sqlite3DbFree(db, zSql);
74189     }
74190
74191     if( rc==SQLITE_OK ){
74192       while( sqlite3_step(pStmt)==SQLITE_ROW ){
74193         char *zIndex;   /* Index name */
74194         Index *pIdx;    /* Pointer to the index object */
74195
74196         zIndex = (char *)sqlite3_column_text(pStmt, 0);
74197         pIdx = zIndex ? sqlite3FindIndex(db, zIndex, sInfo.zDatabase) : 0;
74198         if( pIdx ){
74199           int iSample = sqlite3_column_int(pStmt, 1);
74200           if( iSample<SQLITE_INDEX_SAMPLES && iSample>=0 ){
74201             int eType = sqlite3_column_type(pStmt, 2);
74202
74203             if( pIdx->aSample==0 ){
74204               static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
74205               pIdx->aSample = (IndexSample *)sqlite3DbMallocRaw(0, sz);
74206               if( pIdx->aSample==0 ){
74207                 db->mallocFailed = 1;
74208                 break;
74209               }
74210               memset(pIdx->aSample, 0, sz);
74211             }
74212
74213             assert( pIdx->aSample );
74214             {
74215               IndexSample *pSample = &pIdx->aSample[iSample];
74216               pSample->eType = (u8)eType;
74217               if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
74218                 pSample->u.r = sqlite3_column_double(pStmt, 2);
74219               }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
74220                 const char *z = (const char *)(
74221                     (eType==SQLITE_BLOB) ?
74222                     sqlite3_column_blob(pStmt, 2):
74223                     sqlite3_column_text(pStmt, 2)
74224                 );
74225                 int n = sqlite3_column_bytes(pStmt, 2);
74226                 if( n>24 ){
74227                   n = 24;
74228                 }
74229                 pSample->nByte = (u8)n;
74230                 if( n < 1){
74231                   pSample->u.z = 0;
74232                 }else{
74233                   pSample->u.z = sqlite3DbStrNDup(0, z, n);
74234                   if( pSample->u.z==0 ){
74235                     db->mallocFailed = 1;
74236                     break;
74237                   }
74238                 }
74239               }
74240             }
74241           }
74242         }
74243       }
74244       rc = sqlite3_finalize(pStmt);
74245     }
74246   }
74247 #endif
74248
74249   if( rc==SQLITE_NOMEM ){
74250     db->mallocFailed = 1;
74251   }
74252   return rc;
74253 }
74254
74255
74256 #endif /* SQLITE_OMIT_ANALYZE */
74257
74258 /************** End of analyze.c *********************************************/
74259 /************** Begin file attach.c ******************************************/
74260 /*
74261 ** 2003 April 6
74262 **
74263 ** The author disclaims copyright to this source code.  In place of
74264 ** a legal notice, here is a blessing:
74265 **
74266 **    May you do good and not evil.
74267 **    May you find forgiveness for yourself and forgive others.
74268 **    May you share freely, never taking more than you give.
74269 **
74270 *************************************************************************
74271 ** This file contains code used to implement the ATTACH and DETACH commands.
74272 */
74273
74274 #ifndef SQLITE_OMIT_ATTACH
74275 /*
74276 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
74277 ** is slightly different from resolving a normal SQL expression, because simple
74278 ** identifiers are treated as strings, not possible column names or aliases.
74279 **
74280 ** i.e. if the parser sees:
74281 **
74282 **     ATTACH DATABASE abc AS def
74283 **
74284 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
74285 ** looking for columns of the same name.
74286 **
74287 ** This only applies to the root node of pExpr, so the statement:
74288 **
74289 **     ATTACH DATABASE abc||def AS 'db2'
74290 **
74291 ** will fail because neither abc or def can be resolved.
74292 */
74293 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
74294 {
74295   int rc = SQLITE_OK;
74296   if( pExpr ){
74297     if( pExpr->op!=TK_ID ){
74298       rc = sqlite3ResolveExprNames(pName, pExpr);
74299       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
74300         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
74301         return SQLITE_ERROR;
74302       }
74303     }else{
74304       pExpr->op = TK_STRING;
74305     }
74306   }
74307   return rc;
74308 }
74309
74310 /*
74311 ** An SQL user-function registered to do the work of an ATTACH statement. The
74312 ** three arguments to the function come directly from an attach statement:
74313 **
74314 **     ATTACH DATABASE x AS y KEY z
74315 **
74316 **     SELECT sqlite_attach(x, y, z)
74317 **
74318 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
74319 ** third argument.
74320 */
74321 static void attachFunc(
74322   sqlite3_context *context,
74323   int NotUsed,
74324   sqlite3_value **argv
74325 ){
74326   int i;
74327   int rc = 0;
74328   sqlite3 *db = sqlite3_context_db_handle(context);
74329   const char *zName;
74330   const char *zFile;
74331   Db *aNew;
74332   char *zErrDyn = 0;
74333
74334   UNUSED_PARAMETER(NotUsed);
74335
74336   zFile = (const char *)sqlite3_value_text(argv[0]);
74337   zName = (const char *)sqlite3_value_text(argv[1]);
74338   if( zFile==0 ) zFile = "";
74339   if( zName==0 ) zName = "";
74340
74341   /* Check for the following errors:
74342   **
74343   **     * Too many attached databases,
74344   **     * Transaction currently open
74345   **     * Specified database name already being used.
74346   */
74347   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
74348     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", 
74349       db->aLimit[SQLITE_LIMIT_ATTACHED]
74350     );
74351     goto attach_error;
74352   }
74353   if( !db->autoCommit ){
74354     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
74355     goto attach_error;
74356   }
74357   for(i=0; i<db->nDb; i++){
74358     char *z = db->aDb[i].zName;
74359     assert( z && zName );
74360     if( sqlite3StrICmp(z, zName)==0 ){
74361       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
74362       goto attach_error;
74363     }
74364   }
74365
74366   /* Allocate the new entry in the db->aDb[] array and initialise the schema
74367   ** hash tables.
74368   */
74369   if( db->aDb==db->aDbStatic ){
74370     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
74371     if( aNew==0 ) return;
74372     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
74373   }else{
74374     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
74375     if( aNew==0 ) return;
74376   }
74377   db->aDb = aNew;
74378   aNew = &db->aDb[db->nDb];
74379   memset(aNew, 0, sizeof(*aNew));
74380
74381   /* Open the database file. If the btree is successfully opened, use
74382   ** it to obtain the database schema. At this point the schema may
74383   ** or may not be initialised.
74384   */
74385   rc = sqlite3BtreeOpen(zFile, db, &aNew->pBt, 0,
74386                         db->openFlags | SQLITE_OPEN_MAIN_DB);
74387   db->nDb++;
74388   if( rc==SQLITE_CONSTRAINT ){
74389     rc = SQLITE_ERROR;
74390     zErrDyn = sqlite3MPrintf(db, "database is already attached");
74391   }else if( rc==SQLITE_OK ){
74392     Pager *pPager;
74393     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
74394     if( !aNew->pSchema ){
74395       rc = SQLITE_NOMEM;
74396     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
74397       zErrDyn = sqlite3MPrintf(db, 
74398         "attached databases must use the same text encoding as main database");
74399       rc = SQLITE_ERROR;
74400     }
74401     pPager = sqlite3BtreePager(aNew->pBt);
74402     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
74403     sqlite3BtreeSecureDelete(aNew->pBt,
74404                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
74405   }
74406   aNew->safety_level = 3;
74407   aNew->zName = sqlite3DbStrDup(db, zName);
74408   if( rc==SQLITE_OK && aNew->zName==0 ){
74409     rc = SQLITE_NOMEM;
74410   }
74411
74412
74413 #ifdef SQLITE_HAS_CODEC
74414   if( rc==SQLITE_OK ){
74415     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
74416     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
74417     int nKey;
74418     char *zKey;
74419     int t = sqlite3_value_type(argv[2]);
74420     switch( t ){
74421       case SQLITE_INTEGER:
74422       case SQLITE_FLOAT:
74423         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
74424         rc = SQLITE_ERROR;
74425         break;
74426         
74427       case SQLITE_TEXT:
74428       case SQLITE_BLOB:
74429         nKey = sqlite3_value_bytes(argv[2]);
74430         zKey = (char *)sqlite3_value_blob(argv[2]);
74431         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
74432         break;
74433
74434       case SQLITE_NULL:
74435         /* No key specified.  Use the key from the main database */
74436         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
74437         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
74438         break;
74439     }
74440   }
74441 #endif
74442
74443   /* If the file was opened successfully, read the schema for the new database.
74444   ** If this fails, or if opening the file failed, then close the file and 
74445   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
74446   ** we found it.
74447   */
74448   if( rc==SQLITE_OK ){
74449     sqlite3BtreeEnterAll(db);
74450     rc = sqlite3Init(db, &zErrDyn);
74451     sqlite3BtreeLeaveAll(db);
74452   }
74453   if( rc ){
74454     int iDb = db->nDb - 1;
74455     assert( iDb>=2 );
74456     if( db->aDb[iDb].pBt ){
74457       sqlite3BtreeClose(db->aDb[iDb].pBt);
74458       db->aDb[iDb].pBt = 0;
74459       db->aDb[iDb].pSchema = 0;
74460     }
74461     sqlite3ResetInternalSchema(db, 0);
74462     db->nDb = iDb;
74463     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
74464       db->mallocFailed = 1;
74465       sqlite3DbFree(db, zErrDyn);
74466       zErrDyn = sqlite3MPrintf(db, "out of memory");
74467     }else if( zErrDyn==0 ){
74468       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
74469     }
74470     goto attach_error;
74471   }
74472   
74473   return;
74474
74475 attach_error:
74476   /* Return an error if we get here */
74477   if( zErrDyn ){
74478     sqlite3_result_error(context, zErrDyn, -1);
74479     sqlite3DbFree(db, zErrDyn);
74480   }
74481   if( rc ) sqlite3_result_error_code(context, rc);
74482 }
74483
74484 /*
74485 ** An SQL user-function registered to do the work of an DETACH statement. The
74486 ** three arguments to the function come directly from a detach statement:
74487 **
74488 **     DETACH DATABASE x
74489 **
74490 **     SELECT sqlite_detach(x)
74491 */
74492 static void detachFunc(
74493   sqlite3_context *context,
74494   int NotUsed,
74495   sqlite3_value **argv
74496 ){
74497   const char *zName = (const char *)sqlite3_value_text(argv[0]);
74498   sqlite3 *db = sqlite3_context_db_handle(context);
74499   int i;
74500   Db *pDb = 0;
74501   char zErr[128];
74502
74503   UNUSED_PARAMETER(NotUsed);
74504
74505   if( zName==0 ) zName = "";
74506   for(i=0; i<db->nDb; i++){
74507     pDb = &db->aDb[i];
74508     if( pDb->pBt==0 ) continue;
74509     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
74510   }
74511
74512   if( i>=db->nDb ){
74513     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
74514     goto detach_error;
74515   }
74516   if( i<2 ){
74517     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
74518     goto detach_error;
74519   }
74520   if( !db->autoCommit ){
74521     sqlite3_snprintf(sizeof(zErr), zErr,
74522                      "cannot DETACH database within transaction");
74523     goto detach_error;
74524   }
74525   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
74526     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
74527     goto detach_error;
74528   }
74529
74530   sqlite3BtreeClose(pDb->pBt);
74531   pDb->pBt = 0;
74532   pDb->pSchema = 0;
74533   sqlite3ResetInternalSchema(db, 0);
74534   return;
74535
74536 detach_error:
74537   sqlite3_result_error(context, zErr, -1);
74538 }
74539
74540 /*
74541 ** This procedure generates VDBE code for a single invocation of either the
74542 ** sqlite_detach() or sqlite_attach() SQL user functions.
74543 */
74544 static void codeAttach(
74545   Parse *pParse,       /* The parser context */
74546   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
74547   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
74548   Expr *pAuthArg,      /* Expression to pass to authorization callback */
74549   Expr *pFilename,     /* Name of database file */
74550   Expr *pDbname,       /* Name of the database to use internally */
74551   Expr *pKey           /* Database key for encryption extension */
74552 ){
74553   int rc;
74554   NameContext sName;
74555   Vdbe *v;
74556   sqlite3* db = pParse->db;
74557   int regArgs;
74558
74559   memset(&sName, 0, sizeof(NameContext));
74560   sName.pParse = pParse;
74561
74562   if( 
74563       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
74564       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
74565       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
74566   ){
74567     pParse->nErr++;
74568     goto attach_end;
74569   }
74570
74571 #ifndef SQLITE_OMIT_AUTHORIZATION
74572   if( pAuthArg ){
74573     char *zAuthArg = pAuthArg->u.zToken;
74574     if( NEVER(zAuthArg==0) ){
74575       goto attach_end;
74576     }
74577     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
74578     if(rc!=SQLITE_OK ){
74579       goto attach_end;
74580     }
74581   }
74582 #endif /* SQLITE_OMIT_AUTHORIZATION */
74583
74584
74585   v = sqlite3GetVdbe(pParse);
74586   regArgs = sqlite3GetTempRange(pParse, 4);
74587   sqlite3ExprCode(pParse, pFilename, regArgs);
74588   sqlite3ExprCode(pParse, pDbname, regArgs+1);
74589   sqlite3ExprCode(pParse, pKey, regArgs+2);
74590
74591   assert( v || db->mallocFailed );
74592   if( v ){
74593     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
74594     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
74595     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
74596     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
74597
74598     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
74599     ** statement only). For DETACH, set it to false (expire all existing
74600     ** statements).
74601     */
74602     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
74603   }
74604   
74605 attach_end:
74606   sqlite3ExprDelete(db, pFilename);
74607   sqlite3ExprDelete(db, pDbname);
74608   sqlite3ExprDelete(db, pKey);
74609 }
74610
74611 /*
74612 ** Called by the parser to compile a DETACH statement.
74613 **
74614 **     DETACH pDbname
74615 */
74616 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
74617   static const FuncDef detach_func = {
74618     1,                /* nArg */
74619     SQLITE_UTF8,      /* iPrefEnc */
74620     0,                /* flags */
74621     0,                /* pUserData */
74622     0,                /* pNext */
74623     detachFunc,       /* xFunc */
74624     0,                /* xStep */
74625     0,                /* xFinalize */
74626     "sqlite_detach",  /* zName */
74627     0,                /* pHash */
74628     0                 /* pDestructor */
74629   };
74630   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
74631 }
74632
74633 /*
74634 ** Called by the parser to compile an ATTACH statement.
74635 **
74636 **     ATTACH p AS pDbname KEY pKey
74637 */
74638 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
74639   static const FuncDef attach_func = {
74640     3,                /* nArg */
74641     SQLITE_UTF8,      /* iPrefEnc */
74642     0,                /* flags */
74643     0,                /* pUserData */
74644     0,                /* pNext */
74645     attachFunc,       /* xFunc */
74646     0,                /* xStep */
74647     0,                /* xFinalize */
74648     "sqlite_attach",  /* zName */
74649     0,                /* pHash */
74650     0                 /* pDestructor */
74651   };
74652   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
74653 }
74654 #endif /* SQLITE_OMIT_ATTACH */
74655
74656 /*
74657 ** Initialize a DbFixer structure.  This routine must be called prior
74658 ** to passing the structure to one of the sqliteFixAAAA() routines below.
74659 **
74660 ** The return value indicates whether or not fixation is required.  TRUE
74661 ** means we do need to fix the database references, FALSE means we do not.
74662 */
74663 SQLITE_PRIVATE int sqlite3FixInit(
74664   DbFixer *pFix,      /* The fixer to be initialized */
74665   Parse *pParse,      /* Error messages will be written here */
74666   int iDb,            /* This is the database that must be used */
74667   const char *zType,  /* "view", "trigger", or "index" */
74668   const Token *pName  /* Name of the view, trigger, or index */
74669 ){
74670   sqlite3 *db;
74671
74672   if( NEVER(iDb<0) || iDb==1 ) return 0;
74673   db = pParse->db;
74674   assert( db->nDb>iDb );
74675   pFix->pParse = pParse;
74676   pFix->zDb = db->aDb[iDb].zName;
74677   pFix->zType = zType;
74678   pFix->pName = pName;
74679   return 1;
74680 }
74681
74682 /*
74683 ** The following set of routines walk through the parse tree and assign
74684 ** a specific database to all table references where the database name
74685 ** was left unspecified in the original SQL statement.  The pFix structure
74686 ** must have been initialized by a prior call to sqlite3FixInit().
74687 **
74688 ** These routines are used to make sure that an index, trigger, or
74689 ** view in one database does not refer to objects in a different database.
74690 ** (Exception: indices, triggers, and views in the TEMP database are
74691 ** allowed to refer to anything.)  If a reference is explicitly made
74692 ** to an object in a different database, an error message is added to
74693 ** pParse->zErrMsg and these routines return non-zero.  If everything
74694 ** checks out, these routines return 0.
74695 */
74696 SQLITE_PRIVATE int sqlite3FixSrcList(
74697   DbFixer *pFix,       /* Context of the fixation */
74698   SrcList *pList       /* The Source list to check and modify */
74699 ){
74700   int i;
74701   const char *zDb;
74702   struct SrcList_item *pItem;
74703
74704   if( NEVER(pList==0) ) return 0;
74705   zDb = pFix->zDb;
74706   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
74707     if( pItem->zDatabase==0 ){
74708       pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
74709     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
74710       sqlite3ErrorMsg(pFix->pParse,
74711          "%s %T cannot reference objects in database %s",
74712          pFix->zType, pFix->pName, pItem->zDatabase);
74713       return 1;
74714     }
74715 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
74716     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
74717     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
74718 #endif
74719   }
74720   return 0;
74721 }
74722 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
74723 SQLITE_PRIVATE int sqlite3FixSelect(
74724   DbFixer *pFix,       /* Context of the fixation */
74725   Select *pSelect      /* The SELECT statement to be fixed to one database */
74726 ){
74727   while( pSelect ){
74728     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
74729       return 1;
74730     }
74731     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
74732       return 1;
74733     }
74734     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
74735       return 1;
74736     }
74737     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
74738       return 1;
74739     }
74740     pSelect = pSelect->pPrior;
74741   }
74742   return 0;
74743 }
74744 SQLITE_PRIVATE int sqlite3FixExpr(
74745   DbFixer *pFix,     /* Context of the fixation */
74746   Expr *pExpr        /* The expression to be fixed to one database */
74747 ){
74748   while( pExpr ){
74749     if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
74750     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
74751       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
74752     }else{
74753       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
74754     }
74755     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
74756       return 1;
74757     }
74758     pExpr = pExpr->pLeft;
74759   }
74760   return 0;
74761 }
74762 SQLITE_PRIVATE int sqlite3FixExprList(
74763   DbFixer *pFix,     /* Context of the fixation */
74764   ExprList *pList    /* The expression to be fixed to one database */
74765 ){
74766   int i;
74767   struct ExprList_item *pItem;
74768   if( pList==0 ) return 0;
74769   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
74770     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
74771       return 1;
74772     }
74773   }
74774   return 0;
74775 }
74776 #endif
74777
74778 #ifndef SQLITE_OMIT_TRIGGER
74779 SQLITE_PRIVATE int sqlite3FixTriggerStep(
74780   DbFixer *pFix,     /* Context of the fixation */
74781   TriggerStep *pStep /* The trigger step be fixed to one database */
74782 ){
74783   while( pStep ){
74784     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
74785       return 1;
74786     }
74787     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
74788       return 1;
74789     }
74790     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
74791       return 1;
74792     }
74793     pStep = pStep->pNext;
74794   }
74795   return 0;
74796 }
74797 #endif
74798
74799 /************** End of attach.c **********************************************/
74800 /************** Begin file auth.c ********************************************/
74801 /*
74802 ** 2003 January 11
74803 **
74804 ** The author disclaims copyright to this source code.  In place of
74805 ** a legal notice, here is a blessing:
74806 **
74807 **    May you do good and not evil.
74808 **    May you find forgiveness for yourself and forgive others.
74809 **    May you share freely, never taking more than you give.
74810 **
74811 *************************************************************************
74812 ** This file contains code used to implement the sqlite3_set_authorizer()
74813 ** API.  This facility is an optional feature of the library.  Embedded
74814 ** systems that do not need this facility may omit it by recompiling
74815 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
74816 */
74817
74818 /*
74819 ** All of the code in this file may be omitted by defining a single
74820 ** macro.
74821 */
74822 #ifndef SQLITE_OMIT_AUTHORIZATION
74823
74824 /*
74825 ** Set or clear the access authorization function.
74826 **
74827 ** The access authorization function is be called during the compilation
74828 ** phase to verify that the user has read and/or write access permission on
74829 ** various fields of the database.  The first argument to the auth function
74830 ** is a copy of the 3rd argument to this routine.  The second argument
74831 ** to the auth function is one of these constants:
74832 **
74833 **       SQLITE_CREATE_INDEX
74834 **       SQLITE_CREATE_TABLE
74835 **       SQLITE_CREATE_TEMP_INDEX
74836 **       SQLITE_CREATE_TEMP_TABLE
74837 **       SQLITE_CREATE_TEMP_TRIGGER
74838 **       SQLITE_CREATE_TEMP_VIEW
74839 **       SQLITE_CREATE_TRIGGER
74840 **       SQLITE_CREATE_VIEW
74841 **       SQLITE_DELETE
74842 **       SQLITE_DROP_INDEX
74843 **       SQLITE_DROP_TABLE
74844 **       SQLITE_DROP_TEMP_INDEX
74845 **       SQLITE_DROP_TEMP_TABLE
74846 **       SQLITE_DROP_TEMP_TRIGGER
74847 **       SQLITE_DROP_TEMP_VIEW
74848 **       SQLITE_DROP_TRIGGER
74849 **       SQLITE_DROP_VIEW
74850 **       SQLITE_INSERT
74851 **       SQLITE_PRAGMA
74852 **       SQLITE_READ
74853 **       SQLITE_SELECT
74854 **       SQLITE_TRANSACTION
74855 **       SQLITE_UPDATE
74856 **
74857 ** The third and fourth arguments to the auth function are the name of
74858 ** the table and the column that are being accessed.  The auth function
74859 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
74860 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
74861 ** means that the SQL statement will never-run - the sqlite3_exec() call
74862 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
74863 ** should run but attempts to read the specified column will return NULL
74864 ** and attempts to write the column will be ignored.
74865 **
74866 ** Setting the auth function to NULL disables this hook.  The default
74867 ** setting of the auth function is NULL.
74868 */
74869 SQLITE_API int sqlite3_set_authorizer(
74870   sqlite3 *db,
74871   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
74872   void *pArg
74873 ){
74874   sqlite3_mutex_enter(db->mutex);
74875   db->xAuth = xAuth;
74876   db->pAuthArg = pArg;
74877   sqlite3ExpirePreparedStatements(db);
74878   sqlite3_mutex_leave(db->mutex);
74879   return SQLITE_OK;
74880 }
74881
74882 /*
74883 ** Write an error message into pParse->zErrMsg that explains that the
74884 ** user-supplied authorization function returned an illegal value.
74885 */
74886 static void sqliteAuthBadReturnCode(Parse *pParse){
74887   sqlite3ErrorMsg(pParse, "authorizer malfunction");
74888   pParse->rc = SQLITE_ERROR;
74889 }
74890
74891 /*
74892 ** Invoke the authorization callback for permission to read column zCol from
74893 ** table zTab in database zDb. This function assumes that an authorization
74894 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
74895 **
74896 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
74897 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
74898 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
74899 */
74900 SQLITE_PRIVATE int sqlite3AuthReadCol(
74901   Parse *pParse,                  /* The parser context */
74902   const char *zTab,               /* Table name */
74903   const char *zCol,               /* Column name */
74904   int iDb                         /* Index of containing database. */
74905 ){
74906   sqlite3 *db = pParse->db;       /* Database handle */
74907   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
74908   int rc;                         /* Auth callback return code */
74909
74910   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
74911   if( rc==SQLITE_DENY ){
74912     if( db->nDb>2 || iDb!=0 ){
74913       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
74914     }else{
74915       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
74916     }
74917     pParse->rc = SQLITE_AUTH;
74918   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
74919     sqliteAuthBadReturnCode(pParse);
74920   }
74921   return rc;
74922 }
74923
74924 /*
74925 ** The pExpr should be a TK_COLUMN expression.  The table referred to
74926 ** is in pTabList or else it is the NEW or OLD table of a trigger.  
74927 ** Check to see if it is OK to read this particular column.
74928 **
74929 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
74930 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
74931 ** then generate an error.
74932 */
74933 SQLITE_PRIVATE void sqlite3AuthRead(
74934   Parse *pParse,        /* The parser context */
74935   Expr *pExpr,          /* The expression to check authorization on */
74936   Schema *pSchema,      /* The schema of the expression */
74937   SrcList *pTabList     /* All table that pExpr might refer to */
74938 ){
74939   sqlite3 *db = pParse->db;
74940   Table *pTab = 0;      /* The table being read */
74941   const char *zCol;     /* Name of the column of the table */
74942   int iSrc;             /* Index in pTabList->a[] of table being read */
74943   int iDb;              /* The index of the database the expression refers to */
74944   int iCol;             /* Index of column in table */
74945
74946   if( db->xAuth==0 ) return;
74947   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
74948   if( iDb<0 ){
74949     /* An attempt to read a column out of a subquery or other
74950     ** temporary table. */
74951     return;
74952   }
74953
74954   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
74955   if( pExpr->op==TK_TRIGGER ){
74956     pTab = pParse->pTriggerTab;
74957   }else{
74958     assert( pTabList );
74959     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
74960       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
74961         pTab = pTabList->a[iSrc].pTab;
74962         break;
74963       }
74964     }
74965   }
74966   iCol = pExpr->iColumn;
74967   if( NEVER(pTab==0) ) return;
74968
74969   if( iCol>=0 ){
74970     assert( iCol<pTab->nCol );
74971     zCol = pTab->aCol[iCol].zName;
74972   }else if( pTab->iPKey>=0 ){
74973     assert( pTab->iPKey<pTab->nCol );
74974     zCol = pTab->aCol[pTab->iPKey].zName;
74975   }else{
74976     zCol = "ROWID";
74977   }
74978   assert( iDb>=0 && iDb<db->nDb );
74979   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
74980     pExpr->op = TK_NULL;
74981   }
74982 }
74983
74984 /*
74985 ** Do an authorization check using the code and arguments given.  Return
74986 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
74987 ** is returned, then the error count and error message in pParse are
74988 ** modified appropriately.
74989 */
74990 SQLITE_PRIVATE int sqlite3AuthCheck(
74991   Parse *pParse,
74992   int code,
74993   const char *zArg1,
74994   const char *zArg2,
74995   const char *zArg3
74996 ){
74997   sqlite3 *db = pParse->db;
74998   int rc;
74999
75000   /* Don't do any authorization checks if the database is initialising
75001   ** or if the parser is being invoked from within sqlite3_declare_vtab.
75002   */
75003   if( db->init.busy || IN_DECLARE_VTAB ){
75004     return SQLITE_OK;
75005   }
75006
75007   if( db->xAuth==0 ){
75008     return SQLITE_OK;
75009   }
75010   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
75011   if( rc==SQLITE_DENY ){
75012     sqlite3ErrorMsg(pParse, "not authorized");
75013     pParse->rc = SQLITE_AUTH;
75014   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
75015     rc = SQLITE_DENY;
75016     sqliteAuthBadReturnCode(pParse);
75017   }
75018   return rc;
75019 }
75020
75021 /*
75022 ** Push an authorization context.  After this routine is called, the
75023 ** zArg3 argument to authorization callbacks will be zContext until
75024 ** popped.  Or if pParse==0, this routine is a no-op.
75025 */
75026 SQLITE_PRIVATE void sqlite3AuthContextPush(
75027   Parse *pParse,
75028   AuthContext *pContext, 
75029   const char *zContext
75030 ){
75031   assert( pParse );
75032   pContext->pParse = pParse;
75033   pContext->zAuthContext = pParse->zAuthContext;
75034   pParse->zAuthContext = zContext;
75035 }
75036
75037 /*
75038 ** Pop an authorization context that was previously pushed
75039 ** by sqlite3AuthContextPush
75040 */
75041 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
75042   if( pContext->pParse ){
75043     pContext->pParse->zAuthContext = pContext->zAuthContext;
75044     pContext->pParse = 0;
75045   }
75046 }
75047
75048 #endif /* SQLITE_OMIT_AUTHORIZATION */
75049
75050 /************** End of auth.c ************************************************/
75051 /************** Begin file build.c *******************************************/
75052 /*
75053 ** 2001 September 15
75054 **
75055 ** The author disclaims copyright to this source code.  In place of
75056 ** a legal notice, here is a blessing:
75057 **
75058 **    May you do good and not evil.
75059 **    May you find forgiveness for yourself and forgive others.
75060 **    May you share freely, never taking more than you give.
75061 **
75062 *************************************************************************
75063 ** This file contains C code routines that are called by the SQLite parser
75064 ** when syntax rules are reduced.  The routines in this file handle the
75065 ** following kinds of SQL syntax:
75066 **
75067 **     CREATE TABLE
75068 **     DROP TABLE
75069 **     CREATE INDEX
75070 **     DROP INDEX
75071 **     creating ID lists
75072 **     BEGIN TRANSACTION
75073 **     COMMIT
75074 **     ROLLBACK
75075 */
75076
75077 /*
75078 ** This routine is called when a new SQL statement is beginning to
75079 ** be parsed.  Initialize the pParse structure as needed.
75080 */
75081 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
75082   pParse->explain = (u8)explainFlag;
75083   pParse->nVar = 0;
75084 }
75085
75086 #ifndef SQLITE_OMIT_SHARED_CACHE
75087 /*
75088 ** The TableLock structure is only used by the sqlite3TableLock() and
75089 ** codeTableLocks() functions.
75090 */
75091 struct TableLock {
75092   int iDb;             /* The database containing the table to be locked */
75093   int iTab;            /* The root page of the table to be locked */
75094   u8 isWriteLock;      /* True for write lock.  False for a read lock */
75095   const char *zName;   /* Name of the table */
75096 };
75097
75098 /*
75099 ** Record the fact that we want to lock a table at run-time.  
75100 **
75101 ** The table to be locked has root page iTab and is found in database iDb.
75102 ** A read or a write lock can be taken depending on isWritelock.
75103 **
75104 ** This routine just records the fact that the lock is desired.  The
75105 ** code to make the lock occur is generated by a later call to
75106 ** codeTableLocks() which occurs during sqlite3FinishCoding().
75107 */
75108 SQLITE_PRIVATE void sqlite3TableLock(
75109   Parse *pParse,     /* Parsing context */
75110   int iDb,           /* Index of the database containing the table to lock */
75111   int iTab,          /* Root page number of the table to be locked */
75112   u8 isWriteLock,    /* True for a write lock */
75113   const char *zName  /* Name of the table to be locked */
75114 ){
75115   Parse *pToplevel = sqlite3ParseToplevel(pParse);
75116   int i;
75117   int nBytes;
75118   TableLock *p;
75119   assert( iDb>=0 );
75120
75121   for(i=0; i<pToplevel->nTableLock; i++){
75122     p = &pToplevel->aTableLock[i];
75123     if( p->iDb==iDb && p->iTab==iTab ){
75124       p->isWriteLock = (p->isWriteLock || isWriteLock);
75125       return;
75126     }
75127   }
75128
75129   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
75130   pToplevel->aTableLock =
75131       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
75132   if( pToplevel->aTableLock ){
75133     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
75134     p->iDb = iDb;
75135     p->iTab = iTab;
75136     p->isWriteLock = isWriteLock;
75137     p->zName = zName;
75138   }else{
75139     pToplevel->nTableLock = 0;
75140     pToplevel->db->mallocFailed = 1;
75141   }
75142 }
75143
75144 /*
75145 ** Code an OP_TableLock instruction for each table locked by the
75146 ** statement (configured by calls to sqlite3TableLock()).
75147 */
75148 static void codeTableLocks(Parse *pParse){
75149   int i;
75150   Vdbe *pVdbe; 
75151
75152   pVdbe = sqlite3GetVdbe(pParse);
75153   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
75154
75155   for(i=0; i<pParse->nTableLock; i++){
75156     TableLock *p = &pParse->aTableLock[i];
75157     int p1 = p->iDb;
75158     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
75159                       p->zName, P4_STATIC);
75160   }
75161 }
75162 #else
75163   #define codeTableLocks(x)
75164 #endif
75165
75166 /*
75167 ** This routine is called after a single SQL statement has been
75168 ** parsed and a VDBE program to execute that statement has been
75169 ** prepared.  This routine puts the finishing touches on the
75170 ** VDBE program and resets the pParse structure for the next
75171 ** parse.
75172 **
75173 ** Note that if an error occurred, it might be the case that
75174 ** no VDBE code was generated.
75175 */
75176 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
75177   sqlite3 *db;
75178   Vdbe *v;
75179
75180   db = pParse->db;
75181   if( db->mallocFailed ) return;
75182   if( pParse->nested ) return;
75183   if( pParse->nErr ) return;
75184
75185   /* Begin by generating some termination code at the end of the
75186   ** vdbe program
75187   */
75188   v = sqlite3GetVdbe(pParse);
75189   assert( !pParse->isMultiWrite 
75190        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
75191   if( v ){
75192     sqlite3VdbeAddOp0(v, OP_Halt);
75193
75194     /* The cookie mask contains one bit for each database file open.
75195     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
75196     ** set for each database that is used.  Generate code to start a
75197     ** transaction on each used database and to verify the schema cookie
75198     ** on each used database.
75199     */
75200     if( pParse->cookieGoto>0 ){
75201       u32 mask;
75202       int iDb;
75203       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
75204       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
75205         if( (mask & pParse->cookieMask)==0 ) continue;
75206         sqlite3VdbeUsesBtree(v, iDb);
75207         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
75208         if( db->init.busy==0 ){
75209           sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
75210         }
75211       }
75212 #ifndef SQLITE_OMIT_VIRTUALTABLE
75213       {
75214         int i;
75215         for(i=0; i<pParse->nVtabLock; i++){
75216           char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
75217           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
75218         }
75219         pParse->nVtabLock = 0;
75220       }
75221 #endif
75222
75223       /* Once all the cookies have been verified and transactions opened, 
75224       ** obtain the required table-locks. This is a no-op unless the 
75225       ** shared-cache feature is enabled.
75226       */
75227       codeTableLocks(pParse);
75228
75229       /* Initialize any AUTOINCREMENT data structures required.
75230       */
75231       sqlite3AutoincrementBegin(pParse);
75232
75233       /* Finally, jump back to the beginning of the executable code. */
75234       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
75235     }
75236   }
75237
75238
75239   /* Get the VDBE program ready for execution
75240   */
75241   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
75242 #ifdef SQLITE_DEBUG
75243     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
75244     sqlite3VdbeTrace(v, trace);
75245 #endif
75246     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
75247     /* A minimum of one cursor is required if autoincrement is used
75248     *  See ticket [a696379c1f08866] */
75249     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
75250     sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
75251                          pParse->nTab, pParse->nMaxArg, pParse->explain,
75252                          pParse->isMultiWrite && pParse->mayAbort);
75253     pParse->rc = SQLITE_DONE;
75254     pParse->colNamesSet = 0;
75255   }else{
75256     pParse->rc = SQLITE_ERROR;
75257   }
75258   pParse->nTab = 0;
75259   pParse->nMem = 0;
75260   pParse->nSet = 0;
75261   pParse->nVar = 0;
75262   pParse->cookieMask = 0;
75263   pParse->cookieGoto = 0;
75264 }
75265
75266 /*
75267 ** Run the parser and code generator recursively in order to generate
75268 ** code for the SQL statement given onto the end of the pParse context
75269 ** currently under construction.  When the parser is run recursively
75270 ** this way, the final OP_Halt is not appended and other initialization
75271 ** and finalization steps are omitted because those are handling by the
75272 ** outermost parser.
75273 **
75274 ** Not everything is nestable.  This facility is designed to permit
75275 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
75276 ** care if you decide to try to use this routine for some other purposes.
75277 */
75278 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
75279   va_list ap;
75280   char *zSql;
75281   char *zErrMsg = 0;
75282   sqlite3 *db = pParse->db;
75283 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
75284   char saveBuf[SAVE_SZ];
75285
75286   if( pParse->nErr ) return;
75287   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
75288   va_start(ap, zFormat);
75289   zSql = sqlite3VMPrintf(db, zFormat, ap);
75290   va_end(ap);
75291   if( zSql==0 ){
75292     return;   /* A malloc must have failed */
75293   }
75294   pParse->nested++;
75295   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
75296   memset(&pParse->nVar, 0, SAVE_SZ);
75297   sqlite3RunParser(pParse, zSql, &zErrMsg);
75298   sqlite3DbFree(db, zErrMsg);
75299   sqlite3DbFree(db, zSql);
75300   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
75301   pParse->nested--;
75302 }
75303
75304 /*
75305 ** Locate the in-memory structure that describes a particular database
75306 ** table given the name of that table and (optionally) the name of the
75307 ** database containing the table.  Return NULL if not found.
75308 **
75309 ** If zDatabase is 0, all databases are searched for the table and the
75310 ** first matching table is returned.  (No checking for duplicate table
75311 ** names is done.)  The search order is TEMP first, then MAIN, then any
75312 ** auxiliary databases added using the ATTACH command.
75313 **
75314 ** See also sqlite3LocateTable().
75315 */
75316 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
75317   Table *p = 0;
75318   int i;
75319   int nName;
75320   assert( zName!=0 );
75321   nName = sqlite3Strlen30(zName);
75322   for(i=OMIT_TEMPDB; i<db->nDb; i++){
75323     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
75324     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
75325     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
75326     if( p ) break;
75327   }
75328   return p;
75329 }
75330
75331 /*
75332 ** Locate the in-memory structure that describes a particular database
75333 ** table given the name of that table and (optionally) the name of the
75334 ** database containing the table.  Return NULL if not found.  Also leave an
75335 ** error message in pParse->zErrMsg.
75336 **
75337 ** The difference between this routine and sqlite3FindTable() is that this
75338 ** routine leaves an error message in pParse->zErrMsg where
75339 ** sqlite3FindTable() does not.
75340 */
75341 SQLITE_PRIVATE Table *sqlite3LocateTable(
75342   Parse *pParse,         /* context in which to report errors */
75343   int isView,            /* True if looking for a VIEW rather than a TABLE */
75344   const char *zName,     /* Name of the table we are looking for */
75345   const char *zDbase     /* Name of the database.  Might be NULL */
75346 ){
75347   Table *p;
75348
75349   /* Read the database schema. If an error occurs, leave an error message
75350   ** and code in pParse and return NULL. */
75351   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
75352     return 0;
75353   }
75354
75355   p = sqlite3FindTable(pParse->db, zName, zDbase);
75356   if( p==0 ){
75357     const char *zMsg = isView ? "no such view" : "no such table";
75358     if( zDbase ){
75359       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
75360     }else{
75361       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
75362     }
75363     pParse->checkSchema = 1;
75364   }
75365   return p;
75366 }
75367
75368 /*
75369 ** Locate the in-memory structure that describes 
75370 ** a particular index given the name of that index
75371 ** and the name of the database that contains the index.
75372 ** Return NULL if not found.
75373 **
75374 ** If zDatabase is 0, all databases are searched for the
75375 ** table and the first matching index is returned.  (No checking
75376 ** for duplicate index names is done.)  The search order is
75377 ** TEMP first, then MAIN, then any auxiliary databases added
75378 ** using the ATTACH command.
75379 */
75380 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
75381   Index *p = 0;
75382   int i;
75383   int nName = sqlite3Strlen30(zName);
75384   for(i=OMIT_TEMPDB; i<db->nDb; i++){
75385     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
75386     Schema *pSchema = db->aDb[j].pSchema;
75387     assert( pSchema );
75388     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
75389     p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
75390     if( p ) break;
75391   }
75392   return p;
75393 }
75394
75395 /*
75396 ** Reclaim the memory used by an index
75397 */
75398 static void freeIndex(sqlite3 *db, Index *p){
75399 #ifndef SQLITE_OMIT_ANALYZE
75400   sqlite3DeleteIndexSamples(db, p);
75401 #endif
75402   sqlite3DbFree(db, p->zColAff);
75403   sqlite3DbFree(db, p);
75404 }
75405
75406 /*
75407 ** For the index called zIdxName which is found in the database iDb,
75408 ** unlike that index from its Table then remove the index from
75409 ** the index hash table and free all memory structures associated
75410 ** with the index.
75411 */
75412 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
75413   Index *pIndex;
75414   int len;
75415   Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
75416
75417   len = sqlite3Strlen30(zIdxName);
75418   pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
75419   if( pIndex ){
75420     if( pIndex->pTable->pIndex==pIndex ){
75421       pIndex->pTable->pIndex = pIndex->pNext;
75422     }else{
75423       Index *p;
75424       /* Justification of ALWAYS();  The index must be on the list of
75425       ** indices. */
75426       p = pIndex->pTable->pIndex;
75427       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
75428       if( ALWAYS(p && p->pNext==pIndex) ){
75429         p->pNext = pIndex->pNext;
75430       }
75431     }
75432     freeIndex(db, pIndex);
75433   }
75434   db->flags |= SQLITE_InternChanges;
75435 }
75436
75437 /*
75438 ** Erase all schema information from the in-memory hash tables of
75439 ** a single database.  This routine is called to reclaim memory
75440 ** before the database closes.  It is also called during a rollback
75441 ** if there were schema changes during the transaction or if a
75442 ** schema-cookie mismatch occurs.
75443 **
75444 ** If iDb==0 then reset the internal schema tables for all database
75445 ** files.  If iDb>=1 then reset the internal schema for only the
75446 ** single file indicated.
75447 */
75448 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
75449   int i, j;
75450   assert( iDb>=0 && iDb<db->nDb );
75451
75452   if( iDb==0 ){
75453     sqlite3BtreeEnterAll(db);
75454   }
75455   for(i=iDb; i<db->nDb; i++){
75456     Db *pDb = &db->aDb[i];
75457     if( pDb->pSchema ){
75458       assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
75459       sqlite3SchemaFree(pDb->pSchema);
75460     }
75461     if( iDb>0 ) return;
75462   }
75463   assert( iDb==0 );
75464   db->flags &= ~SQLITE_InternChanges;
75465   sqlite3VtabUnlockList(db);
75466   sqlite3BtreeLeaveAll(db);
75467
75468   /* If one or more of the auxiliary database files has been closed,
75469   ** then remove them from the auxiliary database list.  We take the
75470   ** opportunity to do this here since we have just deleted all of the
75471   ** schema hash tables and therefore do not have to make any changes
75472   ** to any of those tables.
75473   */
75474   for(i=j=2; i<db->nDb; i++){
75475     struct Db *pDb = &db->aDb[i];
75476     if( pDb->pBt==0 ){
75477       sqlite3DbFree(db, pDb->zName);
75478       pDb->zName = 0;
75479       continue;
75480     }
75481     if( j<i ){
75482       db->aDb[j] = db->aDb[i];
75483     }
75484     j++;
75485   }
75486   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
75487   db->nDb = j;
75488   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
75489     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
75490     sqlite3DbFree(db, db->aDb);
75491     db->aDb = db->aDbStatic;
75492   }
75493 }
75494
75495 /*
75496 ** This routine is called when a commit occurs.
75497 */
75498 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
75499   db->flags &= ~SQLITE_InternChanges;
75500 }
75501
75502 /*
75503 ** Delete memory allocated for the column names of a table or view (the
75504 ** Table.aCol[] array).
75505 */
75506 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
75507   int i;
75508   Column *pCol;
75509   assert( pTable!=0 );
75510   if( (pCol = pTable->aCol)!=0 ){
75511     for(i=0; i<pTable->nCol; i++, pCol++){
75512       sqlite3DbFree(db, pCol->zName);
75513       sqlite3ExprDelete(db, pCol->pDflt);
75514       sqlite3DbFree(db, pCol->zDflt);
75515       sqlite3DbFree(db, pCol->zType);
75516       sqlite3DbFree(db, pCol->zColl);
75517     }
75518     sqlite3DbFree(db, pTable->aCol);
75519   }
75520 }
75521
75522 /*
75523 ** Remove the memory data structures associated with the given
75524 ** Table.  No changes are made to disk by this routine.
75525 **
75526 ** This routine just deletes the data structure.  It does not unlink
75527 ** the table data structure from the hash table.  But it does destroy
75528 ** memory structures of the indices and foreign keys associated with 
75529 ** the table.
75530 */
75531 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
75532   Index *pIndex, *pNext;
75533
75534   assert( !pTable || pTable->nRef>0 );
75535
75536   /* Do not delete the table until the reference count reaches zero. */
75537   if( !pTable ) return;
75538   if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
75539
75540   /* Delete all indices associated with this table. */
75541   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
75542     pNext = pIndex->pNext;
75543     assert( pIndex->pSchema==pTable->pSchema );
75544     if( !db || db->pnBytesFreed==0 ){
75545       char *zName = pIndex->zName; 
75546       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
75547           &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
75548       );
75549       assert( pOld==pIndex || pOld==0 );
75550     }
75551     freeIndex(db, pIndex);
75552   }
75553
75554   /* Delete any foreign keys attached to this table. */
75555   sqlite3FkDelete(db, pTable);
75556
75557   /* Delete the Table structure itself.
75558   */
75559   sqliteDeleteColumnNames(db, pTable);
75560   sqlite3DbFree(db, pTable->zName);
75561   sqlite3DbFree(db, pTable->zColAff);
75562   sqlite3SelectDelete(db, pTable->pSelect);
75563 #ifndef SQLITE_OMIT_CHECK
75564   sqlite3ExprDelete(db, pTable->pCheck);
75565 #endif
75566 #ifndef SQLITE_OMIT_VIRTUALTABLE
75567   sqlite3VtabClear(db, pTable);
75568 #endif
75569   sqlite3DbFree(db, pTable);
75570 }
75571
75572 /*
75573 ** Unlink the given table from the hash tables and the delete the
75574 ** table structure with all its indices and foreign keys.
75575 */
75576 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
75577   Table *p;
75578   Db *pDb;
75579
75580   assert( db!=0 );
75581   assert( iDb>=0 && iDb<db->nDb );
75582   assert( zTabName );
75583   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
75584   pDb = &db->aDb[iDb];
75585   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
75586                         sqlite3Strlen30(zTabName),0);
75587   sqlite3DeleteTable(db, p);
75588   db->flags |= SQLITE_InternChanges;
75589 }
75590
75591 /*
75592 ** Given a token, return a string that consists of the text of that
75593 ** token.  Space to hold the returned string
75594 ** is obtained from sqliteMalloc() and must be freed by the calling
75595 ** function.
75596 **
75597 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
75598 ** surround the body of the token are removed.
75599 **
75600 ** Tokens are often just pointers into the original SQL text and so
75601 ** are not \000 terminated and are not persistent.  The returned string
75602 ** is \000 terminated and is persistent.
75603 */
75604 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
75605   char *zName;
75606   if( pName ){
75607     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
75608     sqlite3Dequote(zName);
75609   }else{
75610     zName = 0;
75611   }
75612   return zName;
75613 }
75614
75615 /*
75616 ** Open the sqlite_master table stored in database number iDb for
75617 ** writing. The table is opened using cursor 0.
75618 */
75619 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
75620   Vdbe *v = sqlite3GetVdbe(p);
75621   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
75622   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
75623   sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
75624   if( p->nTab==0 ){
75625     p->nTab = 1;
75626   }
75627 }
75628
75629 /*
75630 ** Parameter zName points to a nul-terminated buffer containing the name
75631 ** of a database ("main", "temp" or the name of an attached db). This
75632 ** function returns the index of the named database in db->aDb[], or
75633 ** -1 if the named db cannot be found.
75634 */
75635 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
75636   int i = -1;         /* Database number */
75637   if( zName ){
75638     Db *pDb;
75639     int n = sqlite3Strlen30(zName);
75640     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
75641       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) && 
75642           0==sqlite3StrICmp(pDb->zName, zName) ){
75643         break;
75644       }
75645     }
75646   }
75647   return i;
75648 }
75649
75650 /*
75651 ** The token *pName contains the name of a database (either "main" or
75652 ** "temp" or the name of an attached db). This routine returns the
75653 ** index of the named database in db->aDb[], or -1 if the named db 
75654 ** does not exist.
75655 */
75656 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
75657   int i;                               /* Database number */
75658   char *zName;                         /* Name we are searching for */
75659   zName = sqlite3NameFromToken(db, pName);
75660   i = sqlite3FindDbName(db, zName);
75661   sqlite3DbFree(db, zName);
75662   return i;
75663 }
75664
75665 /* The table or view or trigger name is passed to this routine via tokens
75666 ** pName1 and pName2. If the table name was fully qualified, for example:
75667 **
75668 ** CREATE TABLE xxx.yyy (...);
75669 ** 
75670 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
75671 ** the table name is not fully qualified, i.e.:
75672 **
75673 ** CREATE TABLE yyy(...);
75674 **
75675 ** Then pName1 is set to "yyy" and pName2 is "".
75676 **
75677 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
75678 ** pName2) that stores the unqualified table name.  The index of the
75679 ** database "xxx" is returned.
75680 */
75681 SQLITE_PRIVATE int sqlite3TwoPartName(
75682   Parse *pParse,      /* Parsing and code generating context */
75683   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
75684   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
75685   Token **pUnqual     /* Write the unqualified object name here */
75686 ){
75687   int iDb;                    /* Database holding the object */
75688   sqlite3 *db = pParse->db;
75689
75690   if( ALWAYS(pName2!=0) && pName2->n>0 ){
75691     if( db->init.busy ) {
75692       sqlite3ErrorMsg(pParse, "corrupt database");
75693       pParse->nErr++;
75694       return -1;
75695     }
75696     *pUnqual = pName2;
75697     iDb = sqlite3FindDb(db, pName1);
75698     if( iDb<0 ){
75699       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
75700       pParse->nErr++;
75701       return -1;
75702     }
75703   }else{
75704     assert( db->init.iDb==0 || db->init.busy );
75705     iDb = db->init.iDb;
75706     *pUnqual = pName1;
75707   }
75708   return iDb;
75709 }
75710
75711 /*
75712 ** This routine is used to check if the UTF-8 string zName is a legal
75713 ** unqualified name for a new schema object (table, index, view or
75714 ** trigger). All names are legal except those that begin with the string
75715 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
75716 ** is reserved for internal use.
75717 */
75718 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
75719   if( !pParse->db->init.busy && pParse->nested==0 
75720           && (pParse->db->flags & SQLITE_WriteSchema)==0
75721           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
75722     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
75723     return SQLITE_ERROR;
75724   }
75725   return SQLITE_OK;
75726 }
75727
75728 /*
75729 ** Begin constructing a new table representation in memory.  This is
75730 ** the first of several action routines that get called in response
75731 ** to a CREATE TABLE statement.  In particular, this routine is called
75732 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
75733 ** flag is true if the table should be stored in the auxiliary database
75734 ** file instead of in the main database file.  This is normally the case
75735 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
75736 ** CREATE and TABLE.
75737 **
75738 ** The new table record is initialized and put in pParse->pNewTable.
75739 ** As more of the CREATE TABLE statement is parsed, additional action
75740 ** routines will be called to add more information to this record.
75741 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
75742 ** is called to complete the construction of the new table record.
75743 */
75744 SQLITE_PRIVATE void sqlite3StartTable(
75745   Parse *pParse,   /* Parser context */
75746   Token *pName1,   /* First part of the name of the table or view */
75747   Token *pName2,   /* Second part of the name of the table or view */
75748   int isTemp,      /* True if this is a TEMP table */
75749   int isView,      /* True if this is a VIEW */
75750   int isVirtual,   /* True if this is a VIRTUAL table */
75751   int noErr        /* Do nothing if table already exists */
75752 ){
75753   Table *pTable;
75754   char *zName = 0; /* The name of the new table */
75755   sqlite3 *db = pParse->db;
75756   Vdbe *v;
75757   int iDb;         /* Database number to create the table in */
75758   Token *pName;    /* Unqualified name of the table to create */
75759
75760   /* The table or view name to create is passed to this routine via tokens
75761   ** pName1 and pName2. If the table name was fully qualified, for example:
75762   **
75763   ** CREATE TABLE xxx.yyy (...);
75764   ** 
75765   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
75766   ** the table name is not fully qualified, i.e.:
75767   **
75768   ** CREATE TABLE yyy(...);
75769   **
75770   ** Then pName1 is set to "yyy" and pName2 is "".
75771   **
75772   ** The call below sets the pName pointer to point at the token (pName1 or
75773   ** pName2) that stores the unqualified table name. The variable iDb is
75774   ** set to the index of the database that the table or view is to be
75775   ** created in.
75776   */
75777   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
75778   if( iDb<0 ) return;
75779   if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
75780     /* If creating a temp table, the name may not be qualified. Unless 
75781     ** the database name is "temp" anyway.  */
75782     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
75783     return;
75784   }
75785   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
75786
75787   pParse->sNameToken = *pName;
75788   zName = sqlite3NameFromToken(db, pName);
75789   if( zName==0 ) return;
75790   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
75791     goto begin_table_error;
75792   }
75793   if( db->init.iDb==1 ) isTemp = 1;
75794 #ifndef SQLITE_OMIT_AUTHORIZATION
75795   assert( (isTemp & 1)==isTemp );
75796   {
75797     int code;
75798     char *zDb = db->aDb[iDb].zName;
75799     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
75800       goto begin_table_error;
75801     }
75802     if( isView ){
75803       if( !OMIT_TEMPDB && isTemp ){
75804         code = SQLITE_CREATE_TEMP_VIEW;
75805       }else{
75806         code = SQLITE_CREATE_VIEW;
75807       }
75808     }else{
75809       if( !OMIT_TEMPDB && isTemp ){
75810         code = SQLITE_CREATE_TEMP_TABLE;
75811       }else{
75812         code = SQLITE_CREATE_TABLE;
75813       }
75814     }
75815     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
75816       goto begin_table_error;
75817     }
75818   }
75819 #endif
75820
75821   /* Make sure the new table name does not collide with an existing
75822   ** index or table name in the same database.  Issue an error message if
75823   ** it does. The exception is if the statement being parsed was passed
75824   ** to an sqlite3_declare_vtab() call. In that case only the column names
75825   ** and types will be used, so there is no need to test for namespace
75826   ** collisions.
75827   */
75828   if( !IN_DECLARE_VTAB ){
75829     char *zDb = db->aDb[iDb].zName;
75830     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
75831       goto begin_table_error;
75832     }
75833     pTable = sqlite3FindTable(db, zName, zDb);
75834     if( pTable ){
75835       if( !noErr ){
75836         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
75837       }
75838       goto begin_table_error;
75839     }
75840     if( sqlite3FindIndex(db, zName, zDb)!=0 ){
75841       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
75842       goto begin_table_error;
75843     }
75844   }
75845
75846   pTable = sqlite3DbMallocZero(db, sizeof(Table));
75847   if( pTable==0 ){
75848     db->mallocFailed = 1;
75849     pParse->rc = SQLITE_NOMEM;
75850     pParse->nErr++;
75851     goto begin_table_error;
75852   }
75853   pTable->zName = zName;
75854   pTable->iPKey = -1;
75855   pTable->pSchema = db->aDb[iDb].pSchema;
75856   pTable->nRef = 1;
75857   pTable->nRowEst = 1000000;
75858   assert( pParse->pNewTable==0 );
75859   pParse->pNewTable = pTable;
75860
75861   /* If this is the magic sqlite_sequence table used by autoincrement,
75862   ** then record a pointer to this table in the main database structure
75863   ** so that INSERT can find the table easily.
75864   */
75865 #ifndef SQLITE_OMIT_AUTOINCREMENT
75866   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
75867     pTable->pSchema->pSeqTab = pTable;
75868   }
75869 #endif
75870
75871   /* Begin generating the code that will insert the table record into
75872   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
75873   ** and allocate the record number for the table entry now.  Before any
75874   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
75875   ** indices to be created and the table record must come before the 
75876   ** indices.  Hence, the record number for the table must be allocated
75877   ** now.
75878   */
75879   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
75880     int j1;
75881     int fileFormat;
75882     int reg1, reg2, reg3;
75883     sqlite3BeginWriteOperation(pParse, 0, iDb);
75884
75885 #ifndef SQLITE_OMIT_VIRTUALTABLE
75886     if( isVirtual ){
75887       sqlite3VdbeAddOp0(v, OP_VBegin);
75888     }
75889 #endif
75890
75891     /* If the file format and encoding in the database have not been set, 
75892     ** set them now.
75893     */
75894     reg1 = pParse->regRowid = ++pParse->nMem;
75895     reg2 = pParse->regRoot = ++pParse->nMem;
75896     reg3 = ++pParse->nMem;
75897     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
75898     sqlite3VdbeUsesBtree(v, iDb);
75899     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
75900     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
75901                   1 : SQLITE_MAX_FILE_FORMAT;
75902     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
75903     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
75904     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
75905     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
75906     sqlite3VdbeJumpHere(v, j1);
75907
75908     /* This just creates a place-holder record in the sqlite_master table.
75909     ** The record created does not contain anything yet.  It will be replaced
75910     ** by the real entry in code generated at sqlite3EndTable().
75911     **
75912     ** The rowid for the new entry is left in register pParse->regRowid.
75913     ** The root page number of the new table is left in reg pParse->regRoot.
75914     ** The rowid and root page number values are needed by the code that
75915     ** sqlite3EndTable will generate.
75916     */
75917 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
75918     if( isView || isVirtual ){
75919       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
75920     }else
75921 #endif
75922     {
75923       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
75924     }
75925     sqlite3OpenMasterTable(pParse, iDb);
75926     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
75927     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
75928     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
75929     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
75930     sqlite3VdbeAddOp0(v, OP_Close);
75931   }
75932
75933   /* Normal (non-error) return. */
75934   return;
75935
75936   /* If an error occurs, we jump here */
75937 begin_table_error:
75938   sqlite3DbFree(db, zName);
75939   return;
75940 }
75941
75942 /*
75943 ** This macro is used to compare two strings in a case-insensitive manner.
75944 ** It is slightly faster than calling sqlite3StrICmp() directly, but
75945 ** produces larger code.
75946 **
75947 ** WARNING: This macro is not compatible with the strcmp() family. It
75948 ** returns true if the two strings are equal, otherwise false.
75949 */
75950 #define STRICMP(x, y) (\
75951 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
75952 sqlite3UpperToLower[*(unsigned char *)(y)]     \
75953 && sqlite3StrICmp((x)+1,(y)+1)==0 )
75954
75955 /*
75956 ** Add a new column to the table currently being constructed.
75957 **
75958 ** The parser calls this routine once for each column declaration
75959 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
75960 ** first to get things going.  Then this routine is called for each
75961 ** column.
75962 */
75963 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
75964   Table *p;
75965   int i;
75966   char *z;
75967   Column *pCol;
75968   sqlite3 *db = pParse->db;
75969   if( (p = pParse->pNewTable)==0 ) return;
75970 #if SQLITE_MAX_COLUMN
75971   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
75972     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
75973     return;
75974   }
75975 #endif
75976   z = sqlite3NameFromToken(db, pName);
75977   if( z==0 ) return;
75978   for(i=0; i<p->nCol; i++){
75979     if( STRICMP(z, p->aCol[i].zName) ){
75980       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
75981       sqlite3DbFree(db, z);
75982       return;
75983     }
75984   }
75985   if( (p->nCol & 0x7)==0 ){
75986     Column *aNew;
75987     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
75988     if( aNew==0 ){
75989       sqlite3DbFree(db, z);
75990       return;
75991     }
75992     p->aCol = aNew;
75993   }
75994   pCol = &p->aCol[p->nCol];
75995   memset(pCol, 0, sizeof(p->aCol[0]));
75996   pCol->zName = z;
75997  
75998   /* If there is no type specified, columns have the default affinity
75999   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
76000   ** be called next to set pCol->affinity correctly.
76001   */
76002   pCol->affinity = SQLITE_AFF_NONE;
76003   p->nCol++;
76004 }
76005
76006 /*
76007 ** This routine is called by the parser while in the middle of
76008 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
76009 ** been seen on a column.  This routine sets the notNull flag on
76010 ** the column currently under construction.
76011 */
76012 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
76013   Table *p;
76014   p = pParse->pNewTable;
76015   if( p==0 || NEVER(p->nCol<1) ) return;
76016   p->aCol[p->nCol-1].notNull = (u8)onError;
76017 }
76018
76019 /*
76020 ** Scan the column type name zType (length nType) and return the
76021 ** associated affinity type.
76022 **
76023 ** This routine does a case-independent search of zType for the 
76024 ** substrings in the following table. If one of the substrings is
76025 ** found, the corresponding affinity is returned. If zType contains
76026 ** more than one of the substrings, entries toward the top of 
76027 ** the table take priority. For example, if zType is 'BLOBINT', 
76028 ** SQLITE_AFF_INTEGER is returned.
76029 **
76030 ** Substring     | Affinity
76031 ** --------------------------------
76032 ** 'INT'         | SQLITE_AFF_INTEGER
76033 ** 'CHAR'        | SQLITE_AFF_TEXT
76034 ** 'CLOB'        | SQLITE_AFF_TEXT
76035 ** 'TEXT'        | SQLITE_AFF_TEXT
76036 ** 'BLOB'        | SQLITE_AFF_NONE
76037 ** 'REAL'        | SQLITE_AFF_REAL
76038 ** 'FLOA'        | SQLITE_AFF_REAL
76039 ** 'DOUB'        | SQLITE_AFF_REAL
76040 **
76041 ** If none of the substrings in the above table are found,
76042 ** SQLITE_AFF_NUMERIC is returned.
76043 */
76044 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
76045   u32 h = 0;
76046   char aff = SQLITE_AFF_NUMERIC;
76047
76048   if( zIn ) while( zIn[0] ){
76049     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
76050     zIn++;
76051     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
76052       aff = SQLITE_AFF_TEXT; 
76053     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
76054       aff = SQLITE_AFF_TEXT;
76055     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
76056       aff = SQLITE_AFF_TEXT;
76057     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
76058         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
76059       aff = SQLITE_AFF_NONE;
76060 #ifndef SQLITE_OMIT_FLOATING_POINT
76061     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
76062         && aff==SQLITE_AFF_NUMERIC ){
76063       aff = SQLITE_AFF_REAL;
76064     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
76065         && aff==SQLITE_AFF_NUMERIC ){
76066       aff = SQLITE_AFF_REAL;
76067     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
76068         && aff==SQLITE_AFF_NUMERIC ){
76069       aff = SQLITE_AFF_REAL;
76070 #endif
76071     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
76072       aff = SQLITE_AFF_INTEGER;
76073       break;
76074     }
76075   }
76076
76077   return aff;
76078 }
76079
76080 /*
76081 ** This routine is called by the parser while in the middle of
76082 ** parsing a CREATE TABLE statement.  The pFirst token is the first
76083 ** token in the sequence of tokens that describe the type of the
76084 ** column currently under construction.   pLast is the last token
76085 ** in the sequence.  Use this information to construct a string
76086 ** that contains the typename of the column and store that string
76087 ** in zType.
76088 */ 
76089 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
76090   Table *p;
76091   Column *pCol;
76092
76093   p = pParse->pNewTable;
76094   if( p==0 || NEVER(p->nCol<1) ) return;
76095   pCol = &p->aCol[p->nCol-1];
76096   assert( pCol->zType==0 );
76097   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
76098   pCol->affinity = sqlite3AffinityType(pCol->zType);
76099 }
76100
76101 /*
76102 ** The expression is the default value for the most recently added column
76103 ** of the table currently under construction.
76104 **
76105 ** Default value expressions must be constant.  Raise an exception if this
76106 ** is not the case.
76107 **
76108 ** This routine is called by the parser while in the middle of
76109 ** parsing a CREATE TABLE statement.
76110 */
76111 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
76112   Table *p;
76113   Column *pCol;
76114   sqlite3 *db = pParse->db;
76115   p = pParse->pNewTable;
76116   if( p!=0 ){
76117     pCol = &(p->aCol[p->nCol-1]);
76118     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
76119       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
76120           pCol->zName);
76121     }else{
76122       /* A copy of pExpr is used instead of the original, as pExpr contains
76123       ** tokens that point to volatile memory. The 'span' of the expression
76124       ** is required by pragma table_info.
76125       */
76126       sqlite3ExprDelete(db, pCol->pDflt);
76127       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
76128       sqlite3DbFree(db, pCol->zDflt);
76129       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
76130                                      (int)(pSpan->zEnd - pSpan->zStart));
76131     }
76132   }
76133   sqlite3ExprDelete(db, pSpan->pExpr);
76134 }
76135
76136 /*
76137 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
76138 ** of columns that form the primary key.  If pList is NULL, then the
76139 ** most recently added column of the table is the primary key.
76140 **
76141 ** A table can have at most one primary key.  If the table already has
76142 ** a primary key (and this is the second primary key) then create an
76143 ** error.
76144 **
76145 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
76146 ** then we will try to use that column as the rowid.  Set the Table.iPKey
76147 ** field of the table under construction to be the index of the
76148 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
76149 ** no INTEGER PRIMARY KEY.
76150 **
76151 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
76152 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
76153 */
76154 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
76155   Parse *pParse,    /* Parsing context */
76156   ExprList *pList,  /* List of field names to be indexed */
76157   int onError,      /* What to do with a uniqueness conflict */
76158   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
76159   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
76160 ){
76161   Table *pTab = pParse->pNewTable;
76162   char *zType = 0;
76163   int iCol = -1, i;
76164   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
76165   if( pTab->tabFlags & TF_HasPrimaryKey ){
76166     sqlite3ErrorMsg(pParse, 
76167       "table \"%s\" has more than one primary key", pTab->zName);
76168     goto primary_key_exit;
76169   }
76170   pTab->tabFlags |= TF_HasPrimaryKey;
76171   if( pList==0 ){
76172     iCol = pTab->nCol - 1;
76173     pTab->aCol[iCol].isPrimKey = 1;
76174   }else{
76175     for(i=0; i<pList->nExpr; i++){
76176       for(iCol=0; iCol<pTab->nCol; iCol++){
76177         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
76178           break;
76179         }
76180       }
76181       if( iCol<pTab->nCol ){
76182         pTab->aCol[iCol].isPrimKey = 1;
76183       }
76184     }
76185     if( pList->nExpr>1 ) iCol = -1;
76186   }
76187   if( iCol>=0 && iCol<pTab->nCol ){
76188     zType = pTab->aCol[iCol].zType;
76189   }
76190   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
76191         && sortOrder==SQLITE_SO_ASC ){
76192     pTab->iPKey = iCol;
76193     pTab->keyConf = (u8)onError;
76194     assert( autoInc==0 || autoInc==1 );
76195     pTab->tabFlags |= autoInc*TF_Autoincrement;
76196   }else if( autoInc ){
76197 #ifndef SQLITE_OMIT_AUTOINCREMENT
76198     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
76199        "INTEGER PRIMARY KEY");
76200 #endif
76201   }else{
76202     Index *p;
76203     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
76204     if( p ){
76205       p->autoIndex = 2;
76206     }
76207     pList = 0;
76208   }
76209
76210 primary_key_exit:
76211   sqlite3ExprListDelete(pParse->db, pList);
76212   return;
76213 }
76214
76215 /*
76216 ** Add a new CHECK constraint to the table currently under construction.
76217 */
76218 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
76219   Parse *pParse,    /* Parsing context */
76220   Expr *pCheckExpr  /* The check expression */
76221 ){
76222   sqlite3 *db = pParse->db;
76223 #ifndef SQLITE_OMIT_CHECK
76224   Table *pTab = pParse->pNewTable;
76225   if( pTab && !IN_DECLARE_VTAB ){
76226     pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
76227   }else
76228 #endif
76229   {
76230     sqlite3ExprDelete(db, pCheckExpr);
76231   }
76232 }
76233
76234 /*
76235 ** Set the collation function of the most recently parsed table column
76236 ** to the CollSeq given.
76237 */
76238 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
76239   Table *p;
76240   int i;
76241   char *zColl;              /* Dequoted name of collation sequence */
76242   sqlite3 *db;
76243
76244   if( (p = pParse->pNewTable)==0 ) return;
76245   i = p->nCol-1;
76246   db = pParse->db;
76247   zColl = sqlite3NameFromToken(db, pToken);
76248   if( !zColl ) return;
76249
76250   if( sqlite3LocateCollSeq(pParse, zColl) ){
76251     Index *pIdx;
76252     p->aCol[i].zColl = zColl;
76253   
76254     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
76255     ** then an index may have been created on this column before the
76256     ** collation type was added. Correct this if it is the case.
76257     */
76258     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
76259       assert( pIdx->nColumn==1 );
76260       if( pIdx->aiColumn[0]==i ){
76261         pIdx->azColl[0] = p->aCol[i].zColl;
76262       }
76263     }
76264   }else{
76265     sqlite3DbFree(db, zColl);
76266   }
76267 }
76268
76269 /*
76270 ** This function returns the collation sequence for database native text
76271 ** encoding identified by the string zName, length nName.
76272 **
76273 ** If the requested collation sequence is not available, or not available
76274 ** in the database native encoding, the collation factory is invoked to
76275 ** request it. If the collation factory does not supply such a sequence,
76276 ** and the sequence is available in another text encoding, then that is
76277 ** returned instead.
76278 **
76279 ** If no versions of the requested collations sequence are available, or
76280 ** another error occurs, NULL is returned and an error message written into
76281 ** pParse.
76282 **
76283 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
76284 ** invokes the collation factory if the named collation cannot be found
76285 ** and generates an error message.
76286 **
76287 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
76288 */
76289 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
76290   sqlite3 *db = pParse->db;
76291   u8 enc = ENC(db);
76292   u8 initbusy = db->init.busy;
76293   CollSeq *pColl;
76294
76295   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
76296   if( !initbusy && (!pColl || !pColl->xCmp) ){
76297     pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
76298     if( !pColl ){
76299       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
76300     }
76301   }
76302
76303   return pColl;
76304 }
76305
76306
76307 /*
76308 ** Generate code that will increment the schema cookie.
76309 **
76310 ** The schema cookie is used to determine when the schema for the
76311 ** database changes.  After each schema change, the cookie value
76312 ** changes.  When a process first reads the schema it records the
76313 ** cookie.  Thereafter, whenever it goes to access the database,
76314 ** it checks the cookie to make sure the schema has not changed
76315 ** since it was last read.
76316 **
76317 ** This plan is not completely bullet-proof.  It is possible for
76318 ** the schema to change multiple times and for the cookie to be
76319 ** set back to prior value.  But schema changes are infrequent
76320 ** and the probability of hitting the same cookie value is only
76321 ** 1 chance in 2^32.  So we're safe enough.
76322 */
76323 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
76324   int r1 = sqlite3GetTempReg(pParse);
76325   sqlite3 *db = pParse->db;
76326   Vdbe *v = pParse->pVdbe;
76327   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
76328   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
76329   sqlite3ReleaseTempReg(pParse, r1);
76330 }
76331
76332 /*
76333 ** Measure the number of characters needed to output the given
76334 ** identifier.  The number returned includes any quotes used
76335 ** but does not include the null terminator.
76336 **
76337 ** The estimate is conservative.  It might be larger that what is
76338 ** really needed.
76339 */
76340 static int identLength(const char *z){
76341   int n;
76342   for(n=0; *z; n++, z++){
76343     if( *z=='"' ){ n++; }
76344   }
76345   return n + 2;
76346 }
76347
76348 /*
76349 ** The first parameter is a pointer to an output buffer. The second 
76350 ** parameter is a pointer to an integer that contains the offset at
76351 ** which to write into the output buffer. This function copies the
76352 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
76353 ** to the specified offset in the buffer and updates *pIdx to refer
76354 ** to the first byte after the last byte written before returning.
76355 ** 
76356 ** If the string zSignedIdent consists entirely of alpha-numeric
76357 ** characters, does not begin with a digit and is not an SQL keyword,
76358 ** then it is copied to the output buffer exactly as it is. Otherwise,
76359 ** it is quoted using double-quotes.
76360 */
76361 static void identPut(char *z, int *pIdx, char *zSignedIdent){
76362   unsigned char *zIdent = (unsigned char*)zSignedIdent;
76363   int i, j, needQuote;
76364   i = *pIdx;
76365
76366   for(j=0; zIdent[j]; j++){
76367     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
76368   }
76369   needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
76370   if( !needQuote ){
76371     needQuote = zIdent[j];
76372   }
76373
76374   if( needQuote ) z[i++] = '"';
76375   for(j=0; zIdent[j]; j++){
76376     z[i++] = zIdent[j];
76377     if( zIdent[j]=='"' ) z[i++] = '"';
76378   }
76379   if( needQuote ) z[i++] = '"';
76380   z[i] = 0;
76381   *pIdx = i;
76382 }
76383
76384 /*
76385 ** Generate a CREATE TABLE statement appropriate for the given
76386 ** table.  Memory to hold the text of the statement is obtained
76387 ** from sqliteMalloc() and must be freed by the calling function.
76388 */
76389 static char *createTableStmt(sqlite3 *db, Table *p){
76390   int i, k, n;
76391   char *zStmt;
76392   char *zSep, *zSep2, *zEnd;
76393   Column *pCol;
76394   n = 0;
76395   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
76396     n += identLength(pCol->zName) + 5;
76397   }
76398   n += identLength(p->zName);
76399   if( n<50 ){ 
76400     zSep = "";
76401     zSep2 = ",";
76402     zEnd = ")";
76403   }else{
76404     zSep = "\n  ";
76405     zSep2 = ",\n  ";
76406     zEnd = "\n)";
76407   }
76408   n += 35 + 6*p->nCol;
76409   zStmt = sqlite3DbMallocRaw(0, n);
76410   if( zStmt==0 ){
76411     db->mallocFailed = 1;
76412     return 0;
76413   }
76414   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
76415   k = sqlite3Strlen30(zStmt);
76416   identPut(zStmt, &k, p->zName);
76417   zStmt[k++] = '(';
76418   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
76419     static const char * const azType[] = {
76420         /* SQLITE_AFF_TEXT    */ " TEXT",
76421         /* SQLITE_AFF_NONE    */ "",
76422         /* SQLITE_AFF_NUMERIC */ " NUM",
76423         /* SQLITE_AFF_INTEGER */ " INT",
76424         /* SQLITE_AFF_REAL    */ " REAL"
76425     };
76426     int len;
76427     const char *zType;
76428
76429     sqlite3_snprintf(n-k, &zStmt[k], zSep);
76430     k += sqlite3Strlen30(&zStmt[k]);
76431     zSep = zSep2;
76432     identPut(zStmt, &k, pCol->zName);
76433     assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
76434     assert( pCol->affinity-SQLITE_AFF_TEXT < sizeof(azType)/sizeof(azType[0]) );
76435     testcase( pCol->affinity==SQLITE_AFF_TEXT );
76436     testcase( pCol->affinity==SQLITE_AFF_NONE );
76437     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
76438     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
76439     testcase( pCol->affinity==SQLITE_AFF_REAL );
76440     
76441     zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
76442     len = sqlite3Strlen30(zType);
76443     assert( pCol->affinity==SQLITE_AFF_NONE 
76444             || pCol->affinity==sqlite3AffinityType(zType) );
76445     memcpy(&zStmt[k], zType, len);
76446     k += len;
76447     assert( k<=n );
76448   }
76449   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
76450   return zStmt;
76451 }
76452
76453 /*
76454 ** This routine is called to report the final ")" that terminates
76455 ** a CREATE TABLE statement.
76456 **
76457 ** The table structure that other action routines have been building
76458 ** is added to the internal hash tables, assuming no errors have
76459 ** occurred.
76460 **
76461 ** An entry for the table is made in the master table on disk, unless
76462 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
76463 ** it means we are reading the sqlite_master table because we just
76464 ** connected to the database or because the sqlite_master table has
76465 ** recently changed, so the entry for this table already exists in
76466 ** the sqlite_master table.  We do not want to create it again.
76467 **
76468 ** If the pSelect argument is not NULL, it means that this routine
76469 ** was called to create a table generated from a 
76470 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
76471 ** the new table will match the result set of the SELECT.
76472 */
76473 SQLITE_PRIVATE void sqlite3EndTable(
76474   Parse *pParse,          /* Parse context */
76475   Token *pCons,           /* The ',' token after the last column defn. */
76476   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
76477   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
76478 ){
76479   Table *p;
76480   sqlite3 *db = pParse->db;
76481   int iDb;
76482
76483   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
76484     return;
76485   }
76486   p = pParse->pNewTable;
76487   if( p==0 ) return;
76488
76489   assert( !db->init.busy || !pSelect );
76490
76491   iDb = sqlite3SchemaToIndex(db, p->pSchema);
76492
76493 #ifndef SQLITE_OMIT_CHECK
76494   /* Resolve names in all CHECK constraint expressions.
76495   */
76496   if( p->pCheck ){
76497     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
76498     NameContext sNC;                /* Name context for pParse->pNewTable */
76499
76500     memset(&sNC, 0, sizeof(sNC));
76501     memset(&sSrc, 0, sizeof(sSrc));
76502     sSrc.nSrc = 1;
76503     sSrc.a[0].zName = p->zName;
76504     sSrc.a[0].pTab = p;
76505     sSrc.a[0].iCursor = -1;
76506     sNC.pParse = pParse;
76507     sNC.pSrcList = &sSrc;
76508     sNC.isCheck = 1;
76509     if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
76510       return;
76511     }
76512   }
76513 #endif /* !defined(SQLITE_OMIT_CHECK) */
76514
76515   /* If the db->init.busy is 1 it means we are reading the SQL off the
76516   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
76517   ** So do not write to the disk again.  Extract the root page number
76518   ** for the table from the db->init.newTnum field.  (The page number
76519   ** should have been put there by the sqliteOpenCb routine.)
76520   */
76521   if( db->init.busy ){
76522     p->tnum = db->init.newTnum;
76523   }
76524
76525   /* If not initializing, then create a record for the new table
76526   ** in the SQLITE_MASTER table of the database.
76527   **
76528   ** If this is a TEMPORARY table, write the entry into the auxiliary
76529   ** file instead of into the main database file.
76530   */
76531   if( !db->init.busy ){
76532     int n;
76533     Vdbe *v;
76534     char *zType;    /* "view" or "table" */
76535     char *zType2;   /* "VIEW" or "TABLE" */
76536     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
76537
76538     v = sqlite3GetVdbe(pParse);
76539     if( NEVER(v==0) ) return;
76540
76541     sqlite3VdbeAddOp1(v, OP_Close, 0);
76542
76543     /* 
76544     ** Initialize zType for the new view or table.
76545     */
76546     if( p->pSelect==0 ){
76547       /* A regular table */
76548       zType = "table";
76549       zType2 = "TABLE";
76550 #ifndef SQLITE_OMIT_VIEW
76551     }else{
76552       /* A view */
76553       zType = "view";
76554       zType2 = "VIEW";
76555 #endif
76556     }
76557
76558     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
76559     ** statement to populate the new table. The root-page number for the
76560     ** new table is in register pParse->regRoot.
76561     **
76562     ** Once the SELECT has been coded by sqlite3Select(), it is in a
76563     ** suitable state to query for the column names and types to be used
76564     ** by the new table.
76565     **
76566     ** A shared-cache write-lock is not required to write to the new table,
76567     ** as a schema-lock must have already been obtained to create it. Since
76568     ** a schema-lock excludes all other database users, the write-lock would
76569     ** be redundant.
76570     */
76571     if( pSelect ){
76572       SelectDest dest;
76573       Table *pSelTab;
76574
76575       assert(pParse->nTab==1);
76576       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
76577       sqlite3VdbeChangeP5(v, 1);
76578       pParse->nTab = 2;
76579       sqlite3SelectDestInit(&dest, SRT_Table, 1);
76580       sqlite3Select(pParse, pSelect, &dest);
76581       sqlite3VdbeAddOp1(v, OP_Close, 1);
76582       if( pParse->nErr==0 ){
76583         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
76584         if( pSelTab==0 ) return;
76585         assert( p->aCol==0 );
76586         p->nCol = pSelTab->nCol;
76587         p->aCol = pSelTab->aCol;
76588         pSelTab->nCol = 0;
76589         pSelTab->aCol = 0;
76590         sqlite3DeleteTable(db, pSelTab);
76591       }
76592     }
76593
76594     /* Compute the complete text of the CREATE statement */
76595     if( pSelect ){
76596       zStmt = createTableStmt(db, p);
76597     }else{
76598       n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
76599       zStmt = sqlite3MPrintf(db, 
76600           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
76601       );
76602     }
76603
76604     /* A slot for the record has already been allocated in the 
76605     ** SQLITE_MASTER table.  We just need to update that slot with all
76606     ** the information we've collected.
76607     */
76608     sqlite3NestedParse(pParse,
76609       "UPDATE %Q.%s "
76610          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
76611        "WHERE rowid=#%d",
76612       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
76613       zType,
76614       p->zName,
76615       p->zName,
76616       pParse->regRoot,
76617       zStmt,
76618       pParse->regRowid
76619     );
76620     sqlite3DbFree(db, zStmt);
76621     sqlite3ChangeCookie(pParse, iDb);
76622
76623 #ifndef SQLITE_OMIT_AUTOINCREMENT
76624     /* Check to see if we need to create an sqlite_sequence table for
76625     ** keeping track of autoincrement keys.
76626     */
76627     if( p->tabFlags & TF_Autoincrement ){
76628       Db *pDb = &db->aDb[iDb];
76629       if( pDb->pSchema->pSeqTab==0 ){
76630         sqlite3NestedParse(pParse,
76631           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
76632           pDb->zName
76633         );
76634       }
76635     }
76636 #endif
76637
76638     /* Reparse everything to update our internal data structures */
76639     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
76640         sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
76641   }
76642
76643
76644   /* Add the table to the in-memory representation of the database.
76645   */
76646   if( db->init.busy ){
76647     Table *pOld;
76648     Schema *pSchema = p->pSchema;
76649     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
76650                              sqlite3Strlen30(p->zName),p);
76651     if( pOld ){
76652       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
76653       db->mallocFailed = 1;
76654       return;
76655     }
76656     pParse->pNewTable = 0;
76657     db->nTable++;
76658     db->flags |= SQLITE_InternChanges;
76659
76660 #ifndef SQLITE_OMIT_ALTERTABLE
76661     if( !p->pSelect ){
76662       const char *zName = (const char *)pParse->sNameToken.z;
76663       int nName;
76664       assert( !pSelect && pCons && pEnd );
76665       if( pCons->z==0 ){
76666         pCons = pEnd;
76667       }
76668       nName = (int)((const char *)pCons->z - zName);
76669       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
76670     }
76671 #endif
76672   }
76673 }
76674
76675 #ifndef SQLITE_OMIT_VIEW
76676 /*
76677 ** The parser calls this routine in order to create a new VIEW
76678 */
76679 SQLITE_PRIVATE void sqlite3CreateView(
76680   Parse *pParse,     /* The parsing context */
76681   Token *pBegin,     /* The CREATE token that begins the statement */
76682   Token *pName1,     /* The token that holds the name of the view */
76683   Token *pName2,     /* The token that holds the name of the view */
76684   Select *pSelect,   /* A SELECT statement that will become the new view */
76685   int isTemp,        /* TRUE for a TEMPORARY view */
76686   int noErr          /* Suppress error messages if VIEW already exists */
76687 ){
76688   Table *p;
76689   int n;
76690   const char *z;
76691   Token sEnd;
76692   DbFixer sFix;
76693   Token *pName;
76694   int iDb;
76695   sqlite3 *db = pParse->db;
76696
76697   if( pParse->nVar>0 ){
76698     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
76699     sqlite3SelectDelete(db, pSelect);
76700     return;
76701   }
76702   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
76703   p = pParse->pNewTable;
76704   if( p==0 || pParse->nErr ){
76705     sqlite3SelectDelete(db, pSelect);
76706     return;
76707   }
76708   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
76709   iDb = sqlite3SchemaToIndex(db, p->pSchema);
76710   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
76711     && sqlite3FixSelect(&sFix, pSelect)
76712   ){
76713     sqlite3SelectDelete(db, pSelect);
76714     return;
76715   }
76716
76717   /* Make a copy of the entire SELECT statement that defines the view.
76718   ** This will force all the Expr.token.z values to be dynamically
76719   ** allocated rather than point to the input string - which means that
76720   ** they will persist after the current sqlite3_exec() call returns.
76721   */
76722   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
76723   sqlite3SelectDelete(db, pSelect);
76724   if( db->mallocFailed ){
76725     return;
76726   }
76727   if( !db->init.busy ){
76728     sqlite3ViewGetColumnNames(pParse, p);
76729   }
76730
76731   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
76732   ** the end.
76733   */
76734   sEnd = pParse->sLastToken;
76735   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
76736     sEnd.z += sEnd.n;
76737   }
76738   sEnd.n = 0;
76739   n = (int)(sEnd.z - pBegin->z);
76740   z = pBegin->z;
76741   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
76742   sEnd.z = &z[n-1];
76743   sEnd.n = 1;
76744
76745   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
76746   sqlite3EndTable(pParse, 0, &sEnd, 0);
76747   return;
76748 }
76749 #endif /* SQLITE_OMIT_VIEW */
76750
76751 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
76752 /*
76753 ** The Table structure pTable is really a VIEW.  Fill in the names of
76754 ** the columns of the view in the pTable structure.  Return the number
76755 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
76756 */
76757 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
76758   Table *pSelTab;   /* A fake table from which we get the result set */
76759   Select *pSel;     /* Copy of the SELECT that implements the view */
76760   int nErr = 0;     /* Number of errors encountered */
76761   int n;            /* Temporarily holds the number of cursors assigned */
76762   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
76763   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
76764
76765   assert( pTable );
76766
76767 #ifndef SQLITE_OMIT_VIRTUALTABLE
76768   if( sqlite3VtabCallConnect(pParse, pTable) ){
76769     return SQLITE_ERROR;
76770   }
76771   if( IsVirtual(pTable) ) return 0;
76772 #endif
76773
76774 #ifndef SQLITE_OMIT_VIEW
76775   /* A positive nCol means the columns names for this view are
76776   ** already known.
76777   */
76778   if( pTable->nCol>0 ) return 0;
76779
76780   /* A negative nCol is a special marker meaning that we are currently
76781   ** trying to compute the column names.  If we enter this routine with
76782   ** a negative nCol, it means two or more views form a loop, like this:
76783   **
76784   **     CREATE VIEW one AS SELECT * FROM two;
76785   **     CREATE VIEW two AS SELECT * FROM one;
76786   **
76787   ** Actually, the error above is now caught prior to reaching this point.
76788   ** But the following test is still important as it does come up
76789   ** in the following:
76790   ** 
76791   **     CREATE TABLE main.ex1(a);
76792   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
76793   **     SELECT * FROM temp.ex1;
76794   */
76795   if( pTable->nCol<0 ){
76796     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
76797     return 1;
76798   }
76799   assert( pTable->nCol>=0 );
76800
76801   /* If we get this far, it means we need to compute the table names.
76802   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
76803   ** "*" elements in the results set of the view and will assign cursors
76804   ** to the elements of the FROM clause.  But we do not want these changes
76805   ** to be permanent.  So the computation is done on a copy of the SELECT
76806   ** statement that defines the view.
76807   */
76808   assert( pTable->pSelect );
76809   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
76810   if( pSel ){
76811     u8 enableLookaside = db->lookaside.bEnabled;
76812     n = pParse->nTab;
76813     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
76814     pTable->nCol = -1;
76815     db->lookaside.bEnabled = 0;
76816 #ifndef SQLITE_OMIT_AUTHORIZATION
76817     xAuth = db->xAuth;
76818     db->xAuth = 0;
76819     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
76820     db->xAuth = xAuth;
76821 #else
76822     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
76823 #endif
76824     db->lookaside.bEnabled = enableLookaside;
76825     pParse->nTab = n;
76826     if( pSelTab ){
76827       assert( pTable->aCol==0 );
76828       pTable->nCol = pSelTab->nCol;
76829       pTable->aCol = pSelTab->aCol;
76830       pSelTab->nCol = 0;
76831       pSelTab->aCol = 0;
76832       sqlite3DeleteTable(db, pSelTab);
76833       pTable->pSchema->flags |= DB_UnresetViews;
76834     }else{
76835       pTable->nCol = 0;
76836       nErr++;
76837     }
76838     sqlite3SelectDelete(db, pSel);
76839   } else {
76840     nErr++;
76841   }
76842 #endif /* SQLITE_OMIT_VIEW */
76843   return nErr;  
76844 }
76845 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
76846
76847 #ifndef SQLITE_OMIT_VIEW
76848 /*
76849 ** Clear the column names from every VIEW in database idx.
76850 */
76851 static void sqliteViewResetAll(sqlite3 *db, int idx){
76852   HashElem *i;
76853   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
76854   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
76855     Table *pTab = sqliteHashData(i);
76856     if( pTab->pSelect ){
76857       sqliteDeleteColumnNames(db, pTab);
76858       pTab->aCol = 0;
76859       pTab->nCol = 0;
76860     }
76861   }
76862   DbClearProperty(db, idx, DB_UnresetViews);
76863 }
76864 #else
76865 # define sqliteViewResetAll(A,B)
76866 #endif /* SQLITE_OMIT_VIEW */
76867
76868 /*
76869 ** This function is called by the VDBE to adjust the internal schema
76870 ** used by SQLite when the btree layer moves a table root page. The
76871 ** root-page of a table or index in database iDb has changed from iFrom
76872 ** to iTo.
76873 **
76874 ** Ticket #1728:  The symbol table might still contain information
76875 ** on tables and/or indices that are the process of being deleted.
76876 ** If you are unlucky, one of those deleted indices or tables might
76877 ** have the same rootpage number as the real table or index that is
76878 ** being moved.  So we cannot stop searching after the first match 
76879 ** because the first match might be for one of the deleted indices
76880 ** or tables and not the table/index that is actually being moved.
76881 ** We must continue looping until all tables and indices with
76882 ** rootpage==iFrom have been converted to have a rootpage of iTo
76883 ** in order to be certain that we got the right one.
76884 */
76885 #ifndef SQLITE_OMIT_AUTOVACUUM
76886 SQLITE_PRIVATE void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
76887   HashElem *pElem;
76888   Hash *pHash;
76889
76890   pHash = &pDb->pSchema->tblHash;
76891   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
76892     Table *pTab = sqliteHashData(pElem);
76893     if( pTab->tnum==iFrom ){
76894       pTab->tnum = iTo;
76895     }
76896   }
76897   pHash = &pDb->pSchema->idxHash;
76898   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
76899     Index *pIdx = sqliteHashData(pElem);
76900     if( pIdx->tnum==iFrom ){
76901       pIdx->tnum = iTo;
76902     }
76903   }
76904 }
76905 #endif
76906
76907 /*
76908 ** Write code to erase the table with root-page iTable from database iDb.
76909 ** Also write code to modify the sqlite_master table and internal schema
76910 ** if a root-page of another table is moved by the btree-layer whilst
76911 ** erasing iTable (this can happen with an auto-vacuum database).
76912 */ 
76913 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
76914   Vdbe *v = sqlite3GetVdbe(pParse);
76915   int r1 = sqlite3GetTempReg(pParse);
76916   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
76917   sqlite3MayAbort(pParse);
76918 #ifndef SQLITE_OMIT_AUTOVACUUM
76919   /* OP_Destroy stores an in integer r1. If this integer
76920   ** is non-zero, then it is the root page number of a table moved to
76921   ** location iTable. The following code modifies the sqlite_master table to
76922   ** reflect this.
76923   **
76924   ** The "#NNN" in the SQL is a special constant that means whatever value
76925   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
76926   ** token for additional information.
76927   */
76928   sqlite3NestedParse(pParse, 
76929      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
76930      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
76931 #endif
76932   sqlite3ReleaseTempReg(pParse, r1);
76933 }
76934
76935 /*
76936 ** Write VDBE code to erase table pTab and all associated indices on disk.
76937 ** Code to update the sqlite_master tables and internal schema definitions
76938 ** in case a root-page belonging to another table is moved by the btree layer
76939 ** is also added (this can happen with an auto-vacuum database).
76940 */
76941 static void destroyTable(Parse *pParse, Table *pTab){
76942 #ifdef SQLITE_OMIT_AUTOVACUUM
76943   Index *pIdx;
76944   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
76945   destroyRootPage(pParse, pTab->tnum, iDb);
76946   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
76947     destroyRootPage(pParse, pIdx->tnum, iDb);
76948   }
76949 #else
76950   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
76951   ** is not defined), then it is important to call OP_Destroy on the
76952   ** table and index root-pages in order, starting with the numerically 
76953   ** largest root-page number. This guarantees that none of the root-pages
76954   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
76955   ** following were coded:
76956   **
76957   ** OP_Destroy 4 0
76958   ** ...
76959   ** OP_Destroy 5 0
76960   **
76961   ** and root page 5 happened to be the largest root-page number in the
76962   ** database, then root page 5 would be moved to page 4 by the 
76963   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
76964   ** a free-list page.
76965   */
76966   int iTab = pTab->tnum;
76967   int iDestroyed = 0;
76968
76969   while( 1 ){
76970     Index *pIdx;
76971     int iLargest = 0;
76972
76973     if( iDestroyed==0 || iTab<iDestroyed ){
76974       iLargest = iTab;
76975     }
76976     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
76977       int iIdx = pIdx->tnum;
76978       assert( pIdx->pSchema==pTab->pSchema );
76979       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
76980         iLargest = iIdx;
76981       }
76982     }
76983     if( iLargest==0 ){
76984       return;
76985     }else{
76986       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
76987       destroyRootPage(pParse, iLargest, iDb);
76988       iDestroyed = iLargest;
76989     }
76990   }
76991 #endif
76992 }
76993
76994 /*
76995 ** This routine is called to do the work of a DROP TABLE statement.
76996 ** pName is the name of the table to be dropped.
76997 */
76998 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
76999   Table *pTab;
77000   Vdbe *v;
77001   sqlite3 *db = pParse->db;
77002   int iDb;
77003
77004   if( db->mallocFailed ){
77005     goto exit_drop_table;
77006   }
77007   assert( pParse->nErr==0 );
77008   assert( pName->nSrc==1 );
77009   if( noErr ) db->suppressErr++;
77010   pTab = sqlite3LocateTable(pParse, isView, 
77011                             pName->a[0].zName, pName->a[0].zDatabase);
77012   if( noErr ) db->suppressErr--;
77013
77014   if( pTab==0 ){
77015     goto exit_drop_table;
77016   }
77017   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
77018   assert( iDb>=0 && iDb<db->nDb );
77019
77020   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
77021   ** it is initialized.
77022   */
77023   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
77024     goto exit_drop_table;
77025   }
77026 #ifndef SQLITE_OMIT_AUTHORIZATION
77027   {
77028     int code;
77029     const char *zTab = SCHEMA_TABLE(iDb);
77030     const char *zDb = db->aDb[iDb].zName;
77031     const char *zArg2 = 0;
77032     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
77033       goto exit_drop_table;
77034     }
77035     if( isView ){
77036       if( !OMIT_TEMPDB && iDb==1 ){
77037         code = SQLITE_DROP_TEMP_VIEW;
77038       }else{
77039         code = SQLITE_DROP_VIEW;
77040       }
77041 #ifndef SQLITE_OMIT_VIRTUALTABLE
77042     }else if( IsVirtual(pTab) ){
77043       code = SQLITE_DROP_VTABLE;
77044       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
77045 #endif
77046     }else{
77047       if( !OMIT_TEMPDB && iDb==1 ){
77048         code = SQLITE_DROP_TEMP_TABLE;
77049       }else{
77050         code = SQLITE_DROP_TABLE;
77051       }
77052     }
77053     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
77054       goto exit_drop_table;
77055     }
77056     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
77057       goto exit_drop_table;
77058     }
77059   }
77060 #endif
77061   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
77062     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
77063     goto exit_drop_table;
77064   }
77065
77066 #ifndef SQLITE_OMIT_VIEW
77067   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
77068   ** on a table.
77069   */
77070   if( isView && pTab->pSelect==0 ){
77071     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
77072     goto exit_drop_table;
77073   }
77074   if( !isView && pTab->pSelect ){
77075     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
77076     goto exit_drop_table;
77077   }
77078 #endif
77079
77080   /* Generate code to remove the table from the master table
77081   ** on disk.
77082   */
77083   v = sqlite3GetVdbe(pParse);
77084   if( v ){
77085     Trigger *pTrigger;
77086     Db *pDb = &db->aDb[iDb];
77087     sqlite3BeginWriteOperation(pParse, 1, iDb);
77088
77089 #ifndef SQLITE_OMIT_VIRTUALTABLE
77090     if( IsVirtual(pTab) ){
77091       sqlite3VdbeAddOp0(v, OP_VBegin);
77092     }
77093 #endif
77094     sqlite3FkDropTable(pParse, pName, pTab);
77095
77096     /* Drop all triggers associated with the table being dropped. Code
77097     ** is generated to remove entries from sqlite_master and/or
77098     ** sqlite_temp_master if required.
77099     */
77100     pTrigger = sqlite3TriggerList(pParse, pTab);
77101     while( pTrigger ){
77102       assert( pTrigger->pSchema==pTab->pSchema || 
77103           pTrigger->pSchema==db->aDb[1].pSchema );
77104       sqlite3DropTriggerPtr(pParse, pTrigger);
77105       pTrigger = pTrigger->pNext;
77106     }
77107
77108 #ifndef SQLITE_OMIT_AUTOINCREMENT
77109     /* Remove any entries of the sqlite_sequence table associated with
77110     ** the table being dropped. This is done before the table is dropped
77111     ** at the btree level, in case the sqlite_sequence table needs to
77112     ** move as a result of the drop (can happen in auto-vacuum mode).
77113     */
77114     if( pTab->tabFlags & TF_Autoincrement ){
77115       sqlite3NestedParse(pParse,
77116         "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
77117         pDb->zName, pTab->zName
77118       );
77119     }
77120 #endif
77121
77122     /* Drop all SQLITE_MASTER table and index entries that refer to the
77123     ** table. The program name loops through the master table and deletes
77124     ** every row that refers to a table of the same name as the one being
77125     ** dropped. Triggers are handled seperately because a trigger can be
77126     ** created in the temp database that refers to a table in another
77127     ** database.
77128     */
77129     sqlite3NestedParse(pParse, 
77130         "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
77131         pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
77132
77133     /* Drop any statistics from the sqlite_stat1 table, if it exists */
77134     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
77135       sqlite3NestedParse(pParse,
77136         "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
77137       );
77138     }
77139
77140     if( !isView && !IsVirtual(pTab) ){
77141       destroyTable(pParse, pTab);
77142     }
77143
77144     /* Remove the table entry from SQLite's internal schema and modify
77145     ** the schema cookie.
77146     */
77147     if( IsVirtual(pTab) ){
77148       sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
77149     }
77150     sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
77151     sqlite3ChangeCookie(pParse, iDb);
77152   }
77153   sqliteViewResetAll(db, iDb);
77154
77155 exit_drop_table:
77156   sqlite3SrcListDelete(db, pName);
77157 }
77158
77159 /*
77160 ** This routine is called to create a new foreign key on the table
77161 ** currently under construction.  pFromCol determines which columns
77162 ** in the current table point to the foreign key.  If pFromCol==0 then
77163 ** connect the key to the last column inserted.  pTo is the name of
77164 ** the table referred to.  pToCol is a list of tables in the other
77165 ** pTo table that the foreign key points to.  flags contains all
77166 ** information about the conflict resolution algorithms specified
77167 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
77168 **
77169 ** An FKey structure is created and added to the table currently
77170 ** under construction in the pParse->pNewTable field.
77171 **
77172 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
77173 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
77174 */
77175 SQLITE_PRIVATE void sqlite3CreateForeignKey(
77176   Parse *pParse,       /* Parsing context */
77177   ExprList *pFromCol,  /* Columns in this table that point to other table */
77178   Token *pTo,          /* Name of the other table */
77179   ExprList *pToCol,    /* Columns in the other table */
77180   int flags            /* Conflict resolution algorithms. */
77181 ){
77182   sqlite3 *db = pParse->db;
77183 #ifndef SQLITE_OMIT_FOREIGN_KEY
77184   FKey *pFKey = 0;
77185   FKey *pNextTo;
77186   Table *p = pParse->pNewTable;
77187   int nByte;
77188   int i;
77189   int nCol;
77190   char *z;
77191
77192   assert( pTo!=0 );
77193   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
77194   if( pFromCol==0 ){
77195     int iCol = p->nCol-1;
77196     if( NEVER(iCol<0) ) goto fk_end;
77197     if( pToCol && pToCol->nExpr!=1 ){
77198       sqlite3ErrorMsg(pParse, "foreign key on %s"
77199          " should reference only one column of table %T",
77200          p->aCol[iCol].zName, pTo);
77201       goto fk_end;
77202     }
77203     nCol = 1;
77204   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
77205     sqlite3ErrorMsg(pParse,
77206         "number of columns in foreign key does not match the number of "
77207         "columns in the referenced table");
77208     goto fk_end;
77209   }else{
77210     nCol = pFromCol->nExpr;
77211   }
77212   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
77213   if( pToCol ){
77214     for(i=0; i<pToCol->nExpr; i++){
77215       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
77216     }
77217   }
77218   pFKey = sqlite3DbMallocZero(db, nByte );
77219   if( pFKey==0 ){
77220     goto fk_end;
77221   }
77222   pFKey->pFrom = p;
77223   pFKey->pNextFrom = p->pFKey;
77224   z = (char*)&pFKey->aCol[nCol];
77225   pFKey->zTo = z;
77226   memcpy(z, pTo->z, pTo->n);
77227   z[pTo->n] = 0;
77228   sqlite3Dequote(z);
77229   z += pTo->n+1;
77230   pFKey->nCol = nCol;
77231   if( pFromCol==0 ){
77232     pFKey->aCol[0].iFrom = p->nCol-1;
77233   }else{
77234     for(i=0; i<nCol; i++){
77235       int j;
77236       for(j=0; j<p->nCol; j++){
77237         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
77238           pFKey->aCol[i].iFrom = j;
77239           break;
77240         }
77241       }
77242       if( j>=p->nCol ){
77243         sqlite3ErrorMsg(pParse, 
77244           "unknown column \"%s\" in foreign key definition", 
77245           pFromCol->a[i].zName);
77246         goto fk_end;
77247       }
77248     }
77249   }
77250   if( pToCol ){
77251     for(i=0; i<nCol; i++){
77252       int n = sqlite3Strlen30(pToCol->a[i].zName);
77253       pFKey->aCol[i].zCol = z;
77254       memcpy(z, pToCol->a[i].zName, n);
77255       z[n] = 0;
77256       z += n+1;
77257     }
77258   }
77259   pFKey->isDeferred = 0;
77260   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
77261   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
77262
77263   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 
77264       pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
77265   );
77266   if( pNextTo==pFKey ){
77267     db->mallocFailed = 1;
77268     goto fk_end;
77269   }
77270   if( pNextTo ){
77271     assert( pNextTo->pPrevTo==0 );
77272     pFKey->pNextTo = pNextTo;
77273     pNextTo->pPrevTo = pFKey;
77274   }
77275
77276   /* Link the foreign key to the table as the last step.
77277   */
77278   p->pFKey = pFKey;
77279   pFKey = 0;
77280
77281 fk_end:
77282   sqlite3DbFree(db, pFKey);
77283 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
77284   sqlite3ExprListDelete(db, pFromCol);
77285   sqlite3ExprListDelete(db, pToCol);
77286 }
77287
77288 /*
77289 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
77290 ** clause is seen as part of a foreign key definition.  The isDeferred
77291 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
77292 ** The behavior of the most recently created foreign key is adjusted
77293 ** accordingly.
77294 */
77295 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
77296 #ifndef SQLITE_OMIT_FOREIGN_KEY
77297   Table *pTab;
77298   FKey *pFKey;
77299   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
77300   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
77301   pFKey->isDeferred = (u8)isDeferred;
77302 #endif
77303 }
77304
77305 /*
77306 ** Generate code that will erase and refill index *pIdx.  This is
77307 ** used to initialize a newly created index or to recompute the
77308 ** content of an index in response to a REINDEX command.
77309 **
77310 ** if memRootPage is not negative, it means that the index is newly
77311 ** created.  The register specified by memRootPage contains the
77312 ** root page number of the index.  If memRootPage is negative, then
77313 ** the index already exists and must be cleared before being refilled and
77314 ** the root page number of the index is taken from pIndex->tnum.
77315 */
77316 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
77317   Table *pTab = pIndex->pTable;  /* The table that is indexed */
77318   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
77319   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
77320   int addr1;                     /* Address of top of loop */
77321   int tnum;                      /* Root page of index */
77322   Vdbe *v;                       /* Generate code into this virtual machine */
77323   KeyInfo *pKey;                 /* KeyInfo for index */
77324   int regIdxKey;                 /* Registers containing the index key */
77325   int regRecord;                 /* Register holding assemblied index record */
77326   sqlite3 *db = pParse->db;      /* The database connection */
77327   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
77328
77329 #ifndef SQLITE_OMIT_AUTHORIZATION
77330   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
77331       db->aDb[iDb].zName ) ){
77332     return;
77333   }
77334 #endif
77335
77336   /* Require a write-lock on the table to perform this operation */
77337   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
77338
77339   v = sqlite3GetVdbe(pParse);
77340   if( v==0 ) return;
77341   if( memRootPage>=0 ){
77342     tnum = memRootPage;
77343   }else{
77344     tnum = pIndex->tnum;
77345     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
77346   }
77347   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
77348   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
77349                     (char *)pKey, P4_KEYINFO_HANDOFF);
77350   if( memRootPage>=0 ){
77351     sqlite3VdbeChangeP5(v, 1);
77352   }
77353   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
77354   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
77355   regRecord = sqlite3GetTempReg(pParse);
77356   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
77357   if( pIndex->onError!=OE_None ){
77358     const int regRowid = regIdxKey + pIndex->nColumn;
77359     const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
77360     void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
77361
77362     /* The registers accessed by the OP_IsUnique opcode were allocated
77363     ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
77364     ** call above. Just before that function was freed they were released
77365     ** (made available to the compiler for reuse) using 
77366     ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
77367     ** opcode use the values stored within seems dangerous. However, since
77368     ** we can be sure that no other temp registers have been allocated
77369     ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
77370     */
77371     sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
77372     sqlite3HaltConstraint(
77373         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
77374   }
77375   sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
77376   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
77377   sqlite3ReleaseTempReg(pParse, regRecord);
77378   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
77379   sqlite3VdbeJumpHere(v, addr1);
77380   sqlite3VdbeAddOp1(v, OP_Close, iTab);
77381   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
77382 }
77383
77384 /*
77385 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
77386 ** and pTblList is the name of the table that is to be indexed.  Both will 
77387 ** be NULL for a primary key or an index that is created to satisfy a
77388 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
77389 ** as the table to be indexed.  pParse->pNewTable is a table that is
77390 ** currently being constructed by a CREATE TABLE statement.
77391 **
77392 ** pList is a list of columns to be indexed.  pList will be NULL if this
77393 ** is a primary key or unique-constraint on the most recent column added
77394 ** to the table currently under construction.  
77395 **
77396 ** If the index is created successfully, return a pointer to the new Index
77397 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
77398 ** as the tables primary key (Index.autoIndex==2).
77399 */
77400 SQLITE_PRIVATE Index *sqlite3CreateIndex(
77401   Parse *pParse,     /* All information about this parse */
77402   Token *pName1,     /* First part of index name. May be NULL */
77403   Token *pName2,     /* Second part of index name. May be NULL */
77404   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
77405   ExprList *pList,   /* A list of columns to be indexed */
77406   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
77407   Token *pStart,     /* The CREATE token that begins this statement */
77408   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
77409   int sortOrder,     /* Sort order of primary key when pList==NULL */
77410   int ifNotExist     /* Omit error if index already exists */
77411 ){
77412   Index *pRet = 0;     /* Pointer to return */
77413   Table *pTab = 0;     /* Table to be indexed */
77414   Index *pIndex = 0;   /* The index to be created */
77415   char *zName = 0;     /* Name of the index */
77416   int nName;           /* Number of characters in zName */
77417   int i, j;
77418   Token nullId;        /* Fake token for an empty ID list */
77419   DbFixer sFix;        /* For assigning database names to pTable */
77420   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
77421   sqlite3 *db = pParse->db;
77422   Db *pDb;             /* The specific table containing the indexed database */
77423   int iDb;             /* Index of the database that is being written */
77424   Token *pName = 0;    /* Unqualified name of the index to create */
77425   struct ExprList_item *pListItem; /* For looping over pList */
77426   int nCol;
77427   int nExtra = 0;
77428   char *zExtra;
77429
77430   assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
77431   assert( pParse->nErr==0 );      /* Never called with prior errors */
77432   if( db->mallocFailed || IN_DECLARE_VTAB ){
77433     goto exit_create_index;
77434   }
77435   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
77436     goto exit_create_index;
77437   }
77438
77439   /*
77440   ** Find the table that is to be indexed.  Return early if not found.
77441   */
77442   if( pTblName!=0 ){
77443
77444     /* Use the two-part index name to determine the database 
77445     ** to search for the table. 'Fix' the table name to this db
77446     ** before looking up the table.
77447     */
77448     assert( pName1 && pName2 );
77449     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
77450     if( iDb<0 ) goto exit_create_index;
77451
77452 #ifndef SQLITE_OMIT_TEMPDB
77453     /* If the index name was unqualified, check if the the table
77454     ** is a temp table. If so, set the database to 1. Do not do this
77455     ** if initialising a database schema.
77456     */
77457     if( !db->init.busy ){
77458       pTab = sqlite3SrcListLookup(pParse, pTblName);
77459       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
77460         iDb = 1;
77461       }
77462     }
77463 #endif
77464
77465     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
77466         sqlite3FixSrcList(&sFix, pTblName)
77467     ){
77468       /* Because the parser constructs pTblName from a single identifier,
77469       ** sqlite3FixSrcList can never fail. */
77470       assert(0);
77471     }
77472     pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, 
77473         pTblName->a[0].zDatabase);
77474     if( !pTab || db->mallocFailed ) goto exit_create_index;
77475     assert( db->aDb[iDb].pSchema==pTab->pSchema );
77476   }else{
77477     assert( pName==0 );
77478     pTab = pParse->pNewTable;
77479     if( !pTab ) goto exit_create_index;
77480     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
77481   }
77482   pDb = &db->aDb[iDb];
77483
77484   assert( pTab!=0 );
77485   assert( pParse->nErr==0 );
77486   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
77487        && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
77488     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
77489     goto exit_create_index;
77490   }
77491 #ifndef SQLITE_OMIT_VIEW
77492   if( pTab->pSelect ){
77493     sqlite3ErrorMsg(pParse, "views may not be indexed");
77494     goto exit_create_index;
77495   }
77496 #endif
77497 #ifndef SQLITE_OMIT_VIRTUALTABLE
77498   if( IsVirtual(pTab) ){
77499     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
77500     goto exit_create_index;
77501   }
77502 #endif
77503
77504   /*
77505   ** Find the name of the index.  Make sure there is not already another
77506   ** index or table with the same name.  
77507   **
77508   ** Exception:  If we are reading the names of permanent indices from the
77509   ** sqlite_master table (because some other process changed the schema) and
77510   ** one of the index names collides with the name of a temporary table or
77511   ** index, then we will continue to process this index.
77512   **
77513   ** If pName==0 it means that we are
77514   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
77515   ** own name.
77516   */
77517   if( pName ){
77518     zName = sqlite3NameFromToken(db, pName);
77519     if( zName==0 ) goto exit_create_index;
77520     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
77521       goto exit_create_index;
77522     }
77523     if( !db->init.busy ){
77524       if( sqlite3FindTable(db, zName, 0)!=0 ){
77525         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
77526         goto exit_create_index;
77527       }
77528     }
77529     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
77530       if( !ifNotExist ){
77531         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
77532       }
77533       goto exit_create_index;
77534     }
77535   }else{
77536     int n;
77537     Index *pLoop;
77538     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
77539     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
77540     if( zName==0 ){
77541       goto exit_create_index;
77542     }
77543   }
77544
77545   /* Check for authorization to create an index.
77546   */
77547 #ifndef SQLITE_OMIT_AUTHORIZATION
77548   {
77549     const char *zDb = pDb->zName;
77550     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
77551       goto exit_create_index;
77552     }
77553     i = SQLITE_CREATE_INDEX;
77554     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
77555     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
77556       goto exit_create_index;
77557     }
77558   }
77559 #endif
77560
77561   /* If pList==0, it means this routine was called to make a primary
77562   ** key out of the last column added to the table under construction.
77563   ** So create a fake list to simulate this.
77564   */
77565   if( pList==0 ){
77566     nullId.z = pTab->aCol[pTab->nCol-1].zName;
77567     nullId.n = sqlite3Strlen30((char*)nullId.z);
77568     pList = sqlite3ExprListAppend(pParse, 0, 0);
77569     if( pList==0 ) goto exit_create_index;
77570     sqlite3ExprListSetName(pParse, pList, &nullId, 0);
77571     pList->a[0].sortOrder = (u8)sortOrder;
77572   }
77573
77574   /* Figure out how many bytes of space are required to store explicitly
77575   ** specified collation sequence names.
77576   */
77577   for(i=0; i<pList->nExpr; i++){
77578     Expr *pExpr = pList->a[i].pExpr;
77579     if( pExpr ){
77580       CollSeq *pColl = pExpr->pColl;
77581       /* Either pColl!=0 or there was an OOM failure.  But if an OOM
77582       ** failure we have quit before reaching this point. */
77583       if( ALWAYS(pColl) ){
77584         nExtra += (1 + sqlite3Strlen30(pColl->zName));
77585       }
77586     }
77587   }
77588
77589   /* 
77590   ** Allocate the index structure. 
77591   */
77592   nName = sqlite3Strlen30(zName);
77593   nCol = pList->nExpr;
77594   pIndex = sqlite3DbMallocZero(db, 
77595       sizeof(Index) +              /* Index structure  */
77596       sizeof(int)*nCol +           /* Index.aiColumn   */
77597       sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
77598       sizeof(char *)*nCol +        /* Index.azColl     */
77599       sizeof(u8)*nCol +            /* Index.aSortOrder */
77600       nName + 1 +                  /* Index.zName      */
77601       nExtra                       /* Collation sequence names */
77602   );
77603   if( db->mallocFailed ){
77604     goto exit_create_index;
77605   }
77606   pIndex->azColl = (char**)(&pIndex[1]);
77607   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
77608   pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
77609   pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
77610   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
77611   zExtra = (char *)(&pIndex->zName[nName+1]);
77612   memcpy(pIndex->zName, zName, nName+1);
77613   pIndex->pTable = pTab;
77614   pIndex->nColumn = pList->nExpr;
77615   pIndex->onError = (u8)onError;
77616   pIndex->autoIndex = (u8)(pName==0);
77617   pIndex->pSchema = db->aDb[iDb].pSchema;
77618
77619   /* Check to see if we should honor DESC requests on index columns
77620   */
77621   if( pDb->pSchema->file_format>=4 ){
77622     sortOrderMask = -1;   /* Honor DESC */
77623   }else{
77624     sortOrderMask = 0;    /* Ignore DESC */
77625   }
77626
77627   /* Scan the names of the columns of the table to be indexed and
77628   ** load the column indices into the Index structure.  Report an error
77629   ** if any column is not found.
77630   **
77631   ** TODO:  Add a test to make sure that the same column is not named
77632   ** more than once within the same index.  Only the first instance of
77633   ** the column will ever be used by the optimizer.  Note that using the
77634   ** same column more than once cannot be an error because that would 
77635   ** break backwards compatibility - it needs to be a warning.
77636   */
77637   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
77638     const char *zColName = pListItem->zName;
77639     Column *pTabCol;
77640     int requestedSortOrder;
77641     char *zColl;                   /* Collation sequence name */
77642
77643     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
77644       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
77645     }
77646     if( j>=pTab->nCol ){
77647       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
77648         pTab->zName, zColName);
77649       pParse->checkSchema = 1;
77650       goto exit_create_index;
77651     }
77652     pIndex->aiColumn[i] = j;
77653     /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
77654     ** the way the "idxlist" non-terminal is constructed by the parser,
77655     ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
77656     ** must exist or else there must have been an OOM error.  But if there
77657     ** was an OOM error, we would never reach this point. */
77658     if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
77659       int nColl;
77660       zColl = pListItem->pExpr->pColl->zName;
77661       nColl = sqlite3Strlen30(zColl) + 1;
77662       assert( nExtra>=nColl );
77663       memcpy(zExtra, zColl, nColl);
77664       zColl = zExtra;
77665       zExtra += nColl;
77666       nExtra -= nColl;
77667     }else{
77668       zColl = pTab->aCol[j].zColl;
77669       if( !zColl ){
77670         zColl = db->pDfltColl->zName;
77671       }
77672     }
77673     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
77674       goto exit_create_index;
77675     }
77676     pIndex->azColl[i] = zColl;
77677     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
77678     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
77679   }
77680   sqlite3DefaultRowEst(pIndex);
77681
77682   if( pTab==pParse->pNewTable ){
77683     /* This routine has been called to create an automatic index as a
77684     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
77685     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
77686     ** i.e. one of:
77687     **
77688     ** CREATE TABLE t(x PRIMARY KEY, y);
77689     ** CREATE TABLE t(x, y, UNIQUE(x, y));
77690     **
77691     ** Either way, check to see if the table already has such an index. If
77692     ** so, don't bother creating this one. This only applies to
77693     ** automatically created indices. Users can do as they wish with
77694     ** explicit indices.
77695     **
77696     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
77697     ** (and thus suppressing the second one) even if they have different
77698     ** sort orders.
77699     **
77700     ** If there are different collating sequences or if the columns of
77701     ** the constraint occur in different orders, then the constraints are
77702     ** considered distinct and both result in separate indices.
77703     */
77704     Index *pIdx;
77705     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
77706       int k;
77707       assert( pIdx->onError!=OE_None );
77708       assert( pIdx->autoIndex );
77709       assert( pIndex->onError!=OE_None );
77710
77711       if( pIdx->nColumn!=pIndex->nColumn ) continue;
77712       for(k=0; k<pIdx->nColumn; k++){
77713         const char *z1;
77714         const char *z2;
77715         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
77716         z1 = pIdx->azColl[k];
77717         z2 = pIndex->azColl[k];
77718         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
77719       }
77720       if( k==pIdx->nColumn ){
77721         if( pIdx->onError!=pIndex->onError ){
77722           /* This constraint creates the same index as a previous
77723           ** constraint specified somewhere in the CREATE TABLE statement.
77724           ** However the ON CONFLICT clauses are different. If both this 
77725           ** constraint and the previous equivalent constraint have explicit
77726           ** ON CONFLICT clauses this is an error. Otherwise, use the
77727           ** explicitly specified behaviour for the index.
77728           */
77729           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
77730             sqlite3ErrorMsg(pParse, 
77731                 "conflicting ON CONFLICT clauses specified", 0);
77732           }
77733           if( pIdx->onError==OE_Default ){
77734             pIdx->onError = pIndex->onError;
77735           }
77736         }
77737         goto exit_create_index;
77738       }
77739     }
77740   }
77741
77742   /* Link the new Index structure to its table and to the other
77743   ** in-memory database structures. 
77744   */
77745   if( db->init.busy ){
77746     Index *p;
77747     p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
77748                           pIndex->zName, sqlite3Strlen30(pIndex->zName),
77749                           pIndex);
77750     if( p ){
77751       assert( p==pIndex );  /* Malloc must have failed */
77752       db->mallocFailed = 1;
77753       goto exit_create_index;
77754     }
77755     db->flags |= SQLITE_InternChanges;
77756     if( pTblName!=0 ){
77757       pIndex->tnum = db->init.newTnum;
77758     }
77759   }
77760
77761   /* If the db->init.busy is 0 then create the index on disk.  This
77762   ** involves writing the index into the master table and filling in the
77763   ** index with the current table contents.
77764   **
77765   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
77766   ** command.  db->init.busy is 1 when a database is opened and 
77767   ** CREATE INDEX statements are read out of the master table.  In
77768   ** the latter case the index already exists on disk, which is why
77769   ** we don't want to recreate it.
77770   **
77771   ** If pTblName==0 it means this index is generated as a primary key
77772   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
77773   ** has just been created, it contains no data and the index initialization
77774   ** step can be skipped.
77775   */
77776   else{ /* if( db->init.busy==0 ) */
77777     Vdbe *v;
77778     char *zStmt;
77779     int iMem = ++pParse->nMem;
77780
77781     v = sqlite3GetVdbe(pParse);
77782     if( v==0 ) goto exit_create_index;
77783
77784
77785     /* Create the rootpage for the index
77786     */
77787     sqlite3BeginWriteOperation(pParse, 1, iDb);
77788     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
77789
77790     /* Gather the complete text of the CREATE INDEX statement into
77791     ** the zStmt variable
77792     */
77793     if( pStart ){
77794       assert( pEnd!=0 );
77795       /* A named index with an explicit CREATE INDEX statement */
77796       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
77797         onError==OE_None ? "" : " UNIQUE",
77798         pEnd->z - pName->z + 1,
77799         pName->z);
77800     }else{
77801       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
77802       /* zStmt = sqlite3MPrintf(""); */
77803       zStmt = 0;
77804     }
77805
77806     /* Add an entry in sqlite_master for this index
77807     */
77808     sqlite3NestedParse(pParse, 
77809         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
77810         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
77811         pIndex->zName,
77812         pTab->zName,
77813         iMem,
77814         zStmt
77815     );
77816     sqlite3DbFree(db, zStmt);
77817
77818     /* Fill the index with data and reparse the schema. Code an OP_Expire
77819     ** to invalidate all pre-compiled statements.
77820     */
77821     if( pTblName ){
77822       sqlite3RefillIndex(pParse, pIndex, iMem);
77823       sqlite3ChangeCookie(pParse, iDb);
77824       sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
77825          sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName), 
77826          P4_DYNAMIC);
77827       sqlite3VdbeAddOp1(v, OP_Expire, 0);
77828     }
77829   }
77830
77831   /* When adding an index to the list of indices for a table, make
77832   ** sure all indices labeled OE_Replace come after all those labeled
77833   ** OE_Ignore.  This is necessary for the correct constraint check
77834   ** processing (in sqlite3GenerateConstraintChecks()) as part of
77835   ** UPDATE and INSERT statements.  
77836   */
77837   if( db->init.busy || pTblName==0 ){
77838     if( onError!=OE_Replace || pTab->pIndex==0
77839          || pTab->pIndex->onError==OE_Replace){
77840       pIndex->pNext = pTab->pIndex;
77841       pTab->pIndex = pIndex;
77842     }else{
77843       Index *pOther = pTab->pIndex;
77844       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
77845         pOther = pOther->pNext;
77846       }
77847       pIndex->pNext = pOther->pNext;
77848       pOther->pNext = pIndex;
77849     }
77850     pRet = pIndex;
77851     pIndex = 0;
77852   }
77853
77854   /* Clean up before exiting */
77855 exit_create_index:
77856   if( pIndex ){
77857     sqlite3DbFree(db, pIndex->zColAff);
77858     sqlite3DbFree(db, pIndex);
77859   }
77860   sqlite3ExprListDelete(db, pList);
77861   sqlite3SrcListDelete(db, pTblName);
77862   sqlite3DbFree(db, zName);
77863   return pRet;
77864 }
77865
77866 /*
77867 ** Fill the Index.aiRowEst[] array with default information - information
77868 ** to be used when we have not run the ANALYZE command.
77869 **
77870 ** aiRowEst[0] is suppose to contain the number of elements in the index.
77871 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
77872 ** number of rows in the table that match any particular value of the
77873 ** first column of the index.  aiRowEst[2] is an estimate of the number
77874 ** of rows that match any particular combiniation of the first 2 columns
77875 ** of the index.  And so forth.  It must always be the case that
77876 *
77877 **           aiRowEst[N]<=aiRowEst[N-1]
77878 **           aiRowEst[N]>=1
77879 **
77880 ** Apart from that, we have little to go on besides intuition as to
77881 ** how aiRowEst[] should be initialized.  The numbers generated here
77882 ** are based on typical values found in actual indices.
77883 */
77884 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
77885   unsigned *a = pIdx->aiRowEst;
77886   int i;
77887   unsigned n;
77888   assert( a!=0 );
77889   a[0] = pIdx->pTable->nRowEst;
77890   if( a[0]<10 ) a[0] = 10;
77891   n = 10;
77892   for(i=1; i<=pIdx->nColumn; i++){
77893     a[i] = n;
77894     if( n>5 ) n--;
77895   }
77896   if( pIdx->onError!=OE_None ){
77897     a[pIdx->nColumn] = 1;
77898   }
77899 }
77900
77901 /*
77902 ** This routine will drop an existing named index.  This routine
77903 ** implements the DROP INDEX statement.
77904 */
77905 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
77906   Index *pIndex;
77907   Vdbe *v;
77908   sqlite3 *db = pParse->db;
77909   int iDb;
77910
77911   assert( pParse->nErr==0 );   /* Never called with prior errors */
77912   if( db->mallocFailed ){
77913     goto exit_drop_index;
77914   }
77915   assert( pName->nSrc==1 );
77916   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
77917     goto exit_drop_index;
77918   }
77919   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
77920   if( pIndex==0 ){
77921     if( !ifExists ){
77922       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
77923     }
77924     pParse->checkSchema = 1;
77925     goto exit_drop_index;
77926   }
77927   if( pIndex->autoIndex ){
77928     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
77929       "or PRIMARY KEY constraint cannot be dropped", 0);
77930     goto exit_drop_index;
77931   }
77932   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
77933 #ifndef SQLITE_OMIT_AUTHORIZATION
77934   {
77935     int code = SQLITE_DROP_INDEX;
77936     Table *pTab = pIndex->pTable;
77937     const char *zDb = db->aDb[iDb].zName;
77938     const char *zTab = SCHEMA_TABLE(iDb);
77939     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
77940       goto exit_drop_index;
77941     }
77942     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
77943     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
77944       goto exit_drop_index;
77945     }
77946   }
77947 #endif
77948
77949   /* Generate code to remove the index and from the master table */
77950   v = sqlite3GetVdbe(pParse);
77951   if( v ){
77952     sqlite3BeginWriteOperation(pParse, 1, iDb);
77953     sqlite3NestedParse(pParse,
77954        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
77955        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
77956        pIndex->zName
77957     );
77958     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
77959       sqlite3NestedParse(pParse,
77960         "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
77961         db->aDb[iDb].zName, pIndex->zName
77962       );
77963     }
77964     sqlite3ChangeCookie(pParse, iDb);
77965     destroyRootPage(pParse, pIndex->tnum, iDb);
77966     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
77967   }
77968
77969 exit_drop_index:
77970   sqlite3SrcListDelete(db, pName);
77971 }
77972
77973 /*
77974 ** pArray is a pointer to an array of objects.  Each object in the
77975 ** array is szEntry bytes in size.  This routine allocates a new
77976 ** object on the end of the array.
77977 **
77978 ** *pnEntry is the number of entries already in use.  *pnAlloc is
77979 ** the previously allocated size of the array.  initSize is the
77980 ** suggested initial array size allocation.
77981 **
77982 ** The index of the new entry is returned in *pIdx.
77983 **
77984 ** This routine returns a pointer to the array of objects.  This
77985 ** might be the same as the pArray parameter or it might be a different
77986 ** pointer if the array was resized.
77987 */
77988 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
77989   sqlite3 *db,      /* Connection to notify of malloc failures */
77990   void *pArray,     /* Array of objects.  Might be reallocated */
77991   int szEntry,      /* Size of each object in the array */
77992   int initSize,     /* Suggested initial allocation, in elements */
77993   int *pnEntry,     /* Number of objects currently in use */
77994   int *pnAlloc,     /* Current size of the allocation, in elements */
77995   int *pIdx         /* Write the index of a new slot here */
77996 ){
77997   char *z;
77998   if( *pnEntry >= *pnAlloc ){
77999     void *pNew;
78000     int newSize;
78001     newSize = (*pnAlloc)*2 + initSize;
78002     pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
78003     if( pNew==0 ){
78004       *pIdx = -1;
78005       return pArray;
78006     }
78007     *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
78008     pArray = pNew;
78009   }
78010   z = (char*)pArray;
78011   memset(&z[*pnEntry * szEntry], 0, szEntry);
78012   *pIdx = *pnEntry;
78013   ++*pnEntry;
78014   return pArray;
78015 }
78016
78017 /*
78018 ** Append a new element to the given IdList.  Create a new IdList if
78019 ** need be.
78020 **
78021 ** A new IdList is returned, or NULL if malloc() fails.
78022 */
78023 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
78024   int i;
78025   if( pList==0 ){
78026     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
78027     if( pList==0 ) return 0;
78028     pList->nAlloc = 0;
78029   }
78030   pList->a = sqlite3ArrayAllocate(
78031       db,
78032       pList->a,
78033       sizeof(pList->a[0]),
78034       5,
78035       &pList->nId,
78036       &pList->nAlloc,
78037       &i
78038   );
78039   if( i<0 ){
78040     sqlite3IdListDelete(db, pList);
78041     return 0;
78042   }
78043   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
78044   return pList;
78045 }
78046
78047 /*
78048 ** Delete an IdList.
78049 */
78050 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
78051   int i;
78052   if( pList==0 ) return;
78053   for(i=0; i<pList->nId; i++){
78054     sqlite3DbFree(db, pList->a[i].zName);
78055   }
78056   sqlite3DbFree(db, pList->a);
78057   sqlite3DbFree(db, pList);
78058 }
78059
78060 /*
78061 ** Return the index in pList of the identifier named zId.  Return -1
78062 ** if not found.
78063 */
78064 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
78065   int i;
78066   if( pList==0 ) return -1;
78067   for(i=0; i<pList->nId; i++){
78068     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
78069   }
78070   return -1;
78071 }
78072
78073 /*
78074 ** Expand the space allocated for the given SrcList object by
78075 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
78076 ** New slots are zeroed.
78077 **
78078 ** For example, suppose a SrcList initially contains two entries: A,B.
78079 ** To append 3 new entries onto the end, do this:
78080 **
78081 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
78082 **
78083 ** After the call above it would contain:  A, B, nil, nil, nil.
78084 ** If the iStart argument had been 1 instead of 2, then the result
78085 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
78086 ** the iStart value would be 0.  The result then would
78087 ** be: nil, nil, nil, A, B.
78088 **
78089 ** If a memory allocation fails the SrcList is unchanged.  The
78090 ** db->mallocFailed flag will be set to true.
78091 */
78092 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
78093   sqlite3 *db,       /* Database connection to notify of OOM errors */
78094   SrcList *pSrc,     /* The SrcList to be enlarged */
78095   int nExtra,        /* Number of new slots to add to pSrc->a[] */
78096   int iStart         /* Index in pSrc->a[] of first new slot */
78097 ){
78098   int i;
78099
78100   /* Sanity checking on calling parameters */
78101   assert( iStart>=0 );
78102   assert( nExtra>=1 );
78103   assert( pSrc!=0 );
78104   assert( iStart<=pSrc->nSrc );
78105
78106   /* Allocate additional space if needed */
78107   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
78108     SrcList *pNew;
78109     int nAlloc = pSrc->nSrc+nExtra;
78110     int nGot;
78111     pNew = sqlite3DbRealloc(db, pSrc,
78112                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
78113     if( pNew==0 ){
78114       assert( db->mallocFailed );
78115       return pSrc;
78116     }
78117     pSrc = pNew;
78118     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
78119     pSrc->nAlloc = (u16)nGot;
78120   }
78121
78122   /* Move existing slots that come after the newly inserted slots
78123   ** out of the way */
78124   for(i=pSrc->nSrc-1; i>=iStart; i--){
78125     pSrc->a[i+nExtra] = pSrc->a[i];
78126   }
78127   pSrc->nSrc += (i16)nExtra;
78128
78129   /* Zero the newly allocated slots */
78130   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
78131   for(i=iStart; i<iStart+nExtra; i++){
78132     pSrc->a[i].iCursor = -1;
78133   }
78134
78135   /* Return a pointer to the enlarged SrcList */
78136   return pSrc;
78137 }
78138
78139
78140 /*
78141 ** Append a new table name to the given SrcList.  Create a new SrcList if
78142 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
78143 **
78144 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
78145 ** SrcList might be the same as the SrcList that was input or it might be
78146 ** a new one.  If an OOM error does occurs, then the prior value of pList
78147 ** that is input to this routine is automatically freed.
78148 **
78149 ** If pDatabase is not null, it means that the table has an optional
78150 ** database name prefix.  Like this:  "database.table".  The pDatabase
78151 ** points to the table name and the pTable points to the database name.
78152 ** The SrcList.a[].zName field is filled with the table name which might
78153 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
78154 ** SrcList.a[].zDatabase is filled with the database name from pTable,
78155 ** or with NULL if no database is specified.
78156 **
78157 ** In other words, if call like this:
78158 **
78159 **         sqlite3SrcListAppend(D,A,B,0);
78160 **
78161 ** Then B is a table name and the database name is unspecified.  If called
78162 ** like this:
78163 **
78164 **         sqlite3SrcListAppend(D,A,B,C);
78165 **
78166 ** Then C is the table name and B is the database name.  If C is defined
78167 ** then so is B.  In other words, we never have a case where:
78168 **
78169 **         sqlite3SrcListAppend(D,A,0,C);
78170 **
78171 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
78172 ** before being added to the SrcList.
78173 */
78174 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
78175   sqlite3 *db,        /* Connection to notify of malloc failures */
78176   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
78177   Token *pTable,      /* Table to append */
78178   Token *pDatabase    /* Database of the table */
78179 ){
78180   struct SrcList_item *pItem;
78181   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
78182   if( pList==0 ){
78183     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
78184     if( pList==0 ) return 0;
78185     pList->nAlloc = 1;
78186   }
78187   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
78188   if( db->mallocFailed ){
78189     sqlite3SrcListDelete(db, pList);
78190     return 0;
78191   }
78192   pItem = &pList->a[pList->nSrc-1];
78193   if( pDatabase && pDatabase->z==0 ){
78194     pDatabase = 0;
78195   }
78196   if( pDatabase ){
78197     Token *pTemp = pDatabase;
78198     pDatabase = pTable;
78199     pTable = pTemp;
78200   }
78201   pItem->zName = sqlite3NameFromToken(db, pTable);
78202   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
78203   return pList;
78204 }
78205
78206 /*
78207 ** Assign VdbeCursor index numbers to all tables in a SrcList
78208 */
78209 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
78210   int i;
78211   struct SrcList_item *pItem;
78212   assert(pList || pParse->db->mallocFailed );
78213   if( pList ){
78214     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
78215       if( pItem->iCursor>=0 ) break;
78216       pItem->iCursor = pParse->nTab++;
78217       if( pItem->pSelect ){
78218         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
78219       }
78220     }
78221   }
78222 }
78223
78224 /*
78225 ** Delete an entire SrcList including all its substructure.
78226 */
78227 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
78228   int i;
78229   struct SrcList_item *pItem;
78230   if( pList==0 ) return;
78231   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
78232     sqlite3DbFree(db, pItem->zDatabase);
78233     sqlite3DbFree(db, pItem->zName);
78234     sqlite3DbFree(db, pItem->zAlias);
78235     sqlite3DbFree(db, pItem->zIndex);
78236     sqlite3DeleteTable(db, pItem->pTab);
78237     sqlite3SelectDelete(db, pItem->pSelect);
78238     sqlite3ExprDelete(db, pItem->pOn);
78239     sqlite3IdListDelete(db, pItem->pUsing);
78240   }
78241   sqlite3DbFree(db, pList);
78242 }
78243
78244 /*
78245 ** This routine is called by the parser to add a new term to the
78246 ** end of a growing FROM clause.  The "p" parameter is the part of
78247 ** the FROM clause that has already been constructed.  "p" is NULL
78248 ** if this is the first term of the FROM clause.  pTable and pDatabase
78249 ** are the name of the table and database named in the FROM clause term.
78250 ** pDatabase is NULL if the database name qualifier is missing - the
78251 ** usual case.  If the term has a alias, then pAlias points to the
78252 ** alias token.  If the term is a subquery, then pSubquery is the
78253 ** SELECT statement that the subquery encodes.  The pTable and
78254 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
78255 ** parameters are the content of the ON and USING clauses.
78256 **
78257 ** Return a new SrcList which encodes is the FROM with the new
78258 ** term added.
78259 */
78260 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
78261   Parse *pParse,          /* Parsing context */
78262   SrcList *p,             /* The left part of the FROM clause already seen */
78263   Token *pTable,          /* Name of the table to add to the FROM clause */
78264   Token *pDatabase,       /* Name of the database containing pTable */
78265   Token *pAlias,          /* The right-hand side of the AS subexpression */
78266   Select *pSubquery,      /* A subquery used in place of a table name */
78267   Expr *pOn,              /* The ON clause of a join */
78268   IdList *pUsing          /* The USING clause of a join */
78269 ){
78270   struct SrcList_item *pItem;
78271   sqlite3 *db = pParse->db;
78272   if( !p && (pOn || pUsing) ){
78273     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 
78274       (pOn ? "ON" : "USING")
78275     );
78276     goto append_from_error;
78277   }
78278   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
78279   if( p==0 || NEVER(p->nSrc==0) ){
78280     goto append_from_error;
78281   }
78282   pItem = &p->a[p->nSrc-1];
78283   assert( pAlias!=0 );
78284   if( pAlias->n ){
78285     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
78286   }
78287   pItem->pSelect = pSubquery;
78288   pItem->pOn = pOn;
78289   pItem->pUsing = pUsing;
78290   return p;
78291
78292  append_from_error:
78293   assert( p==0 );
78294   sqlite3ExprDelete(db, pOn);
78295   sqlite3IdListDelete(db, pUsing);
78296   sqlite3SelectDelete(db, pSubquery);
78297   return 0;
78298 }
78299
78300 /*
78301 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
78302 ** element of the source-list passed as the second argument.
78303 */
78304 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
78305   assert( pIndexedBy!=0 );
78306   if( p && ALWAYS(p->nSrc>0) ){
78307     struct SrcList_item *pItem = &p->a[p->nSrc-1];
78308     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
78309     if( pIndexedBy->n==1 && !pIndexedBy->z ){
78310       /* A "NOT INDEXED" clause was supplied. See parse.y 
78311       ** construct "indexed_opt" for details. */
78312       pItem->notIndexed = 1;
78313     }else{
78314       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
78315     }
78316   }
78317 }
78318
78319 /*
78320 ** When building up a FROM clause in the parser, the join operator
78321 ** is initially attached to the left operand.  But the code generator
78322 ** expects the join operator to be on the right operand.  This routine
78323 ** Shifts all join operators from left to right for an entire FROM
78324 ** clause.
78325 **
78326 ** Example: Suppose the join is like this:
78327 **
78328 **           A natural cross join B
78329 **
78330 ** The operator is "natural cross join".  The A and B operands are stored
78331 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
78332 ** operator with A.  This routine shifts that operator over to B.
78333 */
78334 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
78335   if( p && p->a ){
78336     int i;
78337     for(i=p->nSrc-1; i>0; i--){
78338       p->a[i].jointype = p->a[i-1].jointype;
78339     }
78340     p->a[0].jointype = 0;
78341   }
78342 }
78343
78344 /*
78345 ** Begin a transaction
78346 */
78347 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
78348   sqlite3 *db;
78349   Vdbe *v;
78350   int i;
78351
78352   assert( pParse!=0 );
78353   db = pParse->db;
78354   assert( db!=0 );
78355 /*  if( db->aDb[0].pBt==0 ) return; */
78356   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
78357     return;
78358   }
78359   v = sqlite3GetVdbe(pParse);
78360   if( !v ) return;
78361   if( type!=TK_DEFERRED ){
78362     for(i=0; i<db->nDb; i++){
78363       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
78364       sqlite3VdbeUsesBtree(v, i);
78365     }
78366   }
78367   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
78368 }
78369
78370 /*
78371 ** Commit a transaction
78372 */
78373 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
78374   sqlite3 *db;
78375   Vdbe *v;
78376
78377   assert( pParse!=0 );
78378   db = pParse->db;
78379   assert( db!=0 );
78380 /*  if( db->aDb[0].pBt==0 ) return; */
78381   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
78382     return;
78383   }
78384   v = sqlite3GetVdbe(pParse);
78385   if( v ){
78386     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
78387   }
78388 }
78389
78390 /*
78391 ** Rollback a transaction
78392 */
78393 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
78394   sqlite3 *db;
78395   Vdbe *v;
78396
78397   assert( pParse!=0 );
78398   db = pParse->db;
78399   assert( db!=0 );
78400 /*  if( db->aDb[0].pBt==0 ) return; */
78401   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
78402     return;
78403   }
78404   v = sqlite3GetVdbe(pParse);
78405   if( v ){
78406     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
78407   }
78408 }
78409
78410 /*
78411 ** This function is called by the parser when it parses a command to create,
78412 ** release or rollback an SQL savepoint. 
78413 */
78414 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
78415   char *zName = sqlite3NameFromToken(pParse->db, pName);
78416   if( zName ){
78417     Vdbe *v = sqlite3GetVdbe(pParse);
78418 #ifndef SQLITE_OMIT_AUTHORIZATION
78419     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
78420     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
78421 #endif
78422     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
78423       sqlite3DbFree(pParse->db, zName);
78424       return;
78425     }
78426     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
78427   }
78428 }
78429
78430 /*
78431 ** Make sure the TEMP database is open and available for use.  Return
78432 ** the number of errors.  Leave any error messages in the pParse structure.
78433 */
78434 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
78435   sqlite3 *db = pParse->db;
78436   if( db->aDb[1].pBt==0 && !pParse->explain ){
78437     int rc;
78438     Btree *pBt;
78439     static const int flags = 
78440           SQLITE_OPEN_READWRITE |
78441           SQLITE_OPEN_CREATE |
78442           SQLITE_OPEN_EXCLUSIVE |
78443           SQLITE_OPEN_DELETEONCLOSE |
78444           SQLITE_OPEN_TEMP_DB;
78445
78446     rc = sqlite3BtreeOpen(0, db, &pBt, 0, flags);
78447     if( rc!=SQLITE_OK ){
78448       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
78449         "file for storing temporary tables");
78450       pParse->rc = rc;
78451       return 1;
78452     }
78453     db->aDb[1].pBt = pBt;
78454     assert( db->aDb[1].pSchema );
78455     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
78456       db->mallocFailed = 1;
78457       return 1;
78458     }
78459   }
78460   return 0;
78461 }
78462
78463 /*
78464 ** Generate VDBE code that will verify the schema cookie and start
78465 ** a read-transaction for all named database files.
78466 **
78467 ** It is important that all schema cookies be verified and all
78468 ** read transactions be started before anything else happens in
78469 ** the VDBE program.  But this routine can be called after much other
78470 ** code has been generated.  So here is what we do:
78471 **
78472 ** The first time this routine is called, we code an OP_Goto that
78473 ** will jump to a subroutine at the end of the program.  Then we
78474 ** record every database that needs its schema verified in the
78475 ** pParse->cookieMask field.  Later, after all other code has been
78476 ** generated, the subroutine that does the cookie verifications and
78477 ** starts the transactions will be coded and the OP_Goto P2 value
78478 ** will be made to point to that subroutine.  The generation of the
78479 ** cookie verification subroutine code happens in sqlite3FinishCoding().
78480 **
78481 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
78482 ** schema on any databases.  This can be used to position the OP_Goto
78483 ** early in the code, before we know if any database tables will be used.
78484 */
78485 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
78486   Parse *pToplevel = sqlite3ParseToplevel(pParse);
78487
78488   if( pToplevel->cookieGoto==0 ){
78489     Vdbe *v = sqlite3GetVdbe(pToplevel);
78490     if( v==0 ) return;  /* This only happens if there was a prior error */
78491     pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
78492   }
78493   if( iDb>=0 ){
78494     sqlite3 *db = pToplevel->db;
78495     int mask;
78496
78497     assert( iDb<db->nDb );
78498     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
78499     assert( iDb<SQLITE_MAX_ATTACHED+2 );
78500     mask = 1<<iDb;
78501     if( (pToplevel->cookieMask & mask)==0 ){
78502       pToplevel->cookieMask |= mask;
78503       pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
78504       if( !OMIT_TEMPDB && iDb==1 ){
78505         sqlite3OpenTempDatabase(pToplevel);
78506       }
78507     }
78508   }
78509 }
78510
78511 /*
78512 ** Generate VDBE code that prepares for doing an operation that
78513 ** might change the database.
78514 **
78515 ** This routine starts a new transaction if we are not already within
78516 ** a transaction.  If we are already within a transaction, then a checkpoint
78517 ** is set if the setStatement parameter is true.  A checkpoint should
78518 ** be set for operations that might fail (due to a constraint) part of
78519 ** the way through and which will need to undo some writes without having to
78520 ** rollback the whole transaction.  For operations where all constraints
78521 ** can be checked before any changes are made to the database, it is never
78522 ** necessary to undo a write and the checkpoint should not be set.
78523 */
78524 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
78525   Parse *pToplevel = sqlite3ParseToplevel(pParse);
78526   sqlite3CodeVerifySchema(pParse, iDb);
78527   pToplevel->writeMask |= 1<<iDb;
78528   pToplevel->isMultiWrite |= setStatement;
78529 }
78530
78531 /*
78532 ** Indicate that the statement currently under construction might write
78533 ** more than one entry (example: deleting one row then inserting another,
78534 ** inserting multiple rows in a table, or inserting a row and index entries.)
78535 ** If an abort occurs after some of these writes have completed, then it will
78536 ** be necessary to undo the completed writes.
78537 */
78538 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
78539   Parse *pToplevel = sqlite3ParseToplevel(pParse);
78540   pToplevel->isMultiWrite = 1;
78541 }
78542
78543 /* 
78544 ** The code generator calls this routine if is discovers that it is
78545 ** possible to abort a statement prior to completion.  In order to 
78546 ** perform this abort without corrupting the database, we need to make
78547 ** sure that the statement is protected by a statement transaction.
78548 **
78549 ** Technically, we only need to set the mayAbort flag if the
78550 ** isMultiWrite flag was previously set.  There is a time dependency
78551 ** such that the abort must occur after the multiwrite.  This makes
78552 ** some statements involving the REPLACE conflict resolution algorithm
78553 ** go a little faster.  But taking advantage of this time dependency
78554 ** makes it more difficult to prove that the code is correct (in 
78555 ** particular, it prevents us from writing an effective
78556 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
78557 ** to take the safe route and skip the optimization.
78558 */
78559 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
78560   Parse *pToplevel = sqlite3ParseToplevel(pParse);
78561   pToplevel->mayAbort = 1;
78562 }
78563
78564 /*
78565 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
78566 ** error. The onError parameter determines which (if any) of the statement
78567 ** and/or current transaction is rolled back.
78568 */
78569 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
78570   Vdbe *v = sqlite3GetVdbe(pParse);
78571   if( onError==OE_Abort ){
78572     sqlite3MayAbort(pParse);
78573   }
78574   sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
78575 }
78576
78577 /*
78578 ** Check to see if pIndex uses the collating sequence pColl.  Return
78579 ** true if it does and false if it does not.
78580 */
78581 #ifndef SQLITE_OMIT_REINDEX
78582 static int collationMatch(const char *zColl, Index *pIndex){
78583   int i;
78584   assert( zColl!=0 );
78585   for(i=0; i<pIndex->nColumn; i++){
78586     const char *z = pIndex->azColl[i];
78587     assert( z!=0 );
78588     if( 0==sqlite3StrICmp(z, zColl) ){
78589       return 1;
78590     }
78591   }
78592   return 0;
78593 }
78594 #endif
78595
78596 /*
78597 ** Recompute all indices of pTab that use the collating sequence pColl.
78598 ** If pColl==0 then recompute all indices of pTab.
78599 */
78600 #ifndef SQLITE_OMIT_REINDEX
78601 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
78602   Index *pIndex;              /* An index associated with pTab */
78603
78604   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
78605     if( zColl==0 || collationMatch(zColl, pIndex) ){
78606       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
78607       sqlite3BeginWriteOperation(pParse, 0, iDb);
78608       sqlite3RefillIndex(pParse, pIndex, -1);
78609     }
78610   }
78611 }
78612 #endif
78613
78614 /*
78615 ** Recompute all indices of all tables in all databases where the
78616 ** indices use the collating sequence pColl.  If pColl==0 then recompute
78617 ** all indices everywhere.
78618 */
78619 #ifndef SQLITE_OMIT_REINDEX
78620 static void reindexDatabases(Parse *pParse, char const *zColl){
78621   Db *pDb;                    /* A single database */
78622   int iDb;                    /* The database index number */
78623   sqlite3 *db = pParse->db;   /* The database connection */
78624   HashElem *k;                /* For looping over tables in pDb */
78625   Table *pTab;                /* A table in the database */
78626
78627   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
78628     assert( pDb!=0 );
78629     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
78630       pTab = (Table*)sqliteHashData(k);
78631       reindexTable(pParse, pTab, zColl);
78632     }
78633   }
78634 }
78635 #endif
78636
78637 /*
78638 ** Generate code for the REINDEX command.
78639 **
78640 **        REINDEX                            -- 1
78641 **        REINDEX  <collation>               -- 2
78642 **        REINDEX  ?<database>.?<tablename>  -- 3
78643 **        REINDEX  ?<database>.?<indexname>  -- 4
78644 **
78645 ** Form 1 causes all indices in all attached databases to be rebuilt.
78646 ** Form 2 rebuilds all indices in all databases that use the named
78647 ** collating function.  Forms 3 and 4 rebuild the named index or all
78648 ** indices associated with the named table.
78649 */
78650 #ifndef SQLITE_OMIT_REINDEX
78651 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
78652   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
78653   char *z;                    /* Name of a table or index */
78654   const char *zDb;            /* Name of the database */
78655   Table *pTab;                /* A table in the database */
78656   Index *pIndex;              /* An index associated with pTab */
78657   int iDb;                    /* The database index number */
78658   sqlite3 *db = pParse->db;   /* The database connection */
78659   Token *pObjName;            /* Name of the table or index to be reindexed */
78660
78661   /* Read the database schema. If an error occurs, leave an error message
78662   ** and code in pParse and return NULL. */
78663   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
78664     return;
78665   }
78666
78667   if( pName1==0 ){
78668     reindexDatabases(pParse, 0);
78669     return;
78670   }else if( NEVER(pName2==0) || pName2->z==0 ){
78671     char *zColl;
78672     assert( pName1->z );
78673     zColl = sqlite3NameFromToken(pParse->db, pName1);
78674     if( !zColl ) return;
78675     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
78676     if( pColl ){
78677       reindexDatabases(pParse, zColl);
78678       sqlite3DbFree(db, zColl);
78679       return;
78680     }
78681     sqlite3DbFree(db, zColl);
78682   }
78683   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
78684   if( iDb<0 ) return;
78685   z = sqlite3NameFromToken(db, pObjName);
78686   if( z==0 ) return;
78687   zDb = db->aDb[iDb].zName;
78688   pTab = sqlite3FindTable(db, z, zDb);
78689   if( pTab ){
78690     reindexTable(pParse, pTab, 0);
78691     sqlite3DbFree(db, z);
78692     return;
78693   }
78694   pIndex = sqlite3FindIndex(db, z, zDb);
78695   sqlite3DbFree(db, z);
78696   if( pIndex ){
78697     sqlite3BeginWriteOperation(pParse, 0, iDb);
78698     sqlite3RefillIndex(pParse, pIndex, -1);
78699     return;
78700   }
78701   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
78702 }
78703 #endif
78704
78705 /*
78706 ** Return a dynamicly allocated KeyInfo structure that can be used
78707 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
78708 **
78709 ** If successful, a pointer to the new structure is returned. In this case
78710 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned 
78711 ** pointer. If an error occurs (out of memory or missing collation 
78712 ** sequence), NULL is returned and the state of pParse updated to reflect
78713 ** the error.
78714 */
78715 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
78716   int i;
78717   int nCol = pIdx->nColumn;
78718   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
78719   sqlite3 *db = pParse->db;
78720   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
78721
78722   if( pKey ){
78723     pKey->db = pParse->db;
78724     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
78725     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
78726     for(i=0; i<nCol; i++){
78727       char *zColl = pIdx->azColl[i];
78728       assert( zColl );
78729       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
78730       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
78731     }
78732     pKey->nField = (u16)nCol;
78733   }
78734
78735   if( pParse->nErr ){
78736     sqlite3DbFree(db, pKey);
78737     pKey = 0;
78738   }
78739   return pKey;
78740 }
78741
78742 /************** End of build.c ***********************************************/
78743 /************** Begin file callback.c ****************************************/
78744 /*
78745 ** 2005 May 23 
78746 **
78747 ** The author disclaims copyright to this source code.  In place of
78748 ** a legal notice, here is a blessing:
78749 **
78750 **    May you do good and not evil.
78751 **    May you find forgiveness for yourself and forgive others.
78752 **    May you share freely, never taking more than you give.
78753 **
78754 *************************************************************************
78755 **
78756 ** This file contains functions used to access the internal hash tables
78757 ** of user defined functions and collation sequences.
78758 */
78759
78760
78761 /*
78762 ** Invoke the 'collation needed' callback to request a collation sequence
78763 ** in the encoding enc of name zName, length nName.
78764 */
78765 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
78766   assert( !db->xCollNeeded || !db->xCollNeeded16 );
78767   if( db->xCollNeeded ){
78768     char *zExternal = sqlite3DbStrDup(db, zName);
78769     if( !zExternal ) return;
78770     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
78771     sqlite3DbFree(db, zExternal);
78772   }
78773 #ifndef SQLITE_OMIT_UTF16
78774   if( db->xCollNeeded16 ){
78775     char const *zExternal;
78776     sqlite3_value *pTmp = sqlite3ValueNew(db);
78777     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
78778     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
78779     if( zExternal ){
78780       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
78781     }
78782     sqlite3ValueFree(pTmp);
78783   }
78784 #endif
78785 }
78786
78787 /*
78788 ** This routine is called if the collation factory fails to deliver a
78789 ** collation function in the best encoding but there may be other versions
78790 ** of this collation function (for other text encodings) available. Use one
78791 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
78792 ** possible.
78793 */
78794 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
78795   CollSeq *pColl2;
78796   char *z = pColl->zName;
78797   int i;
78798   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
78799   for(i=0; i<3; i++){
78800     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
78801     if( pColl2->xCmp!=0 ){
78802       memcpy(pColl, pColl2, sizeof(CollSeq));
78803       pColl->xDel = 0;         /* Do not copy the destructor */
78804       return SQLITE_OK;
78805     }
78806   }
78807   return SQLITE_ERROR;
78808 }
78809
78810 /*
78811 ** This function is responsible for invoking the collation factory callback
78812 ** or substituting a collation sequence of a different encoding when the
78813 ** requested collation sequence is not available in the desired encoding.
78814 ** 
78815 ** If it is not NULL, then pColl must point to the database native encoding 
78816 ** collation sequence with name zName, length nName.
78817 **
78818 ** The return value is either the collation sequence to be used in database
78819 ** db for collation type name zName, length nName, or NULL, if no collation
78820 ** sequence can be found.
78821 **
78822 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
78823 */
78824 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
78825   sqlite3* db,          /* The database connection */
78826   u8 enc,               /* The desired encoding for the collating sequence */
78827   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
78828   const char *zName     /* Collating sequence name */
78829 ){
78830   CollSeq *p;
78831
78832   p = pColl;
78833   if( !p ){
78834     p = sqlite3FindCollSeq(db, enc, zName, 0);
78835   }
78836   if( !p || !p->xCmp ){
78837     /* No collation sequence of this type for this encoding is registered.
78838     ** Call the collation factory to see if it can supply us with one.
78839     */
78840     callCollNeeded(db, enc, zName);
78841     p = sqlite3FindCollSeq(db, enc, zName, 0);
78842   }
78843   if( p && !p->xCmp && synthCollSeq(db, p) ){
78844     p = 0;
78845   }
78846   assert( !p || p->xCmp );
78847   return p;
78848 }
78849
78850 /*
78851 ** This routine is called on a collation sequence before it is used to
78852 ** check that it is defined. An undefined collation sequence exists when
78853 ** a database is loaded that contains references to collation sequences
78854 ** that have not been defined by sqlite3_create_collation() etc.
78855 **
78856 ** If required, this routine calls the 'collation needed' callback to
78857 ** request a definition of the collating sequence. If this doesn't work, 
78858 ** an equivalent collating sequence that uses a text encoding different
78859 ** from the main database is substituted, if one is available.
78860 */
78861 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
78862   if( pColl ){
78863     const char *zName = pColl->zName;
78864     sqlite3 *db = pParse->db;
78865     CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
78866     if( !p ){
78867       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
78868       pParse->nErr++;
78869       return SQLITE_ERROR;
78870     }
78871     assert( p==pColl );
78872   }
78873   return SQLITE_OK;
78874 }
78875
78876
78877
78878 /*
78879 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
78880 ** specified by zName and nName is not found and parameter 'create' is
78881 ** true, then create a new entry. Otherwise return NULL.
78882 **
78883 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
78884 ** array of three CollSeq structures. The first is the collation sequence
78885 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
78886 **
78887 ** Stored immediately after the three collation sequences is a copy of
78888 ** the collation sequence name. A pointer to this string is stored in
78889 ** each collation sequence structure.
78890 */
78891 static CollSeq *findCollSeqEntry(
78892   sqlite3 *db,          /* Database connection */
78893   const char *zName,    /* Name of the collating sequence */
78894   int create            /* Create a new entry if true */
78895 ){
78896   CollSeq *pColl;
78897   int nName = sqlite3Strlen30(zName);
78898   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
78899
78900   if( 0==pColl && create ){
78901     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
78902     if( pColl ){
78903       CollSeq *pDel = 0;
78904       pColl[0].zName = (char*)&pColl[3];
78905       pColl[0].enc = SQLITE_UTF8;
78906       pColl[1].zName = (char*)&pColl[3];
78907       pColl[1].enc = SQLITE_UTF16LE;
78908       pColl[2].zName = (char*)&pColl[3];
78909       pColl[2].enc = SQLITE_UTF16BE;
78910       memcpy(pColl[0].zName, zName, nName);
78911       pColl[0].zName[nName] = 0;
78912       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
78913
78914       /* If a malloc() failure occurred in sqlite3HashInsert(), it will 
78915       ** return the pColl pointer to be deleted (because it wasn't added
78916       ** to the hash table).
78917       */
78918       assert( pDel==0 || pDel==pColl );
78919       if( pDel!=0 ){
78920         db->mallocFailed = 1;
78921         sqlite3DbFree(db, pDel);
78922         pColl = 0;
78923       }
78924     }
78925   }
78926   return pColl;
78927 }
78928
78929 /*
78930 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
78931 ** Return the CollSeq* pointer for the collation sequence named zName
78932 ** for the encoding 'enc' from the database 'db'.
78933 **
78934 ** If the entry specified is not found and 'create' is true, then create a
78935 ** new entry.  Otherwise return NULL.
78936 **
78937 ** A separate function sqlite3LocateCollSeq() is a wrapper around
78938 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
78939 ** if necessary and generates an error message if the collating sequence
78940 ** cannot be found.
78941 **
78942 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
78943 */
78944 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
78945   sqlite3 *db,
78946   u8 enc,
78947   const char *zName,
78948   int create
78949 ){
78950   CollSeq *pColl;
78951   if( zName ){
78952     pColl = findCollSeqEntry(db, zName, create);
78953   }else{
78954     pColl = db->pDfltColl;
78955   }
78956   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
78957   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
78958   if( pColl ) pColl += enc-1;
78959   return pColl;
78960 }
78961
78962 /* During the search for the best function definition, this procedure
78963 ** is called to test how well the function passed as the first argument
78964 ** matches the request for a function with nArg arguments in a system
78965 ** that uses encoding enc. The value returned indicates how well the
78966 ** request is matched. A higher value indicates a better match.
78967 **
78968 ** The returned value is always between 0 and 6, as follows:
78969 **
78970 ** 0: Not a match, or if nArg<0 and the function is has no implementation.
78971 ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
78972 **    encoding is requested, or vice versa.
78973 ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
78974 **    requested, or vice versa.
78975 ** 3: A variable arguments function using the same text encoding.
78976 ** 4: A function with the exact number of arguments requested that
78977 **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
78978 ** 5: A function with the exact number of arguments requested that
78979 **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
78980 ** 6: An exact match.
78981 **
78982 */
78983 static int matchQuality(FuncDef *p, int nArg, u8 enc){
78984   int match = 0;
78985   if( p->nArg==-1 || p->nArg==nArg 
78986    || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
78987   ){
78988     match = 1;
78989     if( p->nArg==nArg || nArg==-1 ){
78990       match = 4;
78991     }
78992     if( enc==p->iPrefEnc ){
78993       match += 2;
78994     }
78995     else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
78996              (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
78997       match += 1;
78998     }
78999   }
79000   return match;
79001 }
79002
79003 /*
79004 ** Search a FuncDefHash for a function with the given name.  Return
79005 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
79006 */
79007 static FuncDef *functionSearch(
79008   FuncDefHash *pHash,  /* Hash table to search */
79009   int h,               /* Hash of the name */
79010   const char *zFunc,   /* Name of function */
79011   int nFunc            /* Number of bytes in zFunc */
79012 ){
79013   FuncDef *p;
79014   for(p=pHash->a[h]; p; p=p->pHash){
79015     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
79016       return p;
79017     }
79018   }
79019   return 0;
79020 }
79021
79022 /*
79023 ** Insert a new FuncDef into a FuncDefHash hash table.
79024 */
79025 SQLITE_PRIVATE void sqlite3FuncDefInsert(
79026   FuncDefHash *pHash,  /* The hash table into which to insert */
79027   FuncDef *pDef        /* The function definition to insert */
79028 ){
79029   FuncDef *pOther;
79030   int nName = sqlite3Strlen30(pDef->zName);
79031   u8 c1 = (u8)pDef->zName[0];
79032   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
79033   pOther = functionSearch(pHash, h, pDef->zName, nName);
79034   if( pOther ){
79035     assert( pOther!=pDef && pOther->pNext!=pDef );
79036     pDef->pNext = pOther->pNext;
79037     pOther->pNext = pDef;
79038   }else{
79039     pDef->pNext = 0;
79040     pDef->pHash = pHash->a[h];
79041     pHash->a[h] = pDef;
79042   }
79043 }
79044   
79045   
79046
79047 /*
79048 ** Locate a user function given a name, a number of arguments and a flag
79049 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
79050 ** pointer to the FuncDef structure that defines that function, or return
79051 ** NULL if the function does not exist.
79052 **
79053 ** If the createFlag argument is true, then a new (blank) FuncDef
79054 ** structure is created and liked into the "db" structure if a
79055 ** no matching function previously existed.  When createFlag is true
79056 ** and the nArg parameter is -1, then only a function that accepts
79057 ** any number of arguments will be returned.
79058 **
79059 ** If createFlag is false and nArg is -1, then the first valid
79060 ** function found is returned.  A function is valid if either xFunc
79061 ** or xStep is non-zero.
79062 **
79063 ** If createFlag is false, then a function with the required name and
79064 ** number of arguments may be returned even if the eTextRep flag does not
79065 ** match that requested.
79066 */
79067 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
79068   sqlite3 *db,       /* An open database */
79069   const char *zName, /* Name of the function.  Not null-terminated */
79070   int nName,         /* Number of characters in the name */
79071   int nArg,          /* Number of arguments.  -1 means any number */
79072   u8 enc,            /* Preferred text encoding */
79073   int createFlag     /* Create new entry if true and does not otherwise exist */
79074 ){
79075   FuncDef *p;         /* Iterator variable */
79076   FuncDef *pBest = 0; /* Best match found so far */
79077   int bestScore = 0;  /* Score of best match */
79078   int h;              /* Hash value */
79079
79080
79081   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
79082   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
79083
79084   /* First search for a match amongst the application-defined functions.
79085   */
79086   p = functionSearch(&db->aFunc, h, zName, nName);
79087   while( p ){
79088     int score = matchQuality(p, nArg, enc);
79089     if( score>bestScore ){
79090       pBest = p;
79091       bestScore = score;
79092     }
79093     p = p->pNext;
79094   }
79095
79096   /* If no match is found, search the built-in functions.
79097   **
79098   ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
79099   ** functions even if a prior app-defined function was found.  And give
79100   ** priority to built-in functions.
79101   **
79102   ** Except, if createFlag is true, that means that we are trying to
79103   ** install a new function.  Whatever FuncDef structure is returned it will
79104   ** have fields overwritten with new information appropriate for the
79105   ** new function.  But the FuncDefs for built-in functions are read-only.
79106   ** So we must not search for built-ins when creating a new function.
79107   */ 
79108   if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
79109     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
79110     bestScore = 0;
79111     p = functionSearch(pHash, h, zName, nName);
79112     while( p ){
79113       int score = matchQuality(p, nArg, enc);
79114       if( score>bestScore ){
79115         pBest = p;
79116         bestScore = score;
79117       }
79118       p = p->pNext;
79119     }
79120   }
79121
79122   /* If the createFlag parameter is true and the search did not reveal an
79123   ** exact match for the name, number of arguments and encoding, then add a
79124   ** new entry to the hash table and return it.
79125   */
79126   if( createFlag && (bestScore<6 || pBest->nArg!=nArg) && 
79127       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
79128     pBest->zName = (char *)&pBest[1];
79129     pBest->nArg = (u16)nArg;
79130     pBest->iPrefEnc = enc;
79131     memcpy(pBest->zName, zName, nName);
79132     pBest->zName[nName] = 0;
79133     sqlite3FuncDefInsert(&db->aFunc, pBest);
79134   }
79135
79136   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
79137     return pBest;
79138   }
79139   return 0;
79140 }
79141
79142 /*
79143 ** Free all resources held by the schema structure. The void* argument points
79144 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
79145 ** pointer itself, it just cleans up subsiduary resources (i.e. the contents
79146 ** of the schema hash tables).
79147 **
79148 ** The Schema.cache_size variable is not cleared.
79149 */
79150 SQLITE_PRIVATE void sqlite3SchemaFree(void *p){
79151   Hash temp1;
79152   Hash temp2;
79153   HashElem *pElem;
79154   Schema *pSchema = (Schema *)p;
79155
79156   temp1 = pSchema->tblHash;
79157   temp2 = pSchema->trigHash;
79158   sqlite3HashInit(&pSchema->trigHash);
79159   sqlite3HashClear(&pSchema->idxHash);
79160   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
79161     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
79162   }
79163   sqlite3HashClear(&temp2);
79164   sqlite3HashInit(&pSchema->tblHash);
79165   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
79166     Table *pTab = sqliteHashData(pElem);
79167     sqlite3DeleteTable(0, pTab);
79168   }
79169   sqlite3HashClear(&temp1);
79170   sqlite3HashClear(&pSchema->fkeyHash);
79171   pSchema->pSeqTab = 0;
79172   pSchema->flags &= ~DB_SchemaLoaded;
79173 }
79174
79175 /*
79176 ** Find and return the schema associated with a BTree.  Create
79177 ** a new one if necessary.
79178 */
79179 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
79180   Schema * p;
79181   if( pBt ){
79182     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
79183   }else{
79184     p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
79185   }
79186   if( !p ){
79187     db->mallocFailed = 1;
79188   }else if ( 0==p->file_format ){
79189     sqlite3HashInit(&p->tblHash);
79190     sqlite3HashInit(&p->idxHash);
79191     sqlite3HashInit(&p->trigHash);
79192     sqlite3HashInit(&p->fkeyHash);
79193     p->enc = SQLITE_UTF8;
79194   }
79195   return p;
79196 }
79197
79198 /************** End of callback.c ********************************************/
79199 /************** Begin file delete.c ******************************************/
79200 /*
79201 ** 2001 September 15
79202 **
79203 ** The author disclaims copyright to this source code.  In place of
79204 ** a legal notice, here is a blessing:
79205 **
79206 **    May you do good and not evil.
79207 **    May you find forgiveness for yourself and forgive others.
79208 **    May you share freely, never taking more than you give.
79209 **
79210 *************************************************************************
79211 ** This file contains C code routines that are called by the parser
79212 ** in order to generate code for DELETE FROM statements.
79213 */
79214
79215 /*
79216 ** Look up every table that is named in pSrc.  If any table is not found,
79217 ** add an error message to pParse->zErrMsg and return NULL.  If all tables
79218 ** are found, return a pointer to the last table.
79219 */
79220 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
79221   struct SrcList_item *pItem = pSrc->a;
79222   Table *pTab;
79223   assert( pItem && pSrc->nSrc==1 );
79224   pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
79225   sqlite3DeleteTable(pParse->db, pItem->pTab);
79226   pItem->pTab = pTab;
79227   if( pTab ){
79228     pTab->nRef++;
79229   }
79230   if( sqlite3IndexedByLookup(pParse, pItem) ){
79231     pTab = 0;
79232   }
79233   return pTab;
79234 }
79235
79236 /*
79237 ** Check to make sure the given table is writable.  If it is not
79238 ** writable, generate an error message and return 1.  If it is
79239 ** writable return 0;
79240 */
79241 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
79242   /* A table is not writable under the following circumstances:
79243   **
79244   **   1) It is a virtual table and no implementation of the xUpdate method
79245   **      has been provided, or
79246   **   2) It is a system table (i.e. sqlite_master), this call is not
79247   **      part of a nested parse and writable_schema pragma has not 
79248   **      been specified.
79249   **
79250   ** In either case leave an error message in pParse and return non-zero.
79251   */
79252   if( ( IsVirtual(pTab) 
79253      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
79254    || ( (pTab->tabFlags & TF_Readonly)!=0
79255      && (pParse->db->flags & SQLITE_WriteSchema)==0
79256      && pParse->nested==0 )
79257   ){
79258     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
79259     return 1;
79260   }
79261
79262 #ifndef SQLITE_OMIT_VIEW
79263   if( !viewOk && pTab->pSelect ){
79264     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
79265     return 1;
79266   }
79267 #endif
79268   return 0;
79269 }
79270
79271
79272 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
79273 /*
79274 ** Evaluate a view and store its result in an ephemeral table.  The
79275 ** pWhere argument is an optional WHERE clause that restricts the
79276 ** set of rows in the view that are to be added to the ephemeral table.
79277 */
79278 SQLITE_PRIVATE void sqlite3MaterializeView(
79279   Parse *pParse,       /* Parsing context */
79280   Table *pView,        /* View definition */
79281   Expr *pWhere,        /* Optional WHERE clause to be added */
79282   int iCur             /* Cursor number for ephemerial table */
79283 ){
79284   SelectDest dest;
79285   Select *pDup;
79286   sqlite3 *db = pParse->db;
79287
79288   pDup = sqlite3SelectDup(db, pView->pSelect, 0);
79289   if( pWhere ){
79290     SrcList *pFrom;
79291     
79292     pWhere = sqlite3ExprDup(db, pWhere, 0);
79293     pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
79294     if( pFrom ){
79295       assert( pFrom->nSrc==1 );
79296       pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
79297       pFrom->a[0].pSelect = pDup;
79298       assert( pFrom->a[0].pOn==0 );
79299       assert( pFrom->a[0].pUsing==0 );
79300     }else{
79301       sqlite3SelectDelete(db, pDup);
79302     }
79303     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
79304   }
79305   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
79306   sqlite3Select(pParse, pDup, &dest);
79307   sqlite3SelectDelete(db, pDup);
79308 }
79309 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
79310
79311 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
79312 /*
79313 ** Generate an expression tree to implement the WHERE, ORDER BY,
79314 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
79315 **
79316 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
79317 **                            \__________________________/
79318 **                               pLimitWhere (pInClause)
79319 */
79320 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
79321   Parse *pParse,               /* The parser context */
79322   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
79323   Expr *pWhere,                /* The WHERE clause.  May be null */
79324   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
79325   Expr *pLimit,                /* The LIMIT clause.  May be null */
79326   Expr *pOffset,               /* The OFFSET clause.  May be null */
79327   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
79328 ){
79329   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
79330   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
79331   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
79332   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
79333   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
79334   Select *pSelect = NULL;      /* Complete SELECT tree */
79335
79336   /* Check that there isn't an ORDER BY without a LIMIT clause.
79337   */
79338   if( pOrderBy && (pLimit == 0) ) {
79339     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
79340     pParse->parseError = 1;
79341     goto limit_where_cleanup_2;
79342   }
79343
79344   /* We only need to generate a select expression if there
79345   ** is a limit/offset term to enforce.
79346   */
79347   if( pLimit == 0 ) {
79348     /* if pLimit is null, pOffset will always be null as well. */
79349     assert( pOffset == 0 );
79350     return pWhere;
79351   }
79352
79353   /* Generate a select expression tree to enforce the limit/offset 
79354   ** term for the DELETE or UPDATE statement.  For example:
79355   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
79356   ** becomes:
79357   **   DELETE FROM table_a WHERE rowid IN ( 
79358   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
79359   **   );
79360   */
79361
79362   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
79363   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
79364   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
79365   if( pEList == 0 ) goto limit_where_cleanup_2;
79366
79367   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
79368   ** and the SELECT subtree. */
79369   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
79370   if( pSelectSrc == 0 ) {
79371     sqlite3ExprListDelete(pParse->db, pEList);
79372     goto limit_where_cleanup_2;
79373   }
79374
79375   /* generate the SELECT expression tree. */
79376   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
79377                              pOrderBy,0,pLimit,pOffset);
79378   if( pSelect == 0 ) return 0;
79379
79380   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
79381   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
79382   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
79383   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
79384   if( pInClause == 0 ) goto limit_where_cleanup_1;
79385
79386   pInClause->x.pSelect = pSelect;
79387   pInClause->flags |= EP_xIsSelect;
79388   sqlite3ExprSetHeight(pParse, pInClause);
79389   return pInClause;
79390
79391   /* something went wrong. clean up anything allocated. */
79392 limit_where_cleanup_1:
79393   sqlite3SelectDelete(pParse->db, pSelect);
79394   return 0;
79395
79396 limit_where_cleanup_2:
79397   sqlite3ExprDelete(pParse->db, pWhere);
79398   sqlite3ExprListDelete(pParse->db, pOrderBy);
79399   sqlite3ExprDelete(pParse->db, pLimit);
79400   sqlite3ExprDelete(pParse->db, pOffset);
79401   return 0;
79402 }
79403 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
79404
79405 /*
79406 ** Generate code for a DELETE FROM statement.
79407 **
79408 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
79409 **                 \________/       \________________/
79410 **                  pTabList              pWhere
79411 */
79412 SQLITE_PRIVATE void sqlite3DeleteFrom(
79413   Parse *pParse,         /* The parser context */
79414   SrcList *pTabList,     /* The table from which we should delete things */
79415   Expr *pWhere           /* The WHERE clause.  May be null */
79416 ){
79417   Vdbe *v;               /* The virtual database engine */
79418   Table *pTab;           /* The table from which records will be deleted */
79419   const char *zDb;       /* Name of database holding pTab */
79420   int end, addr = 0;     /* A couple addresses of generated code */
79421   int i;                 /* Loop counter */
79422   WhereInfo *pWInfo;     /* Information about the WHERE clause */
79423   Index *pIdx;           /* For looping over indices of the table */
79424   int iCur;              /* VDBE Cursor number for pTab */
79425   sqlite3 *db;           /* Main database structure */
79426   AuthContext sContext;  /* Authorization context */
79427   NameContext sNC;       /* Name context to resolve expressions in */
79428   int iDb;               /* Database number */
79429   int memCnt = -1;       /* Memory cell used for change counting */
79430   int rcauth;            /* Value returned by authorization callback */
79431
79432 #ifndef SQLITE_OMIT_TRIGGER
79433   int isView;                  /* True if attempting to delete from a view */
79434   Trigger *pTrigger;           /* List of table triggers, if required */
79435 #endif
79436
79437   memset(&sContext, 0, sizeof(sContext));
79438   db = pParse->db;
79439   if( pParse->nErr || db->mallocFailed ){
79440     goto delete_from_cleanup;
79441   }
79442   assert( pTabList->nSrc==1 );
79443
79444   /* Locate the table which we want to delete.  This table has to be
79445   ** put in an SrcList structure because some of the subroutines we
79446   ** will be calling are designed to work with multiple tables and expect
79447   ** an SrcList* parameter instead of just a Table* parameter.
79448   */
79449   pTab = sqlite3SrcListLookup(pParse, pTabList);
79450   if( pTab==0 )  goto delete_from_cleanup;
79451
79452   /* Figure out if we have any triggers and if the table being
79453   ** deleted from is a view
79454   */
79455 #ifndef SQLITE_OMIT_TRIGGER
79456   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
79457   isView = pTab->pSelect!=0;
79458 #else
79459 # define pTrigger 0
79460 # define isView 0
79461 #endif
79462 #ifdef SQLITE_OMIT_VIEW
79463 # undef isView
79464 # define isView 0
79465 #endif
79466
79467   /* If pTab is really a view, make sure it has been initialized.
79468   */
79469   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
79470     goto delete_from_cleanup;
79471   }
79472
79473   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
79474     goto delete_from_cleanup;
79475   }
79476   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
79477   assert( iDb<db->nDb );
79478   zDb = db->aDb[iDb].zName;
79479   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
79480   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
79481   if( rcauth==SQLITE_DENY ){
79482     goto delete_from_cleanup;
79483   }
79484   assert(!isView || pTrigger);
79485
79486   /* Assign  cursor number to the table and all its indices.
79487   */
79488   assert( pTabList->nSrc==1 );
79489   iCur = pTabList->a[0].iCursor = pParse->nTab++;
79490   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
79491     pParse->nTab++;
79492   }
79493
79494   /* Start the view context
79495   */
79496   if( isView ){
79497     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
79498   }
79499
79500   /* Begin generating code.
79501   */
79502   v = sqlite3GetVdbe(pParse);
79503   if( v==0 ){
79504     goto delete_from_cleanup;
79505   }
79506   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
79507   sqlite3BeginWriteOperation(pParse, 1, iDb);
79508
79509   /* If we are trying to delete from a view, realize that view into
79510   ** a ephemeral table.
79511   */
79512 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
79513   if( isView ){
79514     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
79515   }
79516 #endif
79517
79518   /* Resolve the column names in the WHERE clause.
79519   */
79520   memset(&sNC, 0, sizeof(sNC));
79521   sNC.pParse = pParse;
79522   sNC.pSrcList = pTabList;
79523   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
79524     goto delete_from_cleanup;
79525   }
79526
79527   /* Initialize the counter of the number of rows deleted, if
79528   ** we are counting rows.
79529   */
79530   if( db->flags & SQLITE_CountRows ){
79531     memCnt = ++pParse->nMem;
79532     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
79533   }
79534
79535 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
79536   /* Special case: A DELETE without a WHERE clause deletes everything.
79537   ** It is easier just to erase the whole table. Prior to version 3.6.5,
79538   ** this optimization caused the row change count (the value returned by 
79539   ** API function sqlite3_count_changes) to be set incorrectly.  */
79540   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) 
79541    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
79542   ){
79543     assert( !isView );
79544     sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
79545                       pTab->zName, P4_STATIC);
79546     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
79547       assert( pIdx->pSchema==pTab->pSchema );
79548       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
79549     }
79550   }else
79551 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
79552   /* The usual case: There is a WHERE clause so we have to scan through
79553   ** the table and pick which records to delete.
79554   */
79555   {
79556     int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
79557     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
79558     int regRowid;                   /* Actual register containing rowids */
79559
79560     /* Collect rowids of every row to be deleted.
79561     */
79562     sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
79563     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,WHERE_DUPLICATES_OK);
79564     if( pWInfo==0 ) goto delete_from_cleanup;
79565     regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
79566     sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
79567     if( db->flags & SQLITE_CountRows ){
79568       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
79569     }
79570     sqlite3WhereEnd(pWInfo);
79571
79572     /* Delete every item whose key was written to the list during the
79573     ** database scan.  We have to delete items after the scan is complete
79574     ** because deleting an item can change the scan order.  */
79575     end = sqlite3VdbeMakeLabel(v);
79576
79577     /* Unless this is a view, open cursors for the table we are 
79578     ** deleting from and all its indices. If this is a view, then the
79579     ** only effect this statement has is to fire the INSTEAD OF 
79580     ** triggers.  */
79581     if( !isView ){
79582       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
79583     }
79584
79585     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
79586
79587     /* Delete the row */
79588 #ifndef SQLITE_OMIT_VIRTUALTABLE
79589     if( IsVirtual(pTab) ){
79590       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
79591       sqlite3VtabMakeWritable(pParse, pTab);
79592       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
79593       sqlite3MayAbort(pParse);
79594     }else
79595 #endif
79596     {
79597       int count = (pParse->nested==0);    /* True to count changes */
79598       sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
79599     }
79600
79601     /* End of the delete loop */
79602     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
79603     sqlite3VdbeResolveLabel(v, end);
79604
79605     /* Close the cursors open on the table and its indexes. */
79606     if( !isView && !IsVirtual(pTab) ){
79607       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
79608         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
79609       }
79610       sqlite3VdbeAddOp1(v, OP_Close, iCur);
79611     }
79612   }
79613
79614   /* Update the sqlite_sequence table by storing the content of the
79615   ** maximum rowid counter values recorded while inserting into
79616   ** autoincrement tables.
79617   */
79618   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
79619     sqlite3AutoincrementEnd(pParse);
79620   }
79621
79622   /* Return the number of rows that were deleted. If this routine is 
79623   ** generating code because of a call to sqlite3NestedParse(), do not
79624   ** invoke the callback function.
79625   */
79626   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
79627     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
79628     sqlite3VdbeSetNumCols(v, 1);
79629     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
79630   }
79631
79632 delete_from_cleanup:
79633   sqlite3AuthContextPop(&sContext);
79634   sqlite3SrcListDelete(db, pTabList);
79635   sqlite3ExprDelete(db, pWhere);
79636   return;
79637 }
79638 /* Make sure "isView" and other macros defined above are undefined. Otherwise
79639 ** thely may interfere with compilation of other functions in this file
79640 ** (or in another file, if this file becomes part of the amalgamation).  */
79641 #ifdef isView
79642  #undef isView
79643 #endif
79644 #ifdef pTrigger
79645  #undef pTrigger
79646 #endif
79647
79648 /*
79649 ** This routine generates VDBE code that causes a single row of a
79650 ** single table to be deleted.
79651 **
79652 ** The VDBE must be in a particular state when this routine is called.
79653 ** These are the requirements:
79654 **
79655 **   1.  A read/write cursor pointing to pTab, the table containing the row
79656 **       to be deleted, must be opened as cursor number $iCur.
79657 **
79658 **   2.  Read/write cursors for all indices of pTab must be open as
79659 **       cursor number base+i for the i-th index.
79660 **
79661 **   3.  The record number of the row to be deleted must be stored in
79662 **       memory cell iRowid.
79663 **
79664 ** This routine generates code to remove both the table record and all 
79665 ** index entries that point to that record.
79666 */
79667 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
79668   Parse *pParse,     /* Parsing context */
79669   Table *pTab,       /* Table containing the row to be deleted */
79670   int iCur,          /* Cursor number for the table */
79671   int iRowid,        /* Memory cell that contains the rowid to delete */
79672   int count,         /* If non-zero, increment the row change counter */
79673   Trigger *pTrigger, /* List of triggers to (potentially) fire */
79674   int onconf         /* Default ON CONFLICT policy for triggers */
79675 ){
79676   Vdbe *v = pParse->pVdbe;        /* Vdbe */
79677   int iOld = 0;                   /* First register in OLD.* array */
79678   int iLabel;                     /* Label resolved to end of generated code */
79679
79680   /* Vdbe is guaranteed to have been allocated by this stage. */
79681   assert( v );
79682
79683   /* Seek cursor iCur to the row to delete. If this row no longer exists 
79684   ** (this can happen if a trigger program has already deleted it), do
79685   ** not attempt to delete it or fire any DELETE triggers.  */
79686   iLabel = sqlite3VdbeMakeLabel(v);
79687   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
79688  
79689   /* If there are any triggers to fire, allocate a range of registers to
79690   ** use for the old.* references in the triggers.  */
79691   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
79692     u32 mask;                     /* Mask of OLD.* columns in use */
79693     int iCol;                     /* Iterator used while populating OLD.* */
79694
79695     /* TODO: Could use temporary registers here. Also could attempt to
79696     ** avoid copying the contents of the rowid register.  */
79697     mask = sqlite3TriggerColmask(
79698         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
79699     );
79700     mask |= sqlite3FkOldmask(pParse, pTab);
79701     iOld = pParse->nMem+1;
79702     pParse->nMem += (1 + pTab->nCol);
79703
79704     /* Populate the OLD.* pseudo-table register array. These values will be 
79705     ** used by any BEFORE and AFTER triggers that exist.  */
79706     sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
79707     for(iCol=0; iCol<pTab->nCol; iCol++){
79708       if( mask==0xffffffff || mask&(1<<iCol) ){
79709         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
79710       }
79711     }
79712
79713     /* Invoke BEFORE DELETE trigger programs. */
79714     sqlite3CodeRowTrigger(pParse, pTrigger, 
79715         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
79716     );
79717
79718     /* Seek the cursor to the row to be deleted again. It may be that
79719     ** the BEFORE triggers coded above have already removed the row
79720     ** being deleted. Do not attempt to delete the row a second time, and 
79721     ** do not fire AFTER triggers.  */
79722     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
79723
79724     /* Do FK processing. This call checks that any FK constraints that
79725     ** refer to this table (i.e. constraints attached to other tables) 
79726     ** are not violated by deleting this row.  */
79727     sqlite3FkCheck(pParse, pTab, iOld, 0);
79728   }
79729
79730   /* Delete the index and table entries. Skip this step if pTab is really
79731   ** a view (in which case the only effect of the DELETE statement is to
79732   ** fire the INSTEAD OF triggers).  */ 
79733   if( pTab->pSelect==0 ){
79734     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
79735     sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
79736     if( count ){
79737       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
79738     }
79739   }
79740
79741   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
79742   ** handle rows (possibly in other tables) that refer via a foreign key
79743   ** to the row just deleted. */ 
79744   sqlite3FkActions(pParse, pTab, 0, iOld);
79745
79746   /* Invoke AFTER DELETE trigger programs. */
79747   sqlite3CodeRowTrigger(pParse, pTrigger, 
79748       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
79749   );
79750
79751   /* Jump here if the row had already been deleted before any BEFORE
79752   ** trigger programs were invoked. Or if a trigger program throws a 
79753   ** RAISE(IGNORE) exception.  */
79754   sqlite3VdbeResolveLabel(v, iLabel);
79755 }
79756
79757 /*
79758 ** This routine generates VDBE code that causes the deletion of all
79759 ** index entries associated with a single row of a single table.
79760 **
79761 ** The VDBE must be in a particular state when this routine is called.
79762 ** These are the requirements:
79763 **
79764 **   1.  A read/write cursor pointing to pTab, the table containing the row
79765 **       to be deleted, must be opened as cursor number "iCur".
79766 **
79767 **   2.  Read/write cursors for all indices of pTab must be open as
79768 **       cursor number iCur+i for the i-th index.
79769 **
79770 **   3.  The "iCur" cursor must be pointing to the row that is to be
79771 **       deleted.
79772 */
79773 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
79774   Parse *pParse,     /* Parsing and code generating context */
79775   Table *pTab,       /* Table containing the row to be deleted */
79776   int iCur,          /* Cursor number for the table */
79777   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
79778 ){
79779   int i;
79780   Index *pIdx;
79781   int r1;
79782
79783   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
79784     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
79785     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
79786     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
79787   }
79788 }
79789
79790 /*
79791 ** Generate code that will assemble an index key and put it in register
79792 ** regOut.  The key with be for index pIdx which is an index on pTab.
79793 ** iCur is the index of a cursor open on the pTab table and pointing to
79794 ** the entry that needs indexing.
79795 **
79796 ** Return a register number which is the first in a block of
79797 ** registers that holds the elements of the index key.  The
79798 ** block of registers has already been deallocated by the time
79799 ** this routine returns.
79800 */
79801 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
79802   Parse *pParse,     /* Parsing context */
79803   Index *pIdx,       /* The index for which to generate a key */
79804   int iCur,          /* Cursor number for the pIdx->pTable table */
79805   int regOut,        /* Write the new index key to this register */
79806   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
79807 ){
79808   Vdbe *v = pParse->pVdbe;
79809   int j;
79810   Table *pTab = pIdx->pTable;
79811   int regBase;
79812   int nCol;
79813
79814   nCol = pIdx->nColumn;
79815   regBase = sqlite3GetTempRange(pParse, nCol+1);
79816   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
79817   for(j=0; j<nCol; j++){
79818     int idx = pIdx->aiColumn[j];
79819     if( idx==pTab->iPKey ){
79820       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
79821     }else{
79822       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
79823       sqlite3ColumnDefault(v, pTab, idx, -1);
79824     }
79825   }
79826   if( doMakeRec ){
79827     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
79828     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
79829   }
79830   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
79831   return regBase;
79832 }
79833
79834 /************** End of delete.c **********************************************/
79835 /************** Begin file func.c ********************************************/
79836 /*
79837 ** 2002 February 23
79838 **
79839 ** The author disclaims copyright to this source code.  In place of
79840 ** a legal notice, here is a blessing:
79841 **
79842 **    May you do good and not evil.
79843 **    May you find forgiveness for yourself and forgive others.
79844 **    May you share freely, never taking more than you give.
79845 **
79846 *************************************************************************
79847 ** This file contains the C functions that implement various SQL
79848 ** functions of SQLite.  
79849 **
79850 ** There is only one exported symbol in this file - the function
79851 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
79852 ** All other code has file scope.
79853 */
79854
79855 /*
79856 ** Return the collating function associated with a function.
79857 */
79858 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
79859   return context->pColl;
79860 }
79861
79862 /*
79863 ** Implementation of the non-aggregate min() and max() functions
79864 */
79865 static void minmaxFunc(
79866   sqlite3_context *context,
79867   int argc,
79868   sqlite3_value **argv
79869 ){
79870   int i;
79871   int mask;    /* 0 for min() or 0xffffffff for max() */
79872   int iBest;
79873   CollSeq *pColl;
79874
79875   assert( argc>1 );
79876   mask = sqlite3_user_data(context)==0 ? 0 : -1;
79877   pColl = sqlite3GetFuncCollSeq(context);
79878   assert( pColl );
79879   assert( mask==-1 || mask==0 );
79880   iBest = 0;
79881   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
79882   for(i=1; i<argc; i++){
79883     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
79884     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
79885       testcase( mask==0 );
79886       iBest = i;
79887     }
79888   }
79889   sqlite3_result_value(context, argv[iBest]);
79890 }
79891
79892 /*
79893 ** Return the type of the argument.
79894 */
79895 static void typeofFunc(
79896   sqlite3_context *context,
79897   int NotUsed,
79898   sqlite3_value **argv
79899 ){
79900   const char *z = 0;
79901   UNUSED_PARAMETER(NotUsed);
79902   switch( sqlite3_value_type(argv[0]) ){
79903     case SQLITE_INTEGER: z = "integer"; break;
79904     case SQLITE_TEXT:    z = "text";    break;
79905     case SQLITE_FLOAT:   z = "real";    break;
79906     case SQLITE_BLOB:    z = "blob";    break;
79907     default:             z = "null";    break;
79908   }
79909   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
79910 }
79911
79912
79913 /*
79914 ** Implementation of the length() function
79915 */
79916 static void lengthFunc(
79917   sqlite3_context *context,
79918   int argc,
79919   sqlite3_value **argv
79920 ){
79921   int len;
79922
79923   assert( argc==1 );
79924   UNUSED_PARAMETER(argc);
79925   switch( sqlite3_value_type(argv[0]) ){
79926     case SQLITE_BLOB:
79927     case SQLITE_INTEGER:
79928     case SQLITE_FLOAT: {
79929       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
79930       break;
79931     }
79932     case SQLITE_TEXT: {
79933       const unsigned char *z = sqlite3_value_text(argv[0]);
79934       if( z==0 ) return;
79935       len = 0;
79936       while( *z ){
79937         len++;
79938         SQLITE_SKIP_UTF8(z);
79939       }
79940       sqlite3_result_int(context, len);
79941       break;
79942     }
79943     default: {
79944       sqlite3_result_null(context);
79945       break;
79946     }
79947   }
79948 }
79949
79950 /*
79951 ** Implementation of the abs() function.
79952 **
79953 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
79954 ** the numeric argument X. 
79955 */
79956 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
79957   assert( argc==1 );
79958   UNUSED_PARAMETER(argc);
79959   switch( sqlite3_value_type(argv[0]) ){
79960     case SQLITE_INTEGER: {
79961       i64 iVal = sqlite3_value_int64(argv[0]);
79962       if( iVal<0 ){
79963         if( (iVal<<1)==0 ){
79964           /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
79965           ** abs(X) throws an integer overflow error since there is no
79966           ** equivalent positive 64-bit two complement value. */
79967           sqlite3_result_error(context, "integer overflow", -1);
79968           return;
79969         }
79970         iVal = -iVal;
79971       } 
79972       sqlite3_result_int64(context, iVal);
79973       break;
79974     }
79975     case SQLITE_NULL: {
79976       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
79977       sqlite3_result_null(context);
79978       break;
79979     }
79980     default: {
79981       /* Because sqlite3_value_double() returns 0.0 if the argument is not
79982       ** something that can be converted into a number, we have:
79983       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
79984       ** cannot be converted to a numeric value. 
79985       */
79986       double rVal = sqlite3_value_double(argv[0]);
79987       if( rVal<0 ) rVal = -rVal;
79988       sqlite3_result_double(context, rVal);
79989       break;
79990     }
79991   }
79992 }
79993
79994 /*
79995 ** Implementation of the substr() function.
79996 **
79997 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
79998 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
79999 ** of x.  If x is text, then we actually count UTF-8 characters.
80000 ** If x is a blob, then we count bytes.
80001 **
80002 ** If p1 is negative, then we begin abs(p1) from the end of x[].
80003 **
80004 ** If p2 is negative, return the p2 characters preceeding p1.
80005 */
80006 static void substrFunc(
80007   sqlite3_context *context,
80008   int argc,
80009   sqlite3_value **argv
80010 ){
80011   const unsigned char *z;
80012   const unsigned char *z2;
80013   int len;
80014   int p0type;
80015   i64 p1, p2;
80016   int negP2 = 0;
80017
80018   assert( argc==3 || argc==2 );
80019   if( sqlite3_value_type(argv[1])==SQLITE_NULL
80020    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
80021   ){
80022     return;
80023   }
80024   p0type = sqlite3_value_type(argv[0]);
80025   p1 = sqlite3_value_int(argv[1]);
80026   if( p0type==SQLITE_BLOB ){
80027     len = sqlite3_value_bytes(argv[0]);
80028     z = sqlite3_value_blob(argv[0]);
80029     if( z==0 ) return;
80030     assert( len==sqlite3_value_bytes(argv[0]) );
80031   }else{
80032     z = sqlite3_value_text(argv[0]);
80033     if( z==0 ) return;
80034     len = 0;
80035     if( p1<0 ){
80036       for(z2=z; *z2; len++){
80037         SQLITE_SKIP_UTF8(z2);
80038       }
80039     }
80040   }
80041   if( argc==3 ){
80042     p2 = sqlite3_value_int(argv[2]);
80043     if( p2<0 ){
80044       p2 = -p2;
80045       negP2 = 1;
80046     }
80047   }else{
80048     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
80049   }
80050   if( p1<0 ){
80051     p1 += len;
80052     if( p1<0 ){
80053       p2 += p1;
80054       if( p2<0 ) p2 = 0;
80055       p1 = 0;
80056     }
80057   }else if( p1>0 ){
80058     p1--;
80059   }else if( p2>0 ){
80060     p2--;
80061   }
80062   if( negP2 ){
80063     p1 -= p2;
80064     if( p1<0 ){
80065       p2 += p1;
80066       p1 = 0;
80067     }
80068   }
80069   assert( p1>=0 && p2>=0 );
80070   if( p0type!=SQLITE_BLOB ){
80071     while( *z && p1 ){
80072       SQLITE_SKIP_UTF8(z);
80073       p1--;
80074     }
80075     for(z2=z; *z2 && p2; p2--){
80076       SQLITE_SKIP_UTF8(z2);
80077     }
80078     sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
80079   }else{
80080     if( p1+p2>len ){
80081       p2 = len-p1;
80082       if( p2<0 ) p2 = 0;
80083     }
80084     sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
80085   }
80086 }
80087
80088 /*
80089 ** Implementation of the round() function
80090 */
80091 #ifndef SQLITE_OMIT_FLOATING_POINT
80092 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
80093   int n = 0;
80094   double r;
80095   char *zBuf;
80096   assert( argc==1 || argc==2 );
80097   if( argc==2 ){
80098     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
80099     n = sqlite3_value_int(argv[1]);
80100     if( n>30 ) n = 30;
80101     if( n<0 ) n = 0;
80102   }
80103   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
80104   r = sqlite3_value_double(argv[0]);
80105   /* If Y==0 and X will fit in a 64-bit int,
80106   ** handle the rounding directly,
80107   ** otherwise use printf.
80108   */
80109   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
80110     r = (double)((sqlite_int64)(r+0.5));
80111   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
80112     r = -(double)((sqlite_int64)((-r)+0.5));
80113   }else{
80114     zBuf = sqlite3_mprintf("%.*f",n,r);
80115     if( zBuf==0 ){
80116       sqlite3_result_error_nomem(context);
80117       return;
80118     }
80119     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
80120     sqlite3_free(zBuf);
80121   }
80122   sqlite3_result_double(context, r);
80123 }
80124 #endif
80125
80126 /*
80127 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
80128 ** allocation fails, call sqlite3_result_error_nomem() to notify
80129 ** the database handle that malloc() has failed and return NULL.
80130 ** If nByte is larger than the maximum string or blob length, then
80131 ** raise an SQLITE_TOOBIG exception and return NULL.
80132 */
80133 static void *contextMalloc(sqlite3_context *context, i64 nByte){
80134   char *z;
80135   sqlite3 *db = sqlite3_context_db_handle(context);
80136   assert( nByte>0 );
80137   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
80138   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
80139   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
80140     sqlite3_result_error_toobig(context);
80141     z = 0;
80142   }else{
80143     z = sqlite3Malloc((int)nByte);
80144     if( !z ){
80145       sqlite3_result_error_nomem(context);
80146     }
80147   }
80148   return z;
80149 }
80150
80151 /*
80152 ** Implementation of the upper() and lower() SQL functions.
80153 */
80154 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
80155   char *z1;
80156   const char *z2;
80157   int i, n;
80158   UNUSED_PARAMETER(argc);
80159   z2 = (char*)sqlite3_value_text(argv[0]);
80160   n = sqlite3_value_bytes(argv[0]);
80161   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
80162   assert( z2==(char*)sqlite3_value_text(argv[0]) );
80163   if( z2 ){
80164     z1 = contextMalloc(context, ((i64)n)+1);
80165     if( z1 ){
80166       memcpy(z1, z2, n+1);
80167       for(i=0; z1[i]; i++){
80168         z1[i] = (char)sqlite3Toupper(z1[i]);
80169       }
80170       sqlite3_result_text(context, z1, -1, sqlite3_free);
80171     }
80172   }
80173 }
80174 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
80175   u8 *z1;
80176   const char *z2;
80177   int i, n;
80178   UNUSED_PARAMETER(argc);
80179   z2 = (char*)sqlite3_value_text(argv[0]);
80180   n = sqlite3_value_bytes(argv[0]);
80181   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
80182   assert( z2==(char*)sqlite3_value_text(argv[0]) );
80183   if( z2 ){
80184     z1 = contextMalloc(context, ((i64)n)+1);
80185     if( z1 ){
80186       memcpy(z1, z2, n+1);
80187       for(i=0; z1[i]; i++){
80188         z1[i] = sqlite3Tolower(z1[i]);
80189       }
80190       sqlite3_result_text(context, (char *)z1, -1, sqlite3_free);
80191     }
80192   }
80193 }
80194
80195
80196 #if 0  /* This function is never used. */
80197 /*
80198 ** The COALESCE() and IFNULL() functions used to be implemented as shown
80199 ** here.  But now they are implemented as VDBE code so that unused arguments
80200 ** do not have to be computed.  This legacy implementation is retained as
80201 ** comment.
80202 */
80203 /*
80204 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
80205 ** All three do the same thing.  They return the first non-NULL
80206 ** argument.
80207 */
80208 static void ifnullFunc(
80209   sqlite3_context *context,
80210   int argc,
80211   sqlite3_value **argv
80212 ){
80213   int i;
80214   for(i=0; i<argc; i++){
80215     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
80216       sqlite3_result_value(context, argv[i]);
80217       break;
80218     }
80219   }
80220 }
80221 #endif /* NOT USED */
80222 #define ifnullFunc versionFunc   /* Substitute function - never called */
80223
80224 /*
80225 ** Implementation of random().  Return a random integer.  
80226 */
80227 static void randomFunc(
80228   sqlite3_context *context,
80229   int NotUsed,
80230   sqlite3_value **NotUsed2
80231 ){
80232   sqlite_int64 r;
80233   UNUSED_PARAMETER2(NotUsed, NotUsed2);
80234   sqlite3_randomness(sizeof(r), &r);
80235   if( r<0 ){
80236     /* We need to prevent a random number of 0x8000000000000000 
80237     ** (or -9223372036854775808) since when you do abs() of that
80238     ** number of you get the same value back again.  To do this
80239     ** in a way that is testable, mask the sign bit off of negative
80240     ** values, resulting in a positive value.  Then take the 
80241     ** 2s complement of that positive value.  The end result can
80242     ** therefore be no less than -9223372036854775807.
80243     */
80244     r = -(r ^ (((sqlite3_int64)1)<<63));
80245   }
80246   sqlite3_result_int64(context, r);
80247 }
80248
80249 /*
80250 ** Implementation of randomblob(N).  Return a random blob
80251 ** that is N bytes long.
80252 */
80253 static void randomBlob(
80254   sqlite3_context *context,
80255   int argc,
80256   sqlite3_value **argv
80257 ){
80258   int n;
80259   unsigned char *p;
80260   assert( argc==1 );
80261   UNUSED_PARAMETER(argc);
80262   n = sqlite3_value_int(argv[0]);
80263   if( n<1 ){
80264     n = 1;
80265   }
80266   p = contextMalloc(context, n);
80267   if( p ){
80268     sqlite3_randomness(n, p);
80269     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
80270   }
80271 }
80272
80273 /*
80274 ** Implementation of the last_insert_rowid() SQL function.  The return
80275 ** value is the same as the sqlite3_last_insert_rowid() API function.
80276 */
80277 static void last_insert_rowid(
80278   sqlite3_context *context, 
80279   int NotUsed, 
80280   sqlite3_value **NotUsed2
80281 ){
80282   sqlite3 *db = sqlite3_context_db_handle(context);
80283   UNUSED_PARAMETER2(NotUsed, NotUsed2);
80284   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
80285   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
80286   ** function. */
80287   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
80288 }
80289
80290 /*
80291 ** Implementation of the changes() SQL function.
80292 **
80293 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
80294 ** around the sqlite3_changes() C/C++ function and hence follows the same
80295 ** rules for counting changes.
80296 */
80297 static void changes(
80298   sqlite3_context *context,
80299   int NotUsed,
80300   sqlite3_value **NotUsed2
80301 ){
80302   sqlite3 *db = sqlite3_context_db_handle(context);
80303   UNUSED_PARAMETER2(NotUsed, NotUsed2);
80304   sqlite3_result_int(context, sqlite3_changes(db));
80305 }
80306
80307 /*
80308 ** Implementation of the total_changes() SQL function.  The return value is
80309 ** the same as the sqlite3_total_changes() API function.
80310 */
80311 static void total_changes(
80312   sqlite3_context *context,
80313   int NotUsed,
80314   sqlite3_value **NotUsed2
80315 ){
80316   sqlite3 *db = sqlite3_context_db_handle(context);
80317   UNUSED_PARAMETER2(NotUsed, NotUsed2);
80318   /* IMP: R-52756-41993 This function is a wrapper around the
80319   ** sqlite3_total_changes() C/C++ interface. */
80320   sqlite3_result_int(context, sqlite3_total_changes(db));
80321 }
80322
80323 /*
80324 ** A structure defining how to do GLOB-style comparisons.
80325 */
80326 struct compareInfo {
80327   u8 matchAll;
80328   u8 matchOne;
80329   u8 matchSet;
80330   u8 noCase;
80331 };
80332
80333 /*
80334 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
80335 ** character is exactly one byte in size.  Also, all characters are
80336 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
80337 ** whereas only characters less than 0x80 do in ASCII.
80338 */
80339 #if defined(SQLITE_EBCDIC)
80340 # define sqlite3Utf8Read(A,C)    (*(A++))
80341 # define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
80342 #else
80343 # define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
80344 #endif
80345
80346 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
80347 /* The correct SQL-92 behavior is for the LIKE operator to ignore
80348 ** case.  Thus  'a' LIKE 'A' would be true. */
80349 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
80350 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
80351 ** is case sensitive causing 'a' LIKE 'A' to be false */
80352 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
80353
80354 /*
80355 ** Compare two UTF-8 strings for equality where the first string can
80356 ** potentially be a "glob" expression.  Return true (1) if they
80357 ** are the same and false (0) if they are different.
80358 **
80359 ** Globbing rules:
80360 **
80361 **      '*'       Matches any sequence of zero or more characters.
80362 **
80363 **      '?'       Matches exactly one character.
80364 **
80365 **     [...]      Matches one character from the enclosed list of
80366 **                characters.
80367 **
80368 **     [^...]     Matches one character not in the enclosed list.
80369 **
80370 ** With the [...] and [^...] matching, a ']' character can be included
80371 ** in the list by making it the first character after '[' or '^'.  A
80372 ** range of characters can be specified using '-'.  Example:
80373 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
80374 ** it the last character in the list.
80375 **
80376 ** This routine is usually quick, but can be N**2 in the worst case.
80377 **
80378 ** Hints: to match '*' or '?', put them in "[]".  Like this:
80379 **
80380 **         abc[*]xyz        Matches "abc*xyz" only
80381 */
80382 static int patternCompare(
80383   const u8 *zPattern,              /* The glob pattern */
80384   const u8 *zString,               /* The string to compare against the glob */
80385   const struct compareInfo *pInfo, /* Information about how to do the compare */
80386   const int esc                    /* The escape character */
80387 ){
80388   int c, c2;
80389   int invert;
80390   int seen;
80391   u8 matchOne = pInfo->matchOne;
80392   u8 matchAll = pInfo->matchAll;
80393   u8 matchSet = pInfo->matchSet;
80394   u8 noCase = pInfo->noCase; 
80395   int prevEscape = 0;     /* True if the previous character was 'escape' */
80396
80397   while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
80398     if( !prevEscape && c==matchAll ){
80399       while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
80400                || c == matchOne ){
80401         if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
80402           return 0;
80403         }
80404       }
80405       if( c==0 ){
80406         return 1;
80407       }else if( c==esc ){
80408         c = sqlite3Utf8Read(zPattern, &zPattern);
80409         if( c==0 ){
80410           return 0;
80411         }
80412       }else if( c==matchSet ){
80413         assert( esc==0 );         /* This is GLOB, not LIKE */
80414         assert( matchSet<0x80 );  /* '[' is a single-byte character */
80415         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
80416           SQLITE_SKIP_UTF8(zString);
80417         }
80418         return *zString!=0;
80419       }
80420       while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
80421         if( noCase ){
80422           GlogUpperToLower(c2);
80423           GlogUpperToLower(c);
80424           while( c2 != 0 && c2 != c ){
80425             c2 = sqlite3Utf8Read(zString, &zString);
80426             GlogUpperToLower(c2);
80427           }
80428         }else{
80429           while( c2 != 0 && c2 != c ){
80430             c2 = sqlite3Utf8Read(zString, &zString);
80431           }
80432         }
80433         if( c2==0 ) return 0;
80434         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
80435       }
80436       return 0;
80437     }else if( !prevEscape && c==matchOne ){
80438       if( sqlite3Utf8Read(zString, &zString)==0 ){
80439         return 0;
80440       }
80441     }else if( c==matchSet ){
80442       int prior_c = 0;
80443       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
80444       seen = 0;
80445       invert = 0;
80446       c = sqlite3Utf8Read(zString, &zString);
80447       if( c==0 ) return 0;
80448       c2 = sqlite3Utf8Read(zPattern, &zPattern);
80449       if( c2=='^' ){
80450         invert = 1;
80451         c2 = sqlite3Utf8Read(zPattern, &zPattern);
80452       }
80453       if( c2==']' ){
80454         if( c==']' ) seen = 1;
80455         c2 = sqlite3Utf8Read(zPattern, &zPattern);
80456       }
80457       while( c2 && c2!=']' ){
80458         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
80459           c2 = sqlite3Utf8Read(zPattern, &zPattern);
80460           if( c>=prior_c && c<=c2 ) seen = 1;
80461           prior_c = 0;
80462         }else{
80463           if( c==c2 ){
80464             seen = 1;
80465           }
80466           prior_c = c2;
80467         }
80468         c2 = sqlite3Utf8Read(zPattern, &zPattern);
80469       }
80470       if( c2==0 || (seen ^ invert)==0 ){
80471         return 0;
80472       }
80473     }else if( esc==c && !prevEscape ){
80474       prevEscape = 1;
80475     }else{
80476       c2 = sqlite3Utf8Read(zString, &zString);
80477       if( noCase ){
80478         GlogUpperToLower(c);
80479         GlogUpperToLower(c2);
80480       }
80481       if( c!=c2 ){
80482         return 0;
80483       }
80484       prevEscape = 0;
80485     }
80486   }
80487   return *zString==0;
80488 }
80489
80490 /*
80491 ** Count the number of times that the LIKE operator (or GLOB which is
80492 ** just a variation of LIKE) gets called.  This is used for testing
80493 ** only.
80494 */
80495 #ifdef SQLITE_TEST
80496 SQLITE_API int sqlite3_like_count = 0;
80497 #endif
80498
80499
80500 /*
80501 ** Implementation of the like() SQL function.  This function implements
80502 ** the build-in LIKE operator.  The first argument to the function is the
80503 ** pattern and the second argument is the string.  So, the SQL statements:
80504 **
80505 **       A LIKE B
80506 **
80507 ** is implemented as like(B,A).
80508 **
80509 ** This same function (with a different compareInfo structure) computes
80510 ** the GLOB operator.
80511 */
80512 static void likeFunc(
80513   sqlite3_context *context, 
80514   int argc, 
80515   sqlite3_value **argv
80516 ){
80517   const unsigned char *zA, *zB;
80518   int escape = 0;
80519   int nPat;
80520   sqlite3 *db = sqlite3_context_db_handle(context);
80521
80522   zB = sqlite3_value_text(argv[0]);
80523   zA = sqlite3_value_text(argv[1]);
80524
80525   /* Limit the length of the LIKE or GLOB pattern to avoid problems
80526   ** of deep recursion and N*N behavior in patternCompare().
80527   */
80528   nPat = sqlite3_value_bytes(argv[0]);
80529   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
80530   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
80531   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
80532     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
80533     return;
80534   }
80535   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
80536
80537   if( argc==3 ){
80538     /* The escape character string must consist of a single UTF-8 character.
80539     ** Otherwise, return an error.
80540     */
80541     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
80542     if( zEsc==0 ) return;
80543     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
80544       sqlite3_result_error(context, 
80545           "ESCAPE expression must be a single character", -1);
80546       return;
80547     }
80548     escape = sqlite3Utf8Read(zEsc, &zEsc);
80549   }
80550   if( zA && zB ){
80551     struct compareInfo *pInfo = sqlite3_user_data(context);
80552 #ifdef SQLITE_TEST
80553     sqlite3_like_count++;
80554 #endif
80555     
80556     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
80557   }
80558 }
80559
80560 /*
80561 ** Implementation of the NULLIF(x,y) function.  The result is the first
80562 ** argument if the arguments are different.  The result is NULL if the
80563 ** arguments are equal to each other.
80564 */
80565 static void nullifFunc(
80566   sqlite3_context *context,
80567   int NotUsed,
80568   sqlite3_value **argv
80569 ){
80570   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
80571   UNUSED_PARAMETER(NotUsed);
80572   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
80573     sqlite3_result_value(context, argv[0]);
80574   }
80575 }
80576
80577 /*
80578 ** Implementation of the sqlite_version() function.  The result is the version
80579 ** of the SQLite library that is running.
80580 */
80581 static void versionFunc(
80582   sqlite3_context *context,
80583   int NotUsed,
80584   sqlite3_value **NotUsed2
80585 ){
80586   UNUSED_PARAMETER2(NotUsed, NotUsed2);
80587   /* IMP: R-48699-48617 This function is an SQL wrapper around the
80588   ** sqlite3_libversion() C-interface. */
80589   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
80590 }
80591
80592 /*
80593 ** Implementation of the sqlite_source_id() function. The result is a string
80594 ** that identifies the particular version of the source code used to build
80595 ** SQLite.
80596 */
80597 static void sourceidFunc(
80598   sqlite3_context *context,
80599   int NotUsed,
80600   sqlite3_value **NotUsed2
80601 ){
80602   UNUSED_PARAMETER2(NotUsed, NotUsed2);
80603   /* IMP: R-24470-31136 This function is an SQL wrapper around the
80604   ** sqlite3_sourceid() C interface. */
80605   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
80606 }
80607
80608 /*
80609 ** Implementation of the sqlite_compileoption_used() function.
80610 ** The result is an integer that identifies if the compiler option
80611 ** was used to build SQLite.
80612 */
80613 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
80614 static void compileoptionusedFunc(
80615   sqlite3_context *context,
80616   int argc,
80617   sqlite3_value **argv
80618 ){
80619   const char *zOptName;
80620   assert( argc==1 );
80621   UNUSED_PARAMETER(argc);
80622   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
80623   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
80624   ** function.
80625   */
80626   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
80627     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
80628   }
80629 }
80630 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
80631
80632 /*
80633 ** Implementation of the sqlite_compileoption_get() function. 
80634 ** The result is a string that identifies the compiler options 
80635 ** used to build SQLite.
80636 */
80637 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
80638 static void compileoptiongetFunc(
80639   sqlite3_context *context,
80640   int argc,
80641   sqlite3_value **argv
80642 ){
80643   int n;
80644   assert( argc==1 );
80645   UNUSED_PARAMETER(argc);
80646   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
80647   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
80648   */
80649   n = sqlite3_value_int(argv[0]);
80650   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
80651 }
80652 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
80653
80654 /* Array for converting from half-bytes (nybbles) into ASCII hex
80655 ** digits. */
80656 static const char hexdigits[] = {
80657   '0', '1', '2', '3', '4', '5', '6', '7',
80658   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
80659 };
80660
80661 /*
80662 ** EXPERIMENTAL - This is not an official function.  The interface may
80663 ** change.  This function may disappear.  Do not write code that depends
80664 ** on this function.
80665 **
80666 ** Implementation of the QUOTE() function.  This function takes a single
80667 ** argument.  If the argument is numeric, the return value is the same as
80668 ** the argument.  If the argument is NULL, the return value is the string
80669 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
80670 ** single-quote escapes.
80671 */
80672 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
80673   assert( argc==1 );
80674   UNUSED_PARAMETER(argc);
80675   switch( sqlite3_value_type(argv[0]) ){
80676     case SQLITE_INTEGER:
80677     case SQLITE_FLOAT: {
80678       sqlite3_result_value(context, argv[0]);
80679       break;
80680     }
80681     case SQLITE_BLOB: {
80682       char *zText = 0;
80683       char const *zBlob = sqlite3_value_blob(argv[0]);
80684       int nBlob = sqlite3_value_bytes(argv[0]);
80685       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
80686       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
80687       if( zText ){
80688         int i;
80689         for(i=0; i<nBlob; i++){
80690           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
80691           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
80692         }
80693         zText[(nBlob*2)+2] = '\'';
80694         zText[(nBlob*2)+3] = '\0';
80695         zText[0] = 'X';
80696         zText[1] = '\'';
80697         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
80698         sqlite3_free(zText);
80699       }
80700       break;
80701     }
80702     case SQLITE_TEXT: {
80703       int i,j;
80704       u64 n;
80705       const unsigned char *zArg = sqlite3_value_text(argv[0]);
80706       char *z;
80707
80708       if( zArg==0 ) return;
80709       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
80710       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
80711       if( z ){
80712         z[0] = '\'';
80713         for(i=0, j=1; zArg[i]; i++){
80714           z[j++] = zArg[i];
80715           if( zArg[i]=='\'' ){
80716             z[j++] = '\'';
80717           }
80718         }
80719         z[j++] = '\'';
80720         z[j] = 0;
80721         sqlite3_result_text(context, z, j, sqlite3_free);
80722       }
80723       break;
80724     }
80725     default: {
80726       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
80727       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
80728       break;
80729     }
80730   }
80731 }
80732
80733 /*
80734 ** The hex() function.  Interpret the argument as a blob.  Return
80735 ** a hexadecimal rendering as text.
80736 */
80737 static void hexFunc(
80738   sqlite3_context *context,
80739   int argc,
80740   sqlite3_value **argv
80741 ){
80742   int i, n;
80743   const unsigned char *pBlob;
80744   char *zHex, *z;
80745   assert( argc==1 );
80746   UNUSED_PARAMETER(argc);
80747   pBlob = sqlite3_value_blob(argv[0]);
80748   n = sqlite3_value_bytes(argv[0]);
80749   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
80750   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
80751   if( zHex ){
80752     for(i=0; i<n; i++, pBlob++){
80753       unsigned char c = *pBlob;
80754       *(z++) = hexdigits[(c>>4)&0xf];
80755       *(z++) = hexdigits[c&0xf];
80756     }
80757     *z = 0;
80758     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
80759   }
80760 }
80761
80762 /*
80763 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
80764 */
80765 static void zeroblobFunc(
80766   sqlite3_context *context,
80767   int argc,
80768   sqlite3_value **argv
80769 ){
80770   i64 n;
80771   sqlite3 *db = sqlite3_context_db_handle(context);
80772   assert( argc==1 );
80773   UNUSED_PARAMETER(argc);
80774   n = sqlite3_value_int64(argv[0]);
80775   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
80776   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
80777   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
80778     sqlite3_result_error_toobig(context);
80779   }else{
80780     sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
80781   }
80782 }
80783
80784 /*
80785 ** The replace() function.  Three arguments are all strings: call
80786 ** them A, B, and C. The result is also a string which is derived
80787 ** from A by replacing every occurance of B with C.  The match
80788 ** must be exact.  Collating sequences are not used.
80789 */
80790 static void replaceFunc(
80791   sqlite3_context *context,
80792   int argc,
80793   sqlite3_value **argv
80794 ){
80795   const unsigned char *zStr;        /* The input string A */
80796   const unsigned char *zPattern;    /* The pattern string B */
80797   const unsigned char *zRep;        /* The replacement string C */
80798   unsigned char *zOut;              /* The output */
80799   int nStr;                /* Size of zStr */
80800   int nPattern;            /* Size of zPattern */
80801   int nRep;                /* Size of zRep */
80802   i64 nOut;                /* Maximum size of zOut */
80803   int loopLimit;           /* Last zStr[] that might match zPattern[] */
80804   int i, j;                /* Loop counters */
80805
80806   assert( argc==3 );
80807   UNUSED_PARAMETER(argc);
80808   zStr = sqlite3_value_text(argv[0]);
80809   if( zStr==0 ) return;
80810   nStr = sqlite3_value_bytes(argv[0]);
80811   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
80812   zPattern = sqlite3_value_text(argv[1]);
80813   if( zPattern==0 ){
80814     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
80815             || sqlite3_context_db_handle(context)->mallocFailed );
80816     return;
80817   }
80818   if( zPattern[0]==0 ){
80819     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
80820     sqlite3_result_value(context, argv[0]);
80821     return;
80822   }
80823   nPattern = sqlite3_value_bytes(argv[1]);
80824   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
80825   zRep = sqlite3_value_text(argv[2]);
80826   if( zRep==0 ) return;
80827   nRep = sqlite3_value_bytes(argv[2]);
80828   assert( zRep==sqlite3_value_text(argv[2]) );
80829   nOut = nStr + 1;
80830   assert( nOut<SQLITE_MAX_LENGTH );
80831   zOut = contextMalloc(context, (i64)nOut);
80832   if( zOut==0 ){
80833     return;
80834   }
80835   loopLimit = nStr - nPattern;  
80836   for(i=j=0; i<=loopLimit; i++){
80837     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
80838       zOut[j++] = zStr[i];
80839     }else{
80840       u8 *zOld;
80841       sqlite3 *db = sqlite3_context_db_handle(context);
80842       nOut += nRep - nPattern;
80843       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
80844       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
80845       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
80846         sqlite3_result_error_toobig(context);
80847         sqlite3_free(zOut);
80848         return;
80849       }
80850       zOld = zOut;
80851       zOut = sqlite3_realloc(zOut, (int)nOut);
80852       if( zOut==0 ){
80853         sqlite3_result_error_nomem(context);
80854         sqlite3_free(zOld);
80855         return;
80856       }
80857       memcpy(&zOut[j], zRep, nRep);
80858       j += nRep;
80859       i += nPattern-1;
80860     }
80861   }
80862   assert( j+nStr-i+1==nOut );
80863   memcpy(&zOut[j], &zStr[i], nStr-i);
80864   j += nStr - i;
80865   assert( j<=nOut );
80866   zOut[j] = 0;
80867   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
80868 }
80869
80870 /*
80871 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
80872 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
80873 */
80874 static void trimFunc(
80875   sqlite3_context *context,
80876   int argc,
80877   sqlite3_value **argv
80878 ){
80879   const unsigned char *zIn;         /* Input string */
80880   const unsigned char *zCharSet;    /* Set of characters to trim */
80881   int nIn;                          /* Number of bytes in input */
80882   int flags;                        /* 1: trimleft  2: trimright  3: trim */
80883   int i;                            /* Loop counter */
80884   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
80885   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
80886   int nChar;                        /* Number of characters in zCharSet */
80887
80888   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
80889     return;
80890   }
80891   zIn = sqlite3_value_text(argv[0]);
80892   if( zIn==0 ) return;
80893   nIn = sqlite3_value_bytes(argv[0]);
80894   assert( zIn==sqlite3_value_text(argv[0]) );
80895   if( argc==1 ){
80896     static const unsigned char lenOne[] = { 1 };
80897     static unsigned char * const azOne[] = { (u8*)" " };
80898     nChar = 1;
80899     aLen = (u8*)lenOne;
80900     azChar = (unsigned char **)azOne;
80901     zCharSet = 0;
80902   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
80903     return;
80904   }else{
80905     const unsigned char *z;
80906     for(z=zCharSet, nChar=0; *z; nChar++){
80907       SQLITE_SKIP_UTF8(z);
80908     }
80909     if( nChar>0 ){
80910       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
80911       if( azChar==0 ){
80912         return;
80913       }
80914       aLen = (unsigned char*)&azChar[nChar];
80915       for(z=zCharSet, nChar=0; *z; nChar++){
80916         azChar[nChar] = (unsigned char *)z;
80917         SQLITE_SKIP_UTF8(z);
80918         aLen[nChar] = (u8)(z - azChar[nChar]);
80919       }
80920     }
80921   }
80922   if( nChar>0 ){
80923     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
80924     if( flags & 1 ){
80925       while( nIn>0 ){
80926         int len = 0;
80927         for(i=0; i<nChar; i++){
80928           len = aLen[i];
80929           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
80930         }
80931         if( i>=nChar ) break;
80932         zIn += len;
80933         nIn -= len;
80934       }
80935     }
80936     if( flags & 2 ){
80937       while( nIn>0 ){
80938         int len = 0;
80939         for(i=0; i<nChar; i++){
80940           len = aLen[i];
80941           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
80942         }
80943         if( i>=nChar ) break;
80944         nIn -= len;
80945       }
80946     }
80947     if( zCharSet ){
80948       sqlite3_free(azChar);
80949     }
80950   }
80951   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
80952 }
80953
80954
80955 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
80956 ** is only available if the SQLITE_SOUNDEX compile-time option is used
80957 ** when SQLite is built.
80958 */
80959 #ifdef SQLITE_SOUNDEX
80960 /*
80961 ** Compute the soundex encoding of a word.
80962 **
80963 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
80964 ** soundex encoding of the string X. 
80965 */
80966 static void soundexFunc(
80967   sqlite3_context *context,
80968   int argc,
80969   sqlite3_value **argv
80970 ){
80971   char zResult[8];
80972   const u8 *zIn;
80973   int i, j;
80974   static const unsigned char iCode[] = {
80975     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
80976     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
80977     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
80978     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
80979     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
80980     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
80981     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
80982     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
80983   };
80984   assert( argc==1 );
80985   zIn = (u8*)sqlite3_value_text(argv[0]);
80986   if( zIn==0 ) zIn = (u8*)"";
80987   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
80988   if( zIn[i] ){
80989     u8 prevcode = iCode[zIn[i]&0x7f];
80990     zResult[0] = sqlite3Toupper(zIn[i]);
80991     for(j=1; j<4 && zIn[i]; i++){
80992       int code = iCode[zIn[i]&0x7f];
80993       if( code>0 ){
80994         if( code!=prevcode ){
80995           prevcode = code;
80996           zResult[j++] = code + '0';
80997         }
80998       }else{
80999         prevcode = 0;
81000       }
81001     }
81002     while( j<4 ){
81003       zResult[j++] = '0';
81004     }
81005     zResult[j] = 0;
81006     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
81007   }else{
81008     /* IMP: R-64894-50321 The string "?000" is returned if the argument
81009     ** is NULL or contains no ASCII alphabetic characters. */
81010     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
81011   }
81012 }
81013 #endif /* SQLITE_SOUNDEX */
81014
81015 #ifndef SQLITE_OMIT_LOAD_EXTENSION
81016 /*
81017 ** A function that loads a shared-library extension then returns NULL.
81018 */
81019 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
81020   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
81021   const char *zProc;
81022   sqlite3 *db = sqlite3_context_db_handle(context);
81023   char *zErrMsg = 0;
81024
81025   if( argc==2 ){
81026     zProc = (const char *)sqlite3_value_text(argv[1]);
81027   }else{
81028     zProc = 0;
81029   }
81030   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
81031     sqlite3_result_error(context, zErrMsg, -1);
81032     sqlite3_free(zErrMsg);
81033   }
81034 }
81035 #endif
81036
81037
81038 /*
81039 ** An instance of the following structure holds the context of a
81040 ** sum() or avg() aggregate computation.
81041 */
81042 typedef struct SumCtx SumCtx;
81043 struct SumCtx {
81044   double rSum;      /* Floating point sum */
81045   i64 iSum;         /* Integer sum */   
81046   i64 cnt;          /* Number of elements summed */
81047   u8 overflow;      /* True if integer overflow seen */
81048   u8 approx;        /* True if non-integer value was input to the sum */
81049 };
81050
81051 /*
81052 ** Routines used to compute the sum, average, and total.
81053 **
81054 ** The SUM() function follows the (broken) SQL standard which means
81055 ** that it returns NULL if it sums over no inputs.  TOTAL returns
81056 ** 0.0 in that case.  In addition, TOTAL always returns a float where
81057 ** SUM might return an integer if it never encounters a floating point
81058 ** value.  TOTAL never fails, but SUM might through an exception if
81059 ** it overflows an integer.
81060 */
81061 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
81062   SumCtx *p;
81063   int type;
81064   assert( argc==1 );
81065   UNUSED_PARAMETER(argc);
81066   p = sqlite3_aggregate_context(context, sizeof(*p));
81067   type = sqlite3_value_numeric_type(argv[0]);
81068   if( p && type!=SQLITE_NULL ){
81069     p->cnt++;
81070     if( type==SQLITE_INTEGER ){
81071       i64 v = sqlite3_value_int64(argv[0]);
81072       p->rSum += v;
81073       if( (p->approx|p->overflow)==0 ){
81074         i64 iNewSum = p->iSum + v;
81075         int s1 = (int)(p->iSum >> (sizeof(i64)*8-1));
81076         int s2 = (int)(v       >> (sizeof(i64)*8-1));
81077         int s3 = (int)(iNewSum >> (sizeof(i64)*8-1));
81078         p->overflow = ((s1&s2&~s3) | (~s1&~s2&s3))?1:0;
81079         p->iSum = iNewSum;
81080       }
81081     }else{
81082       p->rSum += sqlite3_value_double(argv[0]);
81083       p->approx = 1;
81084     }
81085   }
81086 }
81087 static void sumFinalize(sqlite3_context *context){
81088   SumCtx *p;
81089   p = sqlite3_aggregate_context(context, 0);
81090   if( p && p->cnt>0 ){
81091     if( p->overflow ){
81092       sqlite3_result_error(context,"integer overflow",-1);
81093     }else if( p->approx ){
81094       sqlite3_result_double(context, p->rSum);
81095     }else{
81096       sqlite3_result_int64(context, p->iSum);
81097     }
81098   }
81099 }
81100 static void avgFinalize(sqlite3_context *context){
81101   SumCtx *p;
81102   p = sqlite3_aggregate_context(context, 0);
81103   if( p && p->cnt>0 ){
81104     sqlite3_result_double(context, p->rSum/(double)p->cnt);
81105   }
81106 }
81107 static void totalFinalize(sqlite3_context *context){
81108   SumCtx *p;
81109   p = sqlite3_aggregate_context(context, 0);
81110   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
81111   sqlite3_result_double(context, p ? p->rSum : (double)0);
81112 }
81113
81114 /*
81115 ** The following structure keeps track of state information for the
81116 ** count() aggregate function.
81117 */
81118 typedef struct CountCtx CountCtx;
81119 struct CountCtx {
81120   i64 n;
81121 };
81122
81123 /*
81124 ** Routines to implement the count() aggregate function.
81125 */
81126 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
81127   CountCtx *p;
81128   p = sqlite3_aggregate_context(context, sizeof(*p));
81129   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
81130     p->n++;
81131   }
81132
81133 #ifndef SQLITE_OMIT_DEPRECATED
81134   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
81135   ** sure it still operates correctly, verify that its count agrees with our 
81136   ** internal count when using count(*) and when the total count can be
81137   ** expressed as a 32-bit integer. */
81138   assert( argc==1 || p==0 || p->n>0x7fffffff
81139           || p->n==sqlite3_aggregate_count(context) );
81140 #endif
81141 }   
81142 static void countFinalize(sqlite3_context *context){
81143   CountCtx *p;
81144   p = sqlite3_aggregate_context(context, 0);
81145   sqlite3_result_int64(context, p ? p->n : 0);
81146 }
81147
81148 /*
81149 ** Routines to implement min() and max() aggregate functions.
81150 */
81151 static void minmaxStep(
81152   sqlite3_context *context, 
81153   int NotUsed, 
81154   sqlite3_value **argv
81155 ){
81156   Mem *pArg  = (Mem *)argv[0];
81157   Mem *pBest;
81158   UNUSED_PARAMETER(NotUsed);
81159
81160   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
81161   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
81162   if( !pBest ) return;
81163
81164   if( pBest->flags ){
81165     int max;
81166     int cmp;
81167     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
81168     /* This step function is used for both the min() and max() aggregates,
81169     ** the only difference between the two being that the sense of the
81170     ** comparison is inverted. For the max() aggregate, the
81171     ** sqlite3_user_data() function returns (void *)-1. For min() it
81172     ** returns (void *)db, where db is the sqlite3* database pointer.
81173     ** Therefore the next statement sets variable 'max' to 1 for the max()
81174     ** aggregate, or 0 for min().
81175     */
81176     max = sqlite3_user_data(context)!=0;
81177     cmp = sqlite3MemCompare(pBest, pArg, pColl);
81178     if( (max && cmp<0) || (!max && cmp>0) ){
81179       sqlite3VdbeMemCopy(pBest, pArg);
81180     }
81181   }else{
81182     sqlite3VdbeMemCopy(pBest, pArg);
81183   }
81184 }
81185 static void minMaxFinalize(sqlite3_context *context){
81186   sqlite3_value *pRes;
81187   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
81188   if( pRes ){
81189     if( ALWAYS(pRes->flags) ){
81190       sqlite3_result_value(context, pRes);
81191     }
81192     sqlite3VdbeMemRelease(pRes);
81193   }
81194 }
81195
81196 /*
81197 ** group_concat(EXPR, ?SEPARATOR?)
81198 */
81199 static void groupConcatStep(
81200   sqlite3_context *context,
81201   int argc,
81202   sqlite3_value **argv
81203 ){
81204   const char *zVal;
81205   StrAccum *pAccum;
81206   const char *zSep;
81207   int nVal, nSep;
81208   assert( argc==1 || argc==2 );
81209   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
81210   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
81211
81212   if( pAccum ){
81213     sqlite3 *db = sqlite3_context_db_handle(context);
81214     int firstTerm = pAccum->useMalloc==0;
81215     pAccum->useMalloc = 2;
81216     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
81217     if( !firstTerm ){
81218       if( argc==2 ){
81219         zSep = (char*)sqlite3_value_text(argv[1]);
81220         nSep = sqlite3_value_bytes(argv[1]);
81221       }else{
81222         zSep = ",";
81223         nSep = 1;
81224       }
81225       sqlite3StrAccumAppend(pAccum, zSep, nSep);
81226     }
81227     zVal = (char*)sqlite3_value_text(argv[0]);
81228     nVal = sqlite3_value_bytes(argv[0]);
81229     sqlite3StrAccumAppend(pAccum, zVal, nVal);
81230   }
81231 }
81232 static void groupConcatFinalize(sqlite3_context *context){
81233   StrAccum *pAccum;
81234   pAccum = sqlite3_aggregate_context(context, 0);
81235   if( pAccum ){
81236     if( pAccum->tooBig ){
81237       sqlite3_result_error_toobig(context);
81238     }else if( pAccum->mallocFailed ){
81239       sqlite3_result_error_nomem(context);
81240     }else{    
81241       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
81242                           sqlite3_free);
81243     }
81244   }
81245 }
81246
81247 /*
81248 ** This routine does per-connection function registration.  Most
81249 ** of the built-in functions above are part of the global function set.
81250 ** This routine only deals with those that are not global.
81251 */
81252 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
81253   int rc = sqlite3_overload_function(db, "MATCH", 2);
81254   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
81255   if( rc==SQLITE_NOMEM ){
81256     db->mallocFailed = 1;
81257   }
81258 }
81259
81260 /*
81261 ** Set the LIKEOPT flag on the 2-argument function with the given name.
81262 */
81263 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
81264   FuncDef *pDef;
81265   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
81266                              2, SQLITE_UTF8, 0);
81267   if( ALWAYS(pDef) ){
81268     pDef->flags = flagVal;
81269   }
81270 }
81271
81272 /*
81273 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
81274 ** parameter determines whether or not the LIKE operator is case
81275 ** sensitive.  GLOB is always case sensitive.
81276 */
81277 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
81278   struct compareInfo *pInfo;
81279   if( caseSensitive ){
81280     pInfo = (struct compareInfo*)&likeInfoAlt;
81281   }else{
81282     pInfo = (struct compareInfo*)&likeInfoNorm;
81283   }
81284   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
81285   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
81286   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, 
81287       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
81288   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
81289   setLikeOptFlag(db, "like", 
81290       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
81291 }
81292
81293 /*
81294 ** pExpr points to an expression which implements a function.  If
81295 ** it is appropriate to apply the LIKE optimization to that function
81296 ** then set aWc[0] through aWc[2] to the wildcard characters and
81297 ** return TRUE.  If the function is not a LIKE-style function then
81298 ** return FALSE.
81299 */
81300 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
81301   FuncDef *pDef;
81302   if( pExpr->op!=TK_FUNCTION 
81303    || !pExpr->x.pList 
81304    || pExpr->x.pList->nExpr!=2
81305   ){
81306     return 0;
81307   }
81308   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
81309   pDef = sqlite3FindFunction(db, pExpr->u.zToken, 
81310                              sqlite3Strlen30(pExpr->u.zToken),
81311                              2, SQLITE_UTF8, 0);
81312   if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
81313     return 0;
81314   }
81315
81316   /* The memcpy() statement assumes that the wildcard characters are
81317   ** the first three statements in the compareInfo structure.  The
81318   ** asserts() that follow verify that assumption
81319   */
81320   memcpy(aWc, pDef->pUserData, 3);
81321   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
81322   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
81323   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
81324   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
81325   return 1;
81326 }
81327
81328 /*
81329 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
81330 ** to the global function hash table.  This occurs at start-time (as
81331 ** a consequence of calling sqlite3_initialize()).
81332 **
81333 ** After this routine runs
81334 */
81335 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
81336   /*
81337   ** The following array holds FuncDef structures for all of the functions
81338   ** defined in this file.
81339   **
81340   ** The array cannot be constant since changes are made to the
81341   ** FuncDef.pHash elements at start-time.  The elements of this array
81342   ** are read-only after initialization is complete.
81343   */
81344   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
81345     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
81346     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
81347     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
81348     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
81349     FUNCTION(trim,               1, 3, 0, trimFunc         ),
81350     FUNCTION(trim,               2, 3, 0, trimFunc         ),
81351     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
81352     FUNCTION(min,                0, 0, 1, 0                ),
81353     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
81354     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
81355     FUNCTION(max,                0, 1, 1, 0                ),
81356     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
81357     FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
81358     FUNCTION(length,             1, 0, 0, lengthFunc       ),
81359     FUNCTION(substr,             2, 0, 0, substrFunc       ),
81360     FUNCTION(substr,             3, 0, 0, substrFunc       ),
81361     FUNCTION(abs,                1, 0, 0, absFunc          ),
81362 #ifndef SQLITE_OMIT_FLOATING_POINT
81363     FUNCTION(round,              1, 0, 0, roundFunc        ),
81364     FUNCTION(round,              2, 0, 0, roundFunc        ),
81365 #endif
81366     FUNCTION(upper,              1, 0, 0, upperFunc        ),
81367     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
81368     FUNCTION(coalesce,           1, 0, 0, 0                ),
81369     FUNCTION(coalesce,           0, 0, 0, 0                ),
81370 /*  FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ), */
81371     {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0,0},
81372     FUNCTION(hex,                1, 0, 0, hexFunc          ),
81373 /*  FUNCTION(ifnull,             2, 0, 0, ifnullFunc       ), */
81374     {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0,0},
81375     FUNCTION(random,             0, 0, 0, randomFunc       ),
81376     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
81377     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
81378     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
81379     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
81380 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
81381     FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
81382     FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
81383 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
81384     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
81385     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
81386     FUNCTION(changes,            0, 0, 0, changes          ),
81387     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
81388     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
81389     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
81390   #ifdef SQLITE_SOUNDEX
81391     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
81392   #endif
81393   #ifndef SQLITE_OMIT_LOAD_EXTENSION
81394     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
81395     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
81396   #endif
81397     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
81398     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
81399     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
81400  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
81401     {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
81402     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
81403     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
81404     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
81405   
81406     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
81407   #ifdef SQLITE_CASE_SENSITIVE_LIKE
81408     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
81409     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
81410   #else
81411     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
81412     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
81413   #endif
81414   };
81415
81416   int i;
81417   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
81418   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
81419
81420   for(i=0; i<ArraySize(aBuiltinFunc); i++){
81421     sqlite3FuncDefInsert(pHash, &aFunc[i]);
81422   }
81423   sqlite3RegisterDateTimeFunctions();
81424 #ifndef SQLITE_OMIT_ALTERTABLE
81425   sqlite3AlterFunctions();
81426 #endif
81427 }
81428
81429 /************** End of func.c ************************************************/
81430 /************** Begin file fkey.c ********************************************/
81431 /*
81432 **
81433 ** The author disclaims copyright to this source code.  In place of
81434 ** a legal notice, here is a blessing:
81435 **
81436 **    May you do good and not evil.
81437 **    May you find forgiveness for yourself and forgive others.
81438 **    May you share freely, never taking more than you give.
81439 **
81440 *************************************************************************
81441 ** This file contains code used by the compiler to add foreign key
81442 ** support to compiled SQL statements.
81443 */
81444
81445 #ifndef SQLITE_OMIT_FOREIGN_KEY
81446 #ifndef SQLITE_OMIT_TRIGGER
81447
81448 /*
81449 ** Deferred and Immediate FKs
81450 ** --------------------------
81451 **
81452 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
81453 ** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
81454 ** is returned and the current statement transaction rolled back. If a 
81455 ** deferred foreign key constraint is violated, no action is taken 
81456 ** immediately. However if the application attempts to commit the 
81457 ** transaction before fixing the constraint violation, the attempt fails.
81458 **
81459 ** Deferred constraints are implemented using a simple counter associated
81460 ** with the database handle. The counter is set to zero each time a 
81461 ** database transaction is opened. Each time a statement is executed 
81462 ** that causes a foreign key violation, the counter is incremented. Each
81463 ** time a statement is executed that removes an existing violation from
81464 ** the database, the counter is decremented. When the transaction is
81465 ** committed, the commit fails if the current value of the counter is
81466 ** greater than zero. This scheme has two big drawbacks:
81467 **
81468 **   * When a commit fails due to a deferred foreign key constraint, 
81469 **     there is no way to tell which foreign constraint is not satisfied,
81470 **     or which row it is not satisfied for.
81471 **
81472 **   * If the database contains foreign key violations when the 
81473 **     transaction is opened, this may cause the mechanism to malfunction.
81474 **
81475 ** Despite these problems, this approach is adopted as it seems simpler
81476 ** than the alternatives.
81477 **
81478 ** INSERT operations:
81479 **
81480 **   I.1) For each FK for which the table is the child table, search
81481 **        the parent table for a match. If none is found increment the
81482 **        constraint counter.
81483 **
81484 **   I.2) For each FK for which the table is the parent table, 
81485 **        search the child table for rows that correspond to the new
81486 **        row in the parent table. Decrement the counter for each row
81487 **        found (as the constraint is now satisfied).
81488 **
81489 ** DELETE operations:
81490 **
81491 **   D.1) For each FK for which the table is the child table, 
81492 **        search the parent table for a row that corresponds to the 
81493 **        deleted row in the child table. If such a row is not found, 
81494 **        decrement the counter.
81495 **
81496 **   D.2) For each FK for which the table is the parent table, search 
81497 **        the child table for rows that correspond to the deleted row 
81498 **        in the parent table. For each found increment the counter.
81499 **
81500 ** UPDATE operations:
81501 **
81502 **   An UPDATE command requires that all 4 steps above are taken, but only
81503 **   for FK constraints for which the affected columns are actually 
81504 **   modified (values must be compared at runtime).
81505 **
81506 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
81507 ** This simplifies the implementation a bit.
81508 **
81509 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
81510 ** resolution is considered to delete rows before the new row is inserted.
81511 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
81512 ** is thrown, even if the FK constraint would be satisfied after the new 
81513 ** row is inserted.
81514 **
81515 ** Immediate constraints are usually handled similarly. The only difference 
81516 ** is that the counter used is stored as part of each individual statement
81517 ** object (struct Vdbe). If, after the statement has run, its immediate
81518 ** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
81519 ** and the statement transaction is rolled back. An exception is an INSERT
81520 ** statement that inserts a single row only (no triggers). In this case,
81521 ** instead of using a counter, an exception is thrown immediately if the
81522 ** INSERT violates a foreign key constraint. This is necessary as such
81523 ** an INSERT does not open a statement transaction.
81524 **
81525 ** TODO: How should dropping a table be handled? How should renaming a 
81526 ** table be handled?
81527 **
81528 **
81529 ** Query API Notes
81530 ** ---------------
81531 **
81532 ** Before coding an UPDATE or DELETE row operation, the code-generator
81533 ** for those two operations needs to know whether or not the operation
81534 ** requires any FK processing and, if so, which columns of the original
81535 ** row are required by the FK processing VDBE code (i.e. if FKs were
81536 ** implemented using triggers, which of the old.* columns would be 
81537 ** accessed). No information is required by the code-generator before
81538 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
81539 ** generation code to query for this information are:
81540 **
81541 **   sqlite3FkRequired() - Test to see if FK processing is required.
81542 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
81543 **
81544 **
81545 ** Externally accessible module functions
81546 ** --------------------------------------
81547 **
81548 **   sqlite3FkCheck()    - Check for foreign key violations.
81549 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
81550 **   sqlite3FkDelete()   - Delete an FKey structure.
81551 */
81552
81553 /*
81554 ** VDBE Calling Convention
81555 ** -----------------------
81556 **
81557 ** Example:
81558 **
81559 **   For the following INSERT statement:
81560 **
81561 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
81562 **     INSERT INTO t1 VALUES(1, 2, 3.1);
81563 **
81564 **   Register (x):        2    (type integer)
81565 **   Register (x+1):      1    (type integer)
81566 **   Register (x+2):      NULL (type NULL)
81567 **   Register (x+3):      3.1  (type real)
81568 */
81569
81570 /*
81571 ** A foreign key constraint requires that the key columns in the parent
81572 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
81573 ** Given that pParent is the parent table for foreign key constraint pFKey, 
81574 ** search the schema a unique index on the parent key columns. 
81575 **
81576 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY 
81577 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx 
81578 ** is set to point to the unique index. 
81579 ** 
81580 ** If the parent key consists of a single column (the foreign key constraint
81581 ** is not a composite foreign key), output variable *paiCol is set to NULL.
81582 ** Otherwise, it is set to point to an allocated array of size N, where
81583 ** N is the number of columns in the parent key. The first element of the
81584 ** array is the index of the child table column that is mapped by the FK
81585 ** constraint to the parent table column stored in the left-most column
81586 ** of index *ppIdx. The second element of the array is the index of the
81587 ** child table column that corresponds to the second left-most column of
81588 ** *ppIdx, and so on.
81589 **
81590 ** If the required index cannot be found, either because:
81591 **
81592 **   1) The named parent key columns do not exist, or
81593 **
81594 **   2) The named parent key columns do exist, but are not subject to a
81595 **      UNIQUE or PRIMARY KEY constraint, or
81596 **
81597 **   3) No parent key columns were provided explicitly as part of the
81598 **      foreign key definition, and the parent table does not have a
81599 **      PRIMARY KEY, or
81600 **
81601 **   4) No parent key columns were provided explicitly as part of the
81602 **      foreign key definition, and the PRIMARY KEY of the parent table 
81603 **      consists of a a different number of columns to the child key in 
81604 **      the child table.
81605 **
81606 ** then non-zero is returned, and a "foreign key mismatch" error loaded
81607 ** into pParse. If an OOM error occurs, non-zero is returned and the
81608 ** pParse->db->mallocFailed flag is set.
81609 */
81610 static int locateFkeyIndex(
81611   Parse *pParse,                  /* Parse context to store any error in */
81612   Table *pParent,                 /* Parent table of FK constraint pFKey */
81613   FKey *pFKey,                    /* Foreign key to find index for */
81614   Index **ppIdx,                  /* OUT: Unique index on parent table */
81615   int **paiCol                    /* OUT: Map of index columns in pFKey */
81616 ){
81617   Index *pIdx = 0;                    /* Value to return via *ppIdx */
81618   int *aiCol = 0;                     /* Value to return via *paiCol */
81619   int nCol = pFKey->nCol;             /* Number of columns in parent key */
81620   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
81621
81622   /* The caller is responsible for zeroing output parameters. */
81623   assert( ppIdx && *ppIdx==0 );
81624   assert( !paiCol || *paiCol==0 );
81625   assert( pParse );
81626
81627   /* If this is a non-composite (single column) foreign key, check if it 
81628   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx 
81629   ** and *paiCol set to zero and return early. 
81630   **
81631   ** Otherwise, for a composite foreign key (more than one column), allocate
81632   ** space for the aiCol array (returned via output parameter *paiCol).
81633   ** Non-composite foreign keys do not require the aiCol array.
81634   */
81635   if( nCol==1 ){
81636     /* The FK maps to the IPK if any of the following are true:
81637     **
81638     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly 
81639     **      mapped to the primary key of table pParent, or
81640     **   2) The FK is explicitly mapped to a column declared as INTEGER
81641     **      PRIMARY KEY.
81642     */
81643     if( pParent->iPKey>=0 ){
81644       if( !zKey ) return 0;
81645       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
81646     }
81647   }else if( paiCol ){
81648     assert( nCol>1 );
81649     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
81650     if( !aiCol ) return 1;
81651     *paiCol = aiCol;
81652   }
81653
81654   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
81655     if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){ 
81656       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
81657       ** of columns. If each indexed column corresponds to a foreign key
81658       ** column of pFKey, then this index is a winner.  */
81659
81660       if( zKey==0 ){
81661         /* If zKey is NULL, then this foreign key is implicitly mapped to 
81662         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be 
81663         ** identified by the test (Index.autoIndex==2).  */
81664         if( pIdx->autoIndex==2 ){
81665           if( aiCol ){
81666             int i;
81667             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
81668           }
81669           break;
81670         }
81671       }else{
81672         /* If zKey is non-NULL, then this foreign key was declared to
81673         ** map to an explicit list of columns in table pParent. Check if this
81674         ** index matches those columns. Also, check that the index uses
81675         ** the default collation sequences for each column. */
81676         int i, j;
81677         for(i=0; i<nCol; i++){
81678           int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
81679           char *zDfltColl;                  /* Def. collation for column */
81680           char *zIdxCol;                    /* Name of indexed column */
81681
81682           /* If the index uses a collation sequence that is different from
81683           ** the default collation sequence for the column, this index is
81684           ** unusable. Bail out early in this case.  */
81685           zDfltColl = pParent->aCol[iCol].zColl;
81686           if( !zDfltColl ){
81687             zDfltColl = "BINARY";
81688           }
81689           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
81690
81691           zIdxCol = pParent->aCol[iCol].zName;
81692           for(j=0; j<nCol; j++){
81693             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
81694               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
81695               break;
81696             }
81697           }
81698           if( j==nCol ) break;
81699         }
81700         if( i==nCol ) break;      /* pIdx is usable */
81701       }
81702     }
81703   }
81704
81705   if( !pIdx ){
81706     if( !pParse->disableTriggers ){
81707       sqlite3ErrorMsg(pParse, "foreign key mismatch");
81708     }
81709     sqlite3DbFree(pParse->db, aiCol);
81710     return 1;
81711   }
81712
81713   *ppIdx = pIdx;
81714   return 0;
81715 }
81716
81717 /*
81718 ** This function is called when a row is inserted into or deleted from the 
81719 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed 
81720 ** on the child table of pFKey, this function is invoked twice for each row
81721 ** affected - once to "delete" the old row, and then again to "insert" the
81722 ** new row.
81723 **
81724 ** Each time it is called, this function generates VDBE code to locate the
81725 ** row in the parent table that corresponds to the row being inserted into 
81726 ** or deleted from the child table. If the parent row can be found, no 
81727 ** special action is taken. Otherwise, if the parent row can *not* be
81728 ** found in the parent table:
81729 **
81730 **   Operation | FK type   | Action taken
81731 **   --------------------------------------------------------------------------
81732 **   INSERT      immediate   Increment the "immediate constraint counter".
81733 **
81734 **   DELETE      immediate   Decrement the "immediate constraint counter".
81735 **
81736 **   INSERT      deferred    Increment the "deferred constraint counter".
81737 **
81738 **   DELETE      deferred    Decrement the "deferred constraint counter".
81739 **
81740 ** These operations are identified in the comment at the top of this file 
81741 ** (fkey.c) as "I.1" and "D.1".
81742 */
81743 static void fkLookupParent(
81744   Parse *pParse,        /* Parse context */
81745   int iDb,              /* Index of database housing pTab */
81746   Table *pTab,          /* Parent table of FK pFKey */
81747   Index *pIdx,          /* Unique index on parent key columns in pTab */
81748   FKey *pFKey,          /* Foreign key constraint */
81749   int *aiCol,           /* Map from parent key columns to child table columns */
81750   int regData,          /* Address of array containing child table row */
81751   int nIncr,            /* Increment constraint counter by this */
81752   int isIgnore          /* If true, pretend pTab contains all NULL values */
81753 ){
81754   int i;                                    /* Iterator variable */
81755   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
81756   int iCur = pParse->nTab - 1;              /* Cursor number to use */
81757   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
81758
81759   /* If nIncr is less than zero, then check at runtime if there are any
81760   ** outstanding constraints to resolve. If there are not, there is no need
81761   ** to check if deleting this row resolves any outstanding violations.
81762   **
81763   ** Check if any of the key columns in the child table row are NULL. If 
81764   ** any are, then the constraint is considered satisfied. No need to 
81765   ** search for a matching row in the parent table.  */
81766   if( nIncr<0 ){
81767     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
81768   }
81769   for(i=0; i<pFKey->nCol; i++){
81770     int iReg = aiCol[i] + regData + 1;
81771     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
81772   }
81773
81774   if( isIgnore==0 ){
81775     if( pIdx==0 ){
81776       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
81777       ** column of the parent table (table pTab).  */
81778       int iMustBeInt;               /* Address of MustBeInt instruction */
81779       int regTemp = sqlite3GetTempReg(pParse);
81780   
81781       /* Invoke MustBeInt to coerce the child key value to an integer (i.e. 
81782       ** apply the affinity of the parent key). If this fails, then there
81783       ** is no matching parent key. Before using MustBeInt, make a copy of
81784       ** the value. Otherwise, the value inserted into the child key column
81785       ** will have INTEGER affinity applied to it, which may not be correct.  */
81786       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
81787       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
81788   
81789       /* If the parent table is the same as the child table, and we are about
81790       ** to increment the constraint-counter (i.e. this is an INSERT operation),
81791       ** then check if the row being inserted matches itself. If so, do not
81792       ** increment the constraint-counter.  */
81793       if( pTab==pFKey->pFrom && nIncr==1 ){
81794         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
81795       }
81796   
81797       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
81798       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
81799       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
81800       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
81801       sqlite3VdbeJumpHere(v, iMustBeInt);
81802       sqlite3ReleaseTempReg(pParse, regTemp);
81803     }else{
81804       int nCol = pFKey->nCol;
81805       int regTemp = sqlite3GetTempRange(pParse, nCol);
81806       int regRec = sqlite3GetTempReg(pParse);
81807       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
81808   
81809       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
81810       sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
81811       for(i=0; i<nCol; i++){
81812         sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
81813       }
81814   
81815       /* If the parent table is the same as the child table, and we are about
81816       ** to increment the constraint-counter (i.e. this is an INSERT operation),
81817       ** then check if the row being inserted matches itself. If so, do not
81818       ** increment the constraint-counter.  */
81819       if( pTab==pFKey->pFrom && nIncr==1 ){
81820         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
81821         for(i=0; i<nCol; i++){
81822           int iChild = aiCol[i]+1+regData;
81823           int iParent = pIdx->aiColumn[i]+1+regData;
81824           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
81825         }
81826         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
81827       }
81828   
81829       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
81830       sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
81831       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
81832   
81833       sqlite3ReleaseTempReg(pParse, regRec);
81834       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
81835     }
81836   }
81837
81838   if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
81839     /* Special case: If this is an INSERT statement that will insert exactly
81840     ** one row into the table, raise a constraint immediately instead of
81841     ** incrementing a counter. This is necessary as the VM code is being
81842     ** generated for will not open a statement transaction.  */
81843     assert( nIncr==1 );
81844     sqlite3HaltConstraint(
81845         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
81846     );
81847   }else{
81848     if( nIncr>0 && pFKey->isDeferred==0 ){
81849       sqlite3ParseToplevel(pParse)->mayAbort = 1;
81850     }
81851     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
81852   }
81853
81854   sqlite3VdbeResolveLabel(v, iOk);
81855   sqlite3VdbeAddOp1(v, OP_Close, iCur);
81856 }
81857
81858 /*
81859 ** This function is called to generate code executed when a row is deleted
81860 ** from the parent table of foreign key constraint pFKey and, if pFKey is 
81861 ** deferred, when a row is inserted into the same table. When generating
81862 ** code for an SQL UPDATE operation, this function may be called twice -
81863 ** once to "delete" the old row and once to "insert" the new row.
81864 **
81865 ** The code generated by this function scans through the rows in the child
81866 ** table that correspond to the parent table row being deleted or inserted.
81867 ** For each child row found, one of the following actions is taken:
81868 **
81869 **   Operation | FK type   | Action taken
81870 **   --------------------------------------------------------------------------
81871 **   DELETE      immediate   Increment the "immediate constraint counter".
81872 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
81873 **                           throw a "foreign key constraint failed" exception.
81874 **
81875 **   INSERT      immediate   Decrement the "immediate constraint counter".
81876 **
81877 **   DELETE      deferred    Increment the "deferred constraint counter".
81878 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
81879 **                           throw a "foreign key constraint failed" exception.
81880 **
81881 **   INSERT      deferred    Decrement the "deferred constraint counter".
81882 **
81883 ** These operations are identified in the comment at the top of this file 
81884 ** (fkey.c) as "I.2" and "D.2".
81885 */
81886 static void fkScanChildren(
81887   Parse *pParse,                  /* Parse context */
81888   SrcList *pSrc,                  /* SrcList containing the table to scan */
81889   Table *pTab,
81890   Index *pIdx,                    /* Foreign key index */
81891   FKey *pFKey,                    /* Foreign key relationship */
81892   int *aiCol,                     /* Map from pIdx cols to child table cols */
81893   int regData,                    /* Referenced table data starts here */
81894   int nIncr                       /* Amount to increment deferred counter by */
81895 ){
81896   sqlite3 *db = pParse->db;       /* Database handle */
81897   int i;                          /* Iterator variable */
81898   Expr *pWhere = 0;               /* WHERE clause to scan with */
81899   NameContext sNameContext;       /* Context used to resolve WHERE clause */
81900   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
81901   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
81902   Vdbe *v = sqlite3GetVdbe(pParse);
81903
81904   assert( !pIdx || pIdx->pTable==pTab );
81905
81906   if( nIncr<0 ){
81907     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
81908   }
81909
81910   /* Create an Expr object representing an SQL expression like:
81911   **
81912   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
81913   **
81914   ** The collation sequence used for the comparison should be that of
81915   ** the parent key columns. The affinity of the parent key column should
81916   ** be applied to each child key value before the comparison takes place.
81917   */
81918   for(i=0; i<pFKey->nCol; i++){
81919     Expr *pLeft;                  /* Value from parent table row */
81920     Expr *pRight;                 /* Column ref to child table */
81921     Expr *pEq;                    /* Expression (pLeft = pRight) */
81922     int iCol;                     /* Index of column in child table */ 
81923     const char *zCol;             /* Name of column in child table */
81924
81925     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
81926     if( pLeft ){
81927       /* Set the collation sequence and affinity of the LHS of each TK_EQ
81928       ** expression to the parent key column defaults.  */
81929       if( pIdx ){
81930         Column *pCol;
81931         iCol = pIdx->aiColumn[i];
81932         pCol = &pTab->aCol[iCol];
81933         if( pTab->iPKey==iCol ) iCol = -1;
81934         pLeft->iTable = regData+iCol+1;
81935         pLeft->affinity = pCol->affinity;
81936         pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
81937       }else{
81938         pLeft->iTable = regData;
81939         pLeft->affinity = SQLITE_AFF_INTEGER;
81940       }
81941     }
81942     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
81943     assert( iCol>=0 );
81944     zCol = pFKey->pFrom->aCol[iCol].zName;
81945     pRight = sqlite3Expr(db, TK_ID, zCol);
81946     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
81947     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
81948   }
81949
81950   /* If the child table is the same as the parent table, and this scan
81951   ** is taking place as part of a DELETE operation (operation D.2), omit the
81952   ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE 
81953   ** clause, where $rowid is the rowid of the row being deleted.  */
81954   if( pTab==pFKey->pFrom && nIncr>0 ){
81955     Expr *pEq;                    /* Expression (pLeft = pRight) */
81956     Expr *pLeft;                  /* Value from parent table row */
81957     Expr *pRight;                 /* Column ref to child table */
81958     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
81959     pRight = sqlite3Expr(db, TK_COLUMN, 0);
81960     if( pLeft && pRight ){
81961       pLeft->iTable = regData;
81962       pLeft->affinity = SQLITE_AFF_INTEGER;
81963       pRight->iTable = pSrc->a[0].iCursor;
81964       pRight->iColumn = -1;
81965     }
81966     pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
81967     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
81968   }
81969
81970   /* Resolve the references in the WHERE clause. */
81971   memset(&sNameContext, 0, sizeof(NameContext));
81972   sNameContext.pSrcList = pSrc;
81973   sNameContext.pParse = pParse;
81974   sqlite3ResolveExprNames(&sNameContext, pWhere);
81975
81976   /* Create VDBE to loop through the entries in pSrc that match the WHERE
81977   ** clause. If the constraint is not deferred, throw an exception for
81978   ** each row found. Otherwise, for deferred constraints, increment the
81979   ** deferred constraint counter by nIncr for each row selected.  */
81980   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
81981   if( nIncr>0 && pFKey->isDeferred==0 ){
81982     sqlite3ParseToplevel(pParse)->mayAbort = 1;
81983   }
81984   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
81985   if( pWInfo ){
81986     sqlite3WhereEnd(pWInfo);
81987   }
81988
81989   /* Clean up the WHERE clause constructed above. */
81990   sqlite3ExprDelete(db, pWhere);
81991   if( iFkIfZero ){
81992     sqlite3VdbeJumpHere(v, iFkIfZero);
81993   }
81994 }
81995
81996 /*
81997 ** This function returns a pointer to the head of a linked list of FK
81998 ** constraints for which table pTab is the parent table. For example,
81999 ** given the following schema:
82000 **
82001 **   CREATE TABLE t1(a PRIMARY KEY);
82002 **   CREATE TABLE t2(b REFERENCES t1(a);
82003 **
82004 ** Calling this function with table "t1" as an argument returns a pointer
82005 ** to the FKey structure representing the foreign key constraint on table
82006 ** "t2". Calling this function with "t2" as the argument would return a
82007 ** NULL pointer (as there are no FK constraints for which t2 is the parent
82008 ** table).
82009 */
82010 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
82011   int nName = sqlite3Strlen30(pTab->zName);
82012   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
82013 }
82014
82015 /*
82016 ** The second argument is a Trigger structure allocated by the 
82017 ** fkActionTrigger() routine. This function deletes the Trigger structure
82018 ** and all of its sub-components.
82019 **
82020 ** The Trigger structure or any of its sub-components may be allocated from
82021 ** the lookaside buffer belonging to database handle dbMem.
82022 */
82023 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
82024   if( p ){
82025     TriggerStep *pStep = p->step_list;
82026     sqlite3ExprDelete(dbMem, pStep->pWhere);
82027     sqlite3ExprListDelete(dbMem, pStep->pExprList);
82028     sqlite3SelectDelete(dbMem, pStep->pSelect);
82029     sqlite3ExprDelete(dbMem, p->pWhen);
82030     sqlite3DbFree(dbMem, p);
82031   }
82032 }
82033
82034 /*
82035 ** This function is called to generate code that runs when table pTab is
82036 ** being dropped from the database. The SrcList passed as the second argument
82037 ** to this function contains a single entry guaranteed to resolve to
82038 ** table pTab.
82039 **
82040 ** Normally, no code is required. However, if either
82041 **
82042 **   (a) The table is the parent table of a FK constraint, or
82043 **   (b) The table is the child table of a deferred FK constraint and it is
82044 **       determined at runtime that there are outstanding deferred FK 
82045 **       constraint violations in the database,
82046 **
82047 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
82048 ** the table from the database. Triggers are disabled while running this
82049 ** DELETE, but foreign key actions are not.
82050 */
82051 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
82052   sqlite3 *db = pParse->db;
82053   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
82054     int iSkip = 0;
82055     Vdbe *v = sqlite3GetVdbe(pParse);
82056
82057     assert( v );                  /* VDBE has already been allocated */
82058     if( sqlite3FkReferences(pTab)==0 ){
82059       /* Search for a deferred foreign key constraint for which this table
82060       ** is the child table. If one cannot be found, return without 
82061       ** generating any VDBE code. If one can be found, then jump over
82062       ** the entire DELETE if there are no outstanding deferred constraints
82063       ** when this statement is run.  */
82064       FKey *p;
82065       for(p=pTab->pFKey; p; p=p->pNextFrom){
82066         if( p->isDeferred ) break;
82067       }
82068       if( !p ) return;
82069       iSkip = sqlite3VdbeMakeLabel(v);
82070       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
82071     }
82072
82073     pParse->disableTriggers = 1;
82074     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
82075     pParse->disableTriggers = 0;
82076
82077     /* If the DELETE has generated immediate foreign key constraint 
82078     ** violations, halt the VDBE and return an error at this point, before
82079     ** any modifications to the schema are made. This is because statement
82080     ** transactions are not able to rollback schema changes.  */
82081     sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
82082     sqlite3HaltConstraint(
82083         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
82084     );
82085
82086     if( iSkip ){
82087       sqlite3VdbeResolveLabel(v, iSkip);
82088     }
82089   }
82090 }
82091
82092 /*
82093 ** This function is called when inserting, deleting or updating a row of
82094 ** table pTab to generate VDBE code to perform foreign key constraint 
82095 ** processing for the operation.
82096 **
82097 ** For a DELETE operation, parameter regOld is passed the index of the
82098 ** first register in an array of (pTab->nCol+1) registers containing the
82099 ** rowid of the row being deleted, followed by each of the column values
82100 ** of the row being deleted, from left to right. Parameter regNew is passed
82101 ** zero in this case.
82102 **
82103 ** For an INSERT operation, regOld is passed zero and regNew is passed the
82104 ** first register of an array of (pTab->nCol+1) registers containing the new
82105 ** row data.
82106 **
82107 ** For an UPDATE operation, this function is called twice. Once before
82108 ** the original record is deleted from the table using the calling convention
82109 ** described for DELETE. Then again after the original record is deleted
82110 ** but before the new record is inserted using the INSERT convention. 
82111 */
82112 SQLITE_PRIVATE void sqlite3FkCheck(
82113   Parse *pParse,                  /* Parse context */
82114   Table *pTab,                    /* Row is being deleted from this table */ 
82115   int regOld,                     /* Previous row data is stored here */
82116   int regNew                      /* New row data is stored here */
82117 ){
82118   sqlite3 *db = pParse->db;       /* Database handle */
82119   Vdbe *v;                        /* VM to write code to */
82120   FKey *pFKey;                    /* Used to iterate through FKs */
82121   int iDb;                        /* Index of database containing pTab */
82122   const char *zDb;                /* Name of database containing pTab */
82123   int isIgnoreErrors = pParse->disableTriggers;
82124
82125   /* Exactly one of regOld and regNew should be non-zero. */
82126   assert( (regOld==0)!=(regNew==0) );
82127
82128   /* If foreign-keys are disabled, this function is a no-op. */
82129   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
82130
82131   v = sqlite3GetVdbe(pParse);
82132   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
82133   zDb = db->aDb[iDb].zName;
82134
82135   /* Loop through all the foreign key constraints for which pTab is the
82136   ** child table (the table that the foreign key definition is part of).  */
82137   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
82138     Table *pTo;                   /* Parent table of foreign key pFKey */
82139     Index *pIdx = 0;              /* Index on key columns in pTo */
82140     int *aiFree = 0;
82141     int *aiCol;
82142     int iCol;
82143     int i;
82144     int isIgnore = 0;
82145
82146     /* Find the parent table of this foreign key. Also find a unique index 
82147     ** on the parent key columns in the parent table. If either of these 
82148     ** schema items cannot be located, set an error in pParse and return 
82149     ** early.  */
82150     if( pParse->disableTriggers ){
82151       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
82152     }else{
82153       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
82154     }
82155     if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
82156       if( !isIgnoreErrors || db->mallocFailed ) return;
82157       continue;
82158     }
82159     assert( pFKey->nCol==1 || (aiFree && pIdx) );
82160
82161     if( aiFree ){
82162       aiCol = aiFree;
82163     }else{
82164       iCol = pFKey->aCol[0].iFrom;
82165       aiCol = &iCol;
82166     }
82167     for(i=0; i<pFKey->nCol; i++){
82168       if( aiCol[i]==pTab->iPKey ){
82169         aiCol[i] = -1;
82170       }
82171 #ifndef SQLITE_OMIT_AUTHORIZATION
82172       /* Request permission to read the parent key columns. If the 
82173       ** authorization callback returns SQLITE_IGNORE, behave as if any
82174       ** values read from the parent table are NULL. */
82175       if( db->xAuth ){
82176         int rcauth;
82177         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
82178         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
82179         isIgnore = (rcauth==SQLITE_IGNORE);
82180       }
82181 #endif
82182     }
82183
82184     /* Take a shared-cache advisory read-lock on the parent table. Allocate 
82185     ** a cursor to use to search the unique index on the parent key columns 
82186     ** in the parent table.  */
82187     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
82188     pParse->nTab++;
82189
82190     if( regOld!=0 ){
82191       /* A row is being removed from the child table. Search for the parent.
82192       ** If the parent does not exist, removing the child row resolves an 
82193       ** outstanding foreign key constraint violation. */
82194       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
82195     }
82196     if( regNew!=0 ){
82197       /* A row is being added to the child table. If a parent row cannot
82198       ** be found, adding the child row has violated the FK constraint. */ 
82199       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
82200     }
82201
82202     sqlite3DbFree(db, aiFree);
82203   }
82204
82205   /* Loop through all the foreign key constraints that refer to this table */
82206   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
82207     Index *pIdx = 0;              /* Foreign key index for pFKey */
82208     SrcList *pSrc;
82209     int *aiCol = 0;
82210
82211     if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
82212       assert( regOld==0 && regNew!=0 );
82213       /* Inserting a single row into a parent table cannot cause an immediate
82214       ** foreign key violation. So do nothing in this case.  */
82215       continue;
82216     }
82217
82218     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
82219       if( !isIgnoreErrors || db->mallocFailed ) return;
82220       continue;
82221     }
82222     assert( aiCol || pFKey->nCol==1 );
82223
82224     /* Create a SrcList structure containing a single table (the table 
82225     ** the foreign key that refers to this table is attached to). This
82226     ** is required for the sqlite3WhereXXX() interface.  */
82227     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
82228     if( pSrc ){
82229       struct SrcList_item *pItem = pSrc->a;
82230       pItem->pTab = pFKey->pFrom;
82231       pItem->zName = pFKey->pFrom->zName;
82232       pItem->pTab->nRef++;
82233       pItem->iCursor = pParse->nTab++;
82234   
82235       if( regNew!=0 ){
82236         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
82237       }
82238       if( regOld!=0 ){
82239         /* If there is a RESTRICT action configured for the current operation
82240         ** on the parent table of this FK, then throw an exception 
82241         ** immediately if the FK constraint is violated, even if this is a
82242         ** deferred trigger. That's what RESTRICT means. To defer checking
82243         ** the constraint, the FK should specify NO ACTION (represented
82244         ** using OE_None). NO ACTION is the default.  */
82245         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
82246       }
82247       pItem->zName = 0;
82248       sqlite3SrcListDelete(db, pSrc);
82249     }
82250     sqlite3DbFree(db, aiCol);
82251   }
82252 }
82253
82254 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
82255
82256 /*
82257 ** This function is called before generating code to update or delete a 
82258 ** row contained in table pTab.
82259 */
82260 SQLITE_PRIVATE u32 sqlite3FkOldmask(
82261   Parse *pParse,                  /* Parse context */
82262   Table *pTab                     /* Table being modified */
82263 ){
82264   u32 mask = 0;
82265   if( pParse->db->flags&SQLITE_ForeignKeys ){
82266     FKey *p;
82267     int i;
82268     for(p=pTab->pFKey; p; p=p->pNextFrom){
82269       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
82270     }
82271     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
82272       Index *pIdx = 0;
82273       locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
82274       if( pIdx ){
82275         for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
82276       }
82277     }
82278   }
82279   return mask;
82280 }
82281
82282 /*
82283 ** This function is called before generating code to update or delete a 
82284 ** row contained in table pTab. If the operation is a DELETE, then
82285 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
82286 ** to an array of size N, where N is the number of columns in table pTab.
82287 ** If the i'th column is not modified by the UPDATE, then the corresponding 
82288 ** entry in the aChange[] array is set to -1. If the column is modified,
82289 ** the value is 0 or greater. Parameter chngRowid is set to true if the
82290 ** UPDATE statement modifies the rowid fields of the table.
82291 **
82292 ** If any foreign key processing will be required, this function returns
82293 ** true. If there is no foreign key related processing, this function 
82294 ** returns false.
82295 */
82296 SQLITE_PRIVATE int sqlite3FkRequired(
82297   Parse *pParse,                  /* Parse context */
82298   Table *pTab,                    /* Table being modified */
82299   int *aChange,                   /* Non-NULL for UPDATE operations */
82300   int chngRowid                   /* True for UPDATE that affects rowid */
82301 ){
82302   if( pParse->db->flags&SQLITE_ForeignKeys ){
82303     if( !aChange ){
82304       /* A DELETE operation. Foreign key processing is required if the 
82305       ** table in question is either the child or parent table for any 
82306       ** foreign key constraint.  */
82307       return (sqlite3FkReferences(pTab) || pTab->pFKey);
82308     }else{
82309       /* This is an UPDATE. Foreign key processing is only required if the
82310       ** operation modifies one or more child or parent key columns. */
82311       int i;
82312       FKey *p;
82313
82314       /* Check if any child key columns are being modified. */
82315       for(p=pTab->pFKey; p; p=p->pNextFrom){
82316         for(i=0; i<p->nCol; i++){
82317           int iChildKey = p->aCol[i].iFrom;
82318           if( aChange[iChildKey]>=0 ) return 1;
82319           if( iChildKey==pTab->iPKey && chngRowid ) return 1;
82320         }
82321       }
82322
82323       /* Check if any parent key columns are being modified. */
82324       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
82325         for(i=0; i<p->nCol; i++){
82326           char *zKey = p->aCol[i].zCol;
82327           int iKey;
82328           for(iKey=0; iKey<pTab->nCol; iKey++){
82329             Column *pCol = &pTab->aCol[iKey];
82330             if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
82331               if( aChange[iKey]>=0 ) return 1;
82332               if( iKey==pTab->iPKey && chngRowid ) return 1;
82333             }
82334           }
82335         }
82336       }
82337     }
82338   }
82339   return 0;
82340 }
82341
82342 /*
82343 ** This function is called when an UPDATE or DELETE operation is being 
82344 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
82345 ** If the current operation is an UPDATE, then the pChanges parameter is
82346 ** passed a pointer to the list of columns being modified. If it is a
82347 ** DELETE, pChanges is passed a NULL pointer.
82348 **
82349 ** It returns a pointer to a Trigger structure containing a trigger
82350 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
82351 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
82352 ** returned (these actions require no special handling by the triggers
82353 ** sub-system, code for them is created by fkScanChildren()).
82354 **
82355 ** For example, if pFKey is the foreign key and pTab is table "p" in 
82356 ** the following schema:
82357 **
82358 **   CREATE TABLE p(pk PRIMARY KEY);
82359 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
82360 **
82361 ** then the returned trigger structure is equivalent to:
82362 **
82363 **   CREATE TRIGGER ... DELETE ON p BEGIN
82364 **     DELETE FROM c WHERE ck = old.pk;
82365 **   END;
82366 **
82367 ** The returned pointer is cached as part of the foreign key object. It
82368 ** is eventually freed along with the rest of the foreign key object by 
82369 ** sqlite3FkDelete().
82370 */
82371 static Trigger *fkActionTrigger(
82372   Parse *pParse,                  /* Parse context */
82373   Table *pTab,                    /* Table being updated or deleted from */
82374   FKey *pFKey,                    /* Foreign key to get action for */
82375   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
82376 ){
82377   sqlite3 *db = pParse->db;       /* Database handle */
82378   int action;                     /* One of OE_None, OE_Cascade etc. */
82379   Trigger *pTrigger;              /* Trigger definition to return */
82380   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
82381
82382   action = pFKey->aAction[iAction];
82383   pTrigger = pFKey->apTrigger[iAction];
82384
82385   if( action!=OE_None && !pTrigger ){
82386     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
82387     char const *zFrom;            /* Name of child table */
82388     int nFrom;                    /* Length in bytes of zFrom */
82389     Index *pIdx = 0;              /* Parent key index for this FK */
82390     int *aiCol = 0;               /* child table cols -> parent key cols */
82391     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
82392     Expr *pWhere = 0;             /* WHERE clause of trigger step */
82393     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
82394     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
82395     int i;                        /* Iterator variable */
82396     Expr *pWhen = 0;              /* WHEN clause for the trigger */
82397
82398     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
82399     assert( aiCol || pFKey->nCol==1 );
82400
82401     for(i=0; i<pFKey->nCol; i++){
82402       Token tOld = { "old", 3 };  /* Literal "old" token */
82403       Token tNew = { "new", 3 };  /* Literal "new" token */
82404       Token tFromCol;             /* Name of column in child table */
82405       Token tToCol;               /* Name of column in parent table */
82406       int iFromCol;               /* Idx of column in child table */
82407       Expr *pEq;                  /* tFromCol = OLD.tToCol */
82408
82409       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
82410       assert( iFromCol>=0 );
82411       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
82412       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
82413
82414       tToCol.n = sqlite3Strlen30(tToCol.z);
82415       tFromCol.n = sqlite3Strlen30(tFromCol.z);
82416
82417       /* Create the expression "OLD.zToCol = zFromCol". It is important
82418       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
82419       ** that the affinity and collation sequence associated with the
82420       ** parent table are used for the comparison. */
82421       pEq = sqlite3PExpr(pParse, TK_EQ,
82422           sqlite3PExpr(pParse, TK_DOT, 
82423             sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
82424             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
82425           , 0),
82426           sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
82427       , 0);
82428       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
82429
82430       /* For ON UPDATE, construct the next term of the WHEN clause.
82431       ** The final WHEN clause will be like this:
82432       **
82433       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
82434       */
82435       if( pChanges ){
82436         pEq = sqlite3PExpr(pParse, TK_IS,
82437             sqlite3PExpr(pParse, TK_DOT, 
82438               sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
82439               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
82440               0),
82441             sqlite3PExpr(pParse, TK_DOT, 
82442               sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
82443               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
82444               0),
82445             0);
82446         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
82447       }
82448   
82449       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
82450         Expr *pNew;
82451         if( action==OE_Cascade ){
82452           pNew = sqlite3PExpr(pParse, TK_DOT, 
82453             sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
82454             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
82455           , 0);
82456         }else if( action==OE_SetDflt ){
82457           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
82458           if( pDflt ){
82459             pNew = sqlite3ExprDup(db, pDflt, 0);
82460           }else{
82461             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
82462           }
82463         }else{
82464           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
82465         }
82466         pList = sqlite3ExprListAppend(pParse, pList, pNew);
82467         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
82468       }
82469     }
82470     sqlite3DbFree(db, aiCol);
82471
82472     zFrom = pFKey->pFrom->zName;
82473     nFrom = sqlite3Strlen30(zFrom);
82474
82475     if( action==OE_Restrict ){
82476       Token tFrom;
82477       Expr *pRaise; 
82478
82479       tFrom.z = zFrom;
82480       tFrom.n = nFrom;
82481       pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
82482       if( pRaise ){
82483         pRaise->affinity = OE_Abort;
82484       }
82485       pSelect = sqlite3SelectNew(pParse, 
82486           sqlite3ExprListAppend(pParse, 0, pRaise),
82487           sqlite3SrcListAppend(db, 0, &tFrom, 0),
82488           pWhere,
82489           0, 0, 0, 0, 0, 0
82490       );
82491       pWhere = 0;
82492     }
82493
82494     /* Disable lookaside memory allocation */
82495     enableLookaside = db->lookaside.bEnabled;
82496     db->lookaside.bEnabled = 0;
82497
82498     pTrigger = (Trigger *)sqlite3DbMallocZero(db, 
82499         sizeof(Trigger) +         /* struct Trigger */
82500         sizeof(TriggerStep) +     /* Single step in trigger program */
82501         nFrom + 1                 /* Space for pStep->target.z */
82502     );
82503     if( pTrigger ){
82504       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
82505       pStep->target.z = (char *)&pStep[1];
82506       pStep->target.n = nFrom;
82507       memcpy((char *)pStep->target.z, zFrom, nFrom);
82508   
82509       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
82510       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
82511       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
82512       if( pWhen ){
82513         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
82514         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
82515       }
82516     }
82517
82518     /* Re-enable the lookaside buffer, if it was disabled earlier. */
82519     db->lookaside.bEnabled = enableLookaside;
82520
82521     sqlite3ExprDelete(db, pWhere);
82522     sqlite3ExprDelete(db, pWhen);
82523     sqlite3ExprListDelete(db, pList);
82524     sqlite3SelectDelete(db, pSelect);
82525     if( db->mallocFailed==1 ){
82526       fkTriggerDelete(db, pTrigger);
82527       return 0;
82528     }
82529
82530     switch( action ){
82531       case OE_Restrict:
82532         pStep->op = TK_SELECT; 
82533         break;
82534       case OE_Cascade: 
82535         if( !pChanges ){ 
82536           pStep->op = TK_DELETE; 
82537           break; 
82538         }
82539       default:
82540         pStep->op = TK_UPDATE;
82541     }
82542     pStep->pTrig = pTrigger;
82543     pTrigger->pSchema = pTab->pSchema;
82544     pTrigger->pTabSchema = pTab->pSchema;
82545     pFKey->apTrigger[iAction] = pTrigger;
82546     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
82547   }
82548
82549   return pTrigger;
82550 }
82551
82552 /*
82553 ** This function is called when deleting or updating a row to implement
82554 ** any required CASCADE, SET NULL or SET DEFAULT actions.
82555 */
82556 SQLITE_PRIVATE void sqlite3FkActions(
82557   Parse *pParse,                  /* Parse context */
82558   Table *pTab,                    /* Table being updated or deleted from */
82559   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
82560   int regOld                      /* Address of array containing old row */
82561 ){
82562   /* If foreign-key support is enabled, iterate through all FKs that 
82563   ** refer to table pTab. If there is an action associated with the FK 
82564   ** for this operation (either update or delete), invoke the associated 
82565   ** trigger sub-program.  */
82566   if( pParse->db->flags&SQLITE_ForeignKeys ){
82567     FKey *pFKey;                  /* Iterator variable */
82568     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
82569       Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
82570       if( pAction ){
82571         sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
82572       }
82573     }
82574   }
82575 }
82576
82577 #endif /* ifndef SQLITE_OMIT_TRIGGER */
82578
82579 /*
82580 ** Free all memory associated with foreign key definitions attached to
82581 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
82582 ** hash table.
82583 */
82584 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
82585   FKey *pFKey;                    /* Iterator variable */
82586   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
82587
82588   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
82589
82590     /* Remove the FK from the fkeyHash hash table. */
82591     if( !db || db->pnBytesFreed==0 ){
82592       if( pFKey->pPrevTo ){
82593         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
82594       }else{
82595         void *p = (void *)pFKey->pNextTo;
82596         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
82597         sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
82598       }
82599       if( pFKey->pNextTo ){
82600         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
82601       }
82602     }
82603
82604     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
82605     ** classified as either immediate or deferred.
82606     */
82607     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
82608
82609     /* Delete any triggers created to implement actions for this FK. */
82610 #ifndef SQLITE_OMIT_TRIGGER
82611     fkTriggerDelete(db, pFKey->apTrigger[0]);
82612     fkTriggerDelete(db, pFKey->apTrigger[1]);
82613 #endif
82614
82615     pNext = pFKey->pNextFrom;
82616     sqlite3DbFree(db, pFKey);
82617   }
82618 }
82619 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
82620
82621 /************** End of fkey.c ************************************************/
82622 /************** Begin file insert.c ******************************************/
82623 /*
82624 ** 2001 September 15
82625 **
82626 ** The author disclaims copyright to this source code.  In place of
82627 ** a legal notice, here is a blessing:
82628 **
82629 **    May you do good and not evil.
82630 **    May you find forgiveness for yourself and forgive others.
82631 **    May you share freely, never taking more than you give.
82632 **
82633 *************************************************************************
82634 ** This file contains C code routines that are called by the parser
82635 ** to handle INSERT statements in SQLite.
82636 */
82637
82638 /*
82639 ** Generate code that will open a table for reading.
82640 */
82641 SQLITE_PRIVATE void sqlite3OpenTable(
82642   Parse *p,       /* Generate code into this VDBE */
82643   int iCur,       /* The cursor number of the table */
82644   int iDb,        /* The database index in sqlite3.aDb[] */
82645   Table *pTab,    /* The table to be opened */
82646   int opcode      /* OP_OpenRead or OP_OpenWrite */
82647 ){
82648   Vdbe *v;
82649   if( IsVirtual(pTab) ) return;
82650   v = sqlite3GetVdbe(p);
82651   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
82652   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
82653   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
82654   sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
82655   VdbeComment((v, "%s", pTab->zName));
82656 }
82657
82658 /*
82659 ** Return a pointer to the column affinity string associated with index
82660 ** pIdx. A column affinity string has one character for each column in 
82661 ** the table, according to the affinity of the column:
82662 **
82663 **  Character      Column affinity
82664 **  ------------------------------
82665 **  'a'            TEXT
82666 **  'b'            NONE
82667 **  'c'            NUMERIC
82668 **  'd'            INTEGER
82669 **  'e'            REAL
82670 **
82671 ** An extra 'b' is appended to the end of the string to cover the
82672 ** rowid that appears as the last column in every index.
82673 **
82674 ** Memory for the buffer containing the column index affinity string
82675 ** is managed along with the rest of the Index structure. It will be
82676 ** released when sqlite3DeleteIndex() is called.
82677 */
82678 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
82679   if( !pIdx->zColAff ){
82680     /* The first time a column affinity string for a particular index is
82681     ** required, it is allocated and populated here. It is then stored as
82682     ** a member of the Index structure for subsequent use.
82683     **
82684     ** The column affinity string will eventually be deleted by
82685     ** sqliteDeleteIndex() when the Index structure itself is cleaned
82686     ** up.
82687     */
82688     int n;
82689     Table *pTab = pIdx->pTable;
82690     sqlite3 *db = sqlite3VdbeDb(v);
82691     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
82692     if( !pIdx->zColAff ){
82693       db->mallocFailed = 1;
82694       return 0;
82695     }
82696     for(n=0; n<pIdx->nColumn; n++){
82697       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
82698     }
82699     pIdx->zColAff[n++] = SQLITE_AFF_NONE;
82700     pIdx->zColAff[n] = 0;
82701   }
82702  
82703   return pIdx->zColAff;
82704 }
82705
82706 /*
82707 ** Set P4 of the most recently inserted opcode to a column affinity
82708 ** string for table pTab. A column affinity string has one character
82709 ** for each column indexed by the index, according to the affinity of the
82710 ** column:
82711 **
82712 **  Character      Column affinity
82713 **  ------------------------------
82714 **  'a'            TEXT
82715 **  'b'            NONE
82716 **  'c'            NUMERIC
82717 **  'd'            INTEGER
82718 **  'e'            REAL
82719 */
82720 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
82721   /* The first time a column affinity string for a particular table
82722   ** is required, it is allocated and populated here. It is then 
82723   ** stored as a member of the Table structure for subsequent use.
82724   **
82725   ** The column affinity string will eventually be deleted by
82726   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
82727   */
82728   if( !pTab->zColAff ){
82729     char *zColAff;
82730     int i;
82731     sqlite3 *db = sqlite3VdbeDb(v);
82732
82733     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
82734     if( !zColAff ){
82735       db->mallocFailed = 1;
82736       return;
82737     }
82738
82739     for(i=0; i<pTab->nCol; i++){
82740       zColAff[i] = pTab->aCol[i].affinity;
82741     }
82742     zColAff[pTab->nCol] = '\0';
82743
82744     pTab->zColAff = zColAff;
82745   }
82746
82747   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
82748 }
82749
82750 /*
82751 ** Return non-zero if the table pTab in database iDb or any of its indices
82752 ** have been opened at any point in the VDBE program beginning at location
82753 ** iStartAddr throught the end of the program.  This is used to see if 
82754 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
82755 ** run without using temporary table for the results of the SELECT. 
82756 */
82757 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
82758   Vdbe *v = sqlite3GetVdbe(p);
82759   int i;
82760   int iEnd = sqlite3VdbeCurrentAddr(v);
82761 #ifndef SQLITE_OMIT_VIRTUALTABLE
82762   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
82763 #endif
82764
82765   for(i=iStartAddr; i<iEnd; i++){
82766     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
82767     assert( pOp!=0 );
82768     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
82769       Index *pIndex;
82770       int tnum = pOp->p2;
82771       if( tnum==pTab->tnum ){
82772         return 1;
82773       }
82774       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
82775         if( tnum==pIndex->tnum ){
82776           return 1;
82777         }
82778       }
82779     }
82780 #ifndef SQLITE_OMIT_VIRTUALTABLE
82781     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
82782       assert( pOp->p4.pVtab!=0 );
82783       assert( pOp->p4type==P4_VTAB );
82784       return 1;
82785     }
82786 #endif
82787   }
82788   return 0;
82789 }
82790
82791 #ifndef SQLITE_OMIT_AUTOINCREMENT
82792 /*
82793 ** Locate or create an AutoincInfo structure associated with table pTab
82794 ** which is in database iDb.  Return the register number for the register
82795 ** that holds the maximum rowid.
82796 **
82797 ** There is at most one AutoincInfo structure per table even if the
82798 ** same table is autoincremented multiple times due to inserts within
82799 ** triggers.  A new AutoincInfo structure is created if this is the
82800 ** first use of table pTab.  On 2nd and subsequent uses, the original
82801 ** AutoincInfo structure is used.
82802 **
82803 ** Three memory locations are allocated:
82804 **
82805 **   (1)  Register to hold the name of the pTab table.
82806 **   (2)  Register to hold the maximum ROWID of pTab.
82807 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
82808 **
82809 ** The 2nd register is the one that is returned.  That is all the
82810 ** insert routine needs to know about.
82811 */
82812 static int autoIncBegin(
82813   Parse *pParse,      /* Parsing context */
82814   int iDb,            /* Index of the database holding pTab */
82815   Table *pTab         /* The table we are writing to */
82816 ){
82817   int memId = 0;      /* Register holding maximum rowid */
82818   if( pTab->tabFlags & TF_Autoincrement ){
82819     Parse *pToplevel = sqlite3ParseToplevel(pParse);
82820     AutoincInfo *pInfo;
82821
82822     pInfo = pToplevel->pAinc;
82823     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
82824     if( pInfo==0 ){
82825       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
82826       if( pInfo==0 ) return 0;
82827       pInfo->pNext = pToplevel->pAinc;
82828       pToplevel->pAinc = pInfo;
82829       pInfo->pTab = pTab;
82830       pInfo->iDb = iDb;
82831       pToplevel->nMem++;                  /* Register to hold name of table */
82832       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
82833       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
82834     }
82835     memId = pInfo->regCtr;
82836   }
82837   return memId;
82838 }
82839
82840 /*
82841 ** This routine generates code that will initialize all of the
82842 ** register used by the autoincrement tracker.  
82843 */
82844 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
82845   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
82846   sqlite3 *db = pParse->db;  /* The database connection */
82847   Db *pDb;                   /* Database only autoinc table */
82848   int memId;                 /* Register holding max rowid */
82849   int addr;                  /* A VDBE address */
82850   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
82851
82852   /* This routine is never called during trigger-generation.  It is
82853   ** only called from the top-level */
82854   assert( pParse->pTriggerTab==0 );
82855   assert( pParse==sqlite3ParseToplevel(pParse) );
82856
82857   assert( v );   /* We failed long ago if this is not so */
82858   for(p = pParse->pAinc; p; p = p->pNext){
82859     pDb = &db->aDb[p->iDb];
82860     memId = p->regCtr;
82861     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
82862     addr = sqlite3VdbeCurrentAddr(v);
82863     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
82864     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
82865     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
82866     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
82867     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
82868     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
82869     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
82870     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
82871     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
82872     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
82873     sqlite3VdbeAddOp0(v, OP_Close);
82874   }
82875 }
82876
82877 /*
82878 ** Update the maximum rowid for an autoincrement calculation.
82879 **
82880 ** This routine should be called when the top of the stack holds a
82881 ** new rowid that is about to be inserted.  If that new rowid is
82882 ** larger than the maximum rowid in the memId memory cell, then the
82883 ** memory cell is updated.  The stack is unchanged.
82884 */
82885 static void autoIncStep(Parse *pParse, int memId, int regRowid){
82886   if( memId>0 ){
82887     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
82888   }
82889 }
82890
82891 /*
82892 ** This routine generates the code needed to write autoincrement
82893 ** maximum rowid values back into the sqlite_sequence register.
82894 ** Every statement that might do an INSERT into an autoincrement
82895 ** table (either directly or through triggers) needs to call this
82896 ** routine just before the "exit" code.
82897 */
82898 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
82899   AutoincInfo *p;
82900   Vdbe *v = pParse->pVdbe;
82901   sqlite3 *db = pParse->db;
82902
82903   assert( v );
82904   for(p = pParse->pAinc; p; p = p->pNext){
82905     Db *pDb = &db->aDb[p->iDb];
82906     int j1, j2, j3, j4, j5;
82907     int iRec;
82908     int memId = p->regCtr;
82909
82910     iRec = sqlite3GetTempReg(pParse);
82911     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
82912     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
82913     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
82914     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
82915     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
82916     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
82917     sqlite3VdbeJumpHere(v, j2);
82918     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
82919     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
82920     sqlite3VdbeJumpHere(v, j4);
82921     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
82922     sqlite3VdbeJumpHere(v, j1);
82923     sqlite3VdbeJumpHere(v, j5);
82924     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
82925     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
82926     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
82927     sqlite3VdbeAddOp0(v, OP_Close);
82928     sqlite3ReleaseTempReg(pParse, iRec);
82929   }
82930 }
82931 #else
82932 /*
82933 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
82934 ** above are all no-ops
82935 */
82936 # define autoIncBegin(A,B,C) (0)
82937 # define autoIncStep(A,B,C)
82938 #endif /* SQLITE_OMIT_AUTOINCREMENT */
82939
82940
82941 /* Forward declaration */
82942 static int xferOptimization(
82943   Parse *pParse,        /* Parser context */
82944   Table *pDest,         /* The table we are inserting into */
82945   Select *pSelect,      /* A SELECT statement to use as the data source */
82946   int onError,          /* How to handle constraint errors */
82947   int iDbDest           /* The database of pDest */
82948 );
82949
82950 /*
82951 ** This routine is call to handle SQL of the following forms:
82952 **
82953 **    insert into TABLE (IDLIST) values(EXPRLIST)
82954 **    insert into TABLE (IDLIST) select
82955 **
82956 ** The IDLIST following the table name is always optional.  If omitted,
82957 ** then a list of all columns for the table is substituted.  The IDLIST
82958 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
82959 **
82960 ** The pList parameter holds EXPRLIST in the first form of the INSERT
82961 ** statement above, and pSelect is NULL.  For the second form, pList is
82962 ** NULL and pSelect is a pointer to the select statement used to generate
82963 ** data for the insert.
82964 **
82965 ** The code generated follows one of four templates.  For a simple
82966 ** select with data coming from a VALUES clause, the code executes
82967 ** once straight down through.  Pseudo-code follows (we call this
82968 ** the "1st template"):
82969 **
82970 **         open write cursor to <table> and its indices
82971 **         puts VALUES clause expressions onto the stack
82972 **         write the resulting record into <table>
82973 **         cleanup
82974 **
82975 ** The three remaining templates assume the statement is of the form
82976 **
82977 **   INSERT INTO <table> SELECT ...
82978 **
82979 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
82980 ** in other words if the SELECT pulls all columns from a single table
82981 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
82982 ** if <table2> and <table1> are distinct tables but have identical
82983 ** schemas, including all the same indices, then a special optimization
82984 ** is invoked that copies raw records from <table2> over to <table1>.
82985 ** See the xferOptimization() function for the implementation of this
82986 ** template.  This is the 2nd template.
82987 **
82988 **         open a write cursor to <table>
82989 **         open read cursor on <table2>
82990 **         transfer all records in <table2> over to <table>
82991 **         close cursors
82992 **         foreach index on <table>
82993 **           open a write cursor on the <table> index
82994 **           open a read cursor on the corresponding <table2> index
82995 **           transfer all records from the read to the write cursors
82996 **           close cursors
82997 **         end foreach
82998 **
82999 ** The 3rd template is for when the second template does not apply
83000 ** and the SELECT clause does not read from <table> at any time.
83001 ** The generated code follows this template:
83002 **
83003 **         EOF <- 0
83004 **         X <- A
83005 **         goto B
83006 **      A: setup for the SELECT
83007 **         loop over the rows in the SELECT
83008 **           load values into registers R..R+n
83009 **           yield X
83010 **         end loop
83011 **         cleanup after the SELECT
83012 **         EOF <- 1
83013 **         yield X
83014 **         goto A
83015 **      B: open write cursor to <table> and its indices
83016 **      C: yield X
83017 **         if EOF goto D
83018 **         insert the select result into <table> from R..R+n
83019 **         goto C
83020 **      D: cleanup
83021 **
83022 ** The 4th template is used if the insert statement takes its
83023 ** values from a SELECT but the data is being inserted into a table
83024 ** that is also read as part of the SELECT.  In the third form,
83025 ** we have to use a intermediate table to store the results of
83026 ** the select.  The template is like this:
83027 **
83028 **         EOF <- 0
83029 **         X <- A
83030 **         goto B
83031 **      A: setup for the SELECT
83032 **         loop over the tables in the SELECT
83033 **           load value into register R..R+n
83034 **           yield X
83035 **         end loop
83036 **         cleanup after the SELECT
83037 **         EOF <- 1
83038 **         yield X
83039 **         halt-error
83040 **      B: open temp table
83041 **      L: yield X
83042 **         if EOF goto M
83043 **         insert row from R..R+n into temp table
83044 **         goto L
83045 **      M: open write cursor to <table> and its indices
83046 **         rewind temp table
83047 **      C: loop over rows of intermediate table
83048 **           transfer values form intermediate table into <table>
83049 **         end loop
83050 **      D: cleanup
83051 */
83052 SQLITE_PRIVATE void sqlite3Insert(
83053   Parse *pParse,        /* Parser context */
83054   SrcList *pTabList,    /* Name of table into which we are inserting */
83055   ExprList *pList,      /* List of values to be inserted */
83056   Select *pSelect,      /* A SELECT statement to use as the data source */
83057   IdList *pColumn,      /* Column names corresponding to IDLIST. */
83058   int onError           /* How to handle constraint errors */
83059 ){
83060   sqlite3 *db;          /* The main database structure */
83061   Table *pTab;          /* The table to insert into.  aka TABLE */
83062   char *zTab;           /* Name of the table into which we are inserting */
83063   const char *zDb;      /* Name of the database holding this table */
83064   int i, j, idx;        /* Loop counters */
83065   Vdbe *v;              /* Generate code into this virtual machine */
83066   Index *pIdx;          /* For looping over indices of the table */
83067   int nColumn;          /* Number of columns in the data */
83068   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
83069   int baseCur = 0;      /* VDBE Cursor number for pTab */
83070   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
83071   int endOfLoop;        /* Label for the end of the insertion loop */
83072   int useTempTable = 0; /* Store SELECT results in intermediate table */
83073   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
83074   int addrInsTop = 0;   /* Jump to label "D" */
83075   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
83076   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
83077   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
83078   int iDb;              /* Index of database holding TABLE */
83079   Db *pDb;              /* The database containing table being inserted into */
83080   int appendFlag = 0;   /* True if the insert is likely to be an append */
83081
83082   /* Register allocations */
83083   int regFromSelect = 0;/* Base register for data coming from SELECT */
83084   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
83085   int regRowCount = 0;  /* Memory cell used for the row counter */
83086   int regIns;           /* Block of regs holding rowid+data being inserted */
83087   int regRowid;         /* registers holding insert rowid */
83088   int regData;          /* register holding first column to insert */
83089   int regRecord;        /* Holds the assemblied row record */
83090   int regEof = 0;       /* Register recording end of SELECT data */
83091   int *aRegIdx = 0;     /* One register allocated to each index */
83092
83093 #ifndef SQLITE_OMIT_TRIGGER
83094   int isView;                 /* True if attempting to insert into a view */
83095   Trigger *pTrigger;          /* List of triggers on pTab, if required */
83096   int tmask;                  /* Mask of trigger times */
83097 #endif
83098
83099   db = pParse->db;
83100   memset(&dest, 0, sizeof(dest));
83101   if( pParse->nErr || db->mallocFailed ){
83102     goto insert_cleanup;
83103   }
83104
83105   /* Locate the table into which we will be inserting new information.
83106   */
83107   assert( pTabList->nSrc==1 );
83108   zTab = pTabList->a[0].zName;
83109   if( NEVER(zTab==0) ) goto insert_cleanup;
83110   pTab = sqlite3SrcListLookup(pParse, pTabList);
83111   if( pTab==0 ){
83112     goto insert_cleanup;
83113   }
83114   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
83115   assert( iDb<db->nDb );
83116   pDb = &db->aDb[iDb];
83117   zDb = pDb->zName;
83118   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
83119     goto insert_cleanup;
83120   }
83121
83122   /* Figure out if we have any triggers and if the table being
83123   ** inserted into is a view
83124   */
83125 #ifndef SQLITE_OMIT_TRIGGER
83126   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
83127   isView = pTab->pSelect!=0;
83128 #else
83129 # define pTrigger 0
83130 # define tmask 0
83131 # define isView 0
83132 #endif
83133 #ifdef SQLITE_OMIT_VIEW
83134 # undef isView
83135 # define isView 0
83136 #endif
83137   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
83138
83139   /* If pTab is really a view, make sure it has been initialized.
83140   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
83141   ** module table).
83142   */
83143   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
83144     goto insert_cleanup;
83145   }
83146
83147   /* Ensure that:
83148   *  (a) the table is not read-only, 
83149   *  (b) that if it is a view then ON INSERT triggers exist
83150   */
83151   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
83152     goto insert_cleanup;
83153   }
83154
83155   /* Allocate a VDBE
83156   */
83157   v = sqlite3GetVdbe(pParse);
83158   if( v==0 ) goto insert_cleanup;
83159   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
83160   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
83161
83162 #ifndef SQLITE_OMIT_XFER_OPT
83163   /* If the statement is of the form
83164   **
83165   **       INSERT INTO <table1> SELECT * FROM <table2>;
83166   **
83167   ** Then special optimizations can be applied that make the transfer
83168   ** very fast and which reduce fragmentation of indices.
83169   **
83170   ** This is the 2nd template.
83171   */
83172   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
83173     assert( !pTrigger );
83174     assert( pList==0 );
83175     goto insert_end;
83176   }
83177 #endif /* SQLITE_OMIT_XFER_OPT */
83178
83179   /* If this is an AUTOINCREMENT table, look up the sequence number in the
83180   ** sqlite_sequence table and store it in memory cell regAutoinc.
83181   */
83182   regAutoinc = autoIncBegin(pParse, iDb, pTab);
83183
83184   /* Figure out how many columns of data are supplied.  If the data
83185   ** is coming from a SELECT statement, then generate a co-routine that
83186   ** produces a single row of the SELECT on each invocation.  The
83187   ** co-routine is the common header to the 3rd and 4th templates.
83188   */
83189   if( pSelect ){
83190     /* Data is coming from a SELECT.  Generate code to implement that SELECT
83191     ** as a co-routine.  The code is common to both the 3rd and 4th
83192     ** templates:
83193     **
83194     **         EOF <- 0
83195     **         X <- A
83196     **         goto B
83197     **      A: setup for the SELECT
83198     **         loop over the tables in the SELECT
83199     **           load value into register R..R+n
83200     **           yield X
83201     **         end loop
83202     **         cleanup after the SELECT
83203     **         EOF <- 1
83204     **         yield X
83205     **         halt-error
83206     **
83207     ** On each invocation of the co-routine, it puts a single row of the
83208     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
83209     ** (These output registers are allocated by sqlite3Select().)  When
83210     ** the SELECT completes, it sets the EOF flag stored in regEof.
83211     */
83212     int rc, j1;
83213
83214     regEof = ++pParse->nMem;
83215     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
83216     VdbeComment((v, "SELECT eof flag"));
83217     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
83218     addrSelect = sqlite3VdbeCurrentAddr(v)+2;
83219     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
83220     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
83221     VdbeComment((v, "Jump over SELECT coroutine"));
83222
83223     /* Resolve the expressions in the SELECT statement and execute it. */
83224     rc = sqlite3Select(pParse, pSelect, &dest);
83225     assert( pParse->nErr==0 || rc );
83226     if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
83227       goto insert_cleanup;
83228     }
83229     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
83230     sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
83231     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
83232     VdbeComment((v, "End of SELECT coroutine"));
83233     sqlite3VdbeJumpHere(v, j1);                          /* label B: */
83234
83235     regFromSelect = dest.iMem;
83236     assert( pSelect->pEList );
83237     nColumn = pSelect->pEList->nExpr;
83238     assert( dest.nMem==nColumn );
83239
83240     /* Set useTempTable to TRUE if the result of the SELECT statement
83241     ** should be written into a temporary table (template 4).  Set to
83242     ** FALSE if each* row of the SELECT can be written directly into
83243     ** the destination table (template 3).
83244     **
83245     ** A temp table must be used if the table being updated is also one
83246     ** of the tables being read by the SELECT statement.  Also use a 
83247     ** temp table in the case of row triggers.
83248     */
83249     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
83250       useTempTable = 1;
83251     }
83252
83253     if( useTempTable ){
83254       /* Invoke the coroutine to extract information from the SELECT
83255       ** and add it to a transient table srcTab.  The code generated
83256       ** here is from the 4th template:
83257       **
83258       **      B: open temp table
83259       **      L: yield X
83260       **         if EOF goto M
83261       **         insert row from R..R+n into temp table
83262       **         goto L
83263       **      M: ...
83264       */
83265       int regRec;          /* Register to hold packed record */
83266       int regTempRowid;    /* Register to hold temp table ROWID */
83267       int addrTop;         /* Label "L" */
83268       int addrIf;          /* Address of jump to M */
83269
83270       srcTab = pParse->nTab++;
83271       regRec = sqlite3GetTempReg(pParse);
83272       regTempRowid = sqlite3GetTempReg(pParse);
83273       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
83274       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
83275       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
83276       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
83277       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
83278       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
83279       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
83280       sqlite3VdbeJumpHere(v, addrIf);
83281       sqlite3ReleaseTempReg(pParse, regRec);
83282       sqlite3ReleaseTempReg(pParse, regTempRowid);
83283     }
83284   }else{
83285     /* This is the case if the data for the INSERT is coming from a VALUES
83286     ** clause
83287     */
83288     NameContext sNC;
83289     memset(&sNC, 0, sizeof(sNC));
83290     sNC.pParse = pParse;
83291     srcTab = -1;
83292     assert( useTempTable==0 );
83293     nColumn = pList ? pList->nExpr : 0;
83294     for(i=0; i<nColumn; i++){
83295       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
83296         goto insert_cleanup;
83297       }
83298     }
83299   }
83300
83301   /* Make sure the number of columns in the source data matches the number
83302   ** of columns to be inserted into the table.
83303   */
83304   if( IsVirtual(pTab) ){
83305     for(i=0; i<pTab->nCol; i++){
83306       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
83307     }
83308   }
83309   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
83310     sqlite3ErrorMsg(pParse, 
83311        "table %S has %d columns but %d values were supplied",
83312        pTabList, 0, pTab->nCol-nHidden, nColumn);
83313     goto insert_cleanup;
83314   }
83315   if( pColumn!=0 && nColumn!=pColumn->nId ){
83316     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
83317     goto insert_cleanup;
83318   }
83319
83320   /* If the INSERT statement included an IDLIST term, then make sure
83321   ** all elements of the IDLIST really are columns of the table and 
83322   ** remember the column indices.
83323   **
83324   ** If the table has an INTEGER PRIMARY KEY column and that column
83325   ** is named in the IDLIST, then record in the keyColumn variable
83326   ** the index into IDLIST of the primary key column.  keyColumn is
83327   ** the index of the primary key as it appears in IDLIST, not as
83328   ** is appears in the original table.  (The index of the primary
83329   ** key in the original table is pTab->iPKey.)
83330   */
83331   if( pColumn ){
83332     for(i=0; i<pColumn->nId; i++){
83333       pColumn->a[i].idx = -1;
83334     }
83335     for(i=0; i<pColumn->nId; i++){
83336       for(j=0; j<pTab->nCol; j++){
83337         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
83338           pColumn->a[i].idx = j;
83339           if( j==pTab->iPKey ){
83340             keyColumn = i;
83341           }
83342           break;
83343         }
83344       }
83345       if( j>=pTab->nCol ){
83346         if( sqlite3IsRowid(pColumn->a[i].zName) ){
83347           keyColumn = i;
83348         }else{
83349           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
83350               pTabList, 0, pColumn->a[i].zName);
83351           pParse->checkSchema = 1;
83352           goto insert_cleanup;
83353         }
83354       }
83355     }
83356   }
83357
83358   /* If there is no IDLIST term but the table has an integer primary
83359   ** key, the set the keyColumn variable to the primary key column index
83360   ** in the original table definition.
83361   */
83362   if( pColumn==0 && nColumn>0 ){
83363     keyColumn = pTab->iPKey;
83364   }
83365     
83366   /* Initialize the count of rows to be inserted
83367   */
83368   if( db->flags & SQLITE_CountRows ){
83369     regRowCount = ++pParse->nMem;
83370     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
83371   }
83372
83373   /* If this is not a view, open the table and and all indices */
83374   if( !isView ){
83375     int nIdx;
83376
83377     baseCur = pParse->nTab;
83378     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
83379     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
83380     if( aRegIdx==0 ){
83381       goto insert_cleanup;
83382     }
83383     for(i=0; i<nIdx; i++){
83384       aRegIdx[i] = ++pParse->nMem;
83385     }
83386   }
83387
83388   /* This is the top of the main insertion loop */
83389   if( useTempTable ){
83390     /* This block codes the top of loop only.  The complete loop is the
83391     ** following pseudocode (template 4):
83392     **
83393     **         rewind temp table
83394     **      C: loop over rows of intermediate table
83395     **           transfer values form intermediate table into <table>
83396     **         end loop
83397     **      D: ...
83398     */
83399     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
83400     addrCont = sqlite3VdbeCurrentAddr(v);
83401   }else if( pSelect ){
83402     /* This block codes the top of loop only.  The complete loop is the
83403     ** following pseudocode (template 3):
83404     **
83405     **      C: yield X
83406     **         if EOF goto D
83407     **         insert the select result into <table> from R..R+n
83408     **         goto C
83409     **      D: ...
83410     */
83411     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
83412     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
83413   }
83414
83415   /* Allocate registers for holding the rowid of the new row,
83416   ** the content of the new row, and the assemblied row record.
83417   */
83418   regRecord = ++pParse->nMem;
83419   regRowid = regIns = pParse->nMem+1;
83420   pParse->nMem += pTab->nCol + 1;
83421   if( IsVirtual(pTab) ){
83422     regRowid++;
83423     pParse->nMem++;
83424   }
83425   regData = regRowid+1;
83426
83427   /* Run the BEFORE and INSTEAD OF triggers, if there are any
83428   */
83429   endOfLoop = sqlite3VdbeMakeLabel(v);
83430   if( tmask & TRIGGER_BEFORE ){
83431     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
83432
83433     /* build the NEW.* reference row.  Note that if there is an INTEGER
83434     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
83435     ** translated into a unique ID for the row.  But on a BEFORE trigger,
83436     ** we do not know what the unique ID will be (because the insert has
83437     ** not happened yet) so we substitute a rowid of -1
83438     */
83439     if( keyColumn<0 ){
83440       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
83441     }else{
83442       int j1;
83443       if( useTempTable ){
83444         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
83445       }else{
83446         assert( pSelect==0 );  /* Otherwise useTempTable is true */
83447         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
83448       }
83449       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
83450       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
83451       sqlite3VdbeJumpHere(v, j1);
83452       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
83453     }
83454
83455     /* Cannot have triggers on a virtual table. If it were possible,
83456     ** this block would have to account for hidden column.
83457     */
83458     assert( !IsVirtual(pTab) );
83459
83460     /* Create the new column data
83461     */
83462     for(i=0; i<pTab->nCol; i++){
83463       if( pColumn==0 ){
83464         j = i;
83465       }else{
83466         for(j=0; j<pColumn->nId; j++){
83467           if( pColumn->a[j].idx==i ) break;
83468         }
83469       }
83470       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
83471         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
83472       }else if( useTempTable ){
83473         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
83474       }else{
83475         assert( pSelect==0 ); /* Otherwise useTempTable is true */
83476         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
83477       }
83478     }
83479
83480     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
83481     ** do not attempt any conversions before assembling the record.
83482     ** If this is a real table, attempt conversions as required by the
83483     ** table column affinities.
83484     */
83485     if( !isView ){
83486       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
83487       sqlite3TableAffinityStr(v, pTab);
83488     }
83489
83490     /* Fire BEFORE or INSTEAD OF triggers */
83491     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
83492         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
83493
83494     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
83495   }
83496
83497   /* Push the record number for the new entry onto the stack.  The
83498   ** record number is a randomly generate integer created by NewRowid
83499   ** except when the table has an INTEGER PRIMARY KEY column, in which
83500   ** case the record number is the same as that column. 
83501   */
83502   if( !isView ){
83503     if( IsVirtual(pTab) ){
83504       /* The row that the VUpdate opcode will delete: none */
83505       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
83506     }
83507     if( keyColumn>=0 ){
83508       if( useTempTable ){
83509         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
83510       }else if( pSelect ){
83511         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
83512       }else{
83513         VdbeOp *pOp;
83514         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
83515         pOp = sqlite3VdbeGetOp(v, -1);
83516         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
83517           appendFlag = 1;
83518           pOp->opcode = OP_NewRowid;
83519           pOp->p1 = baseCur;
83520           pOp->p2 = regRowid;
83521           pOp->p3 = regAutoinc;
83522         }
83523       }
83524       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
83525       ** to generate a unique primary key value.
83526       */
83527       if( !appendFlag ){
83528         int j1;
83529         if( !IsVirtual(pTab) ){
83530           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
83531           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
83532           sqlite3VdbeJumpHere(v, j1);
83533         }else{
83534           j1 = sqlite3VdbeCurrentAddr(v);
83535           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
83536         }
83537         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
83538       }
83539     }else if( IsVirtual(pTab) ){
83540       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
83541     }else{
83542       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
83543       appendFlag = 1;
83544     }
83545     autoIncStep(pParse, regAutoinc, regRowid);
83546
83547     /* Push onto the stack, data for all columns of the new entry, beginning
83548     ** with the first column.
83549     */
83550     nHidden = 0;
83551     for(i=0; i<pTab->nCol; i++){
83552       int iRegStore = regRowid+1+i;
83553       if( i==pTab->iPKey ){
83554         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
83555         ** Whenever this column is read, the record number will be substituted
83556         ** in its place.  So will fill this column with a NULL to avoid
83557         ** taking up data space with information that will never be used. */
83558         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
83559         continue;
83560       }
83561       if( pColumn==0 ){
83562         if( IsHiddenColumn(&pTab->aCol[i]) ){
83563           assert( IsVirtual(pTab) );
83564           j = -1;
83565           nHidden++;
83566         }else{
83567           j = i - nHidden;
83568         }
83569       }else{
83570         for(j=0; j<pColumn->nId; j++){
83571           if( pColumn->a[j].idx==i ) break;
83572         }
83573       }
83574       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
83575         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
83576       }else if( useTempTable ){
83577         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
83578       }else if( pSelect ){
83579         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
83580       }else{
83581         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
83582       }
83583     }
83584
83585     /* Generate code to check constraints and generate index keys and
83586     ** do the insertion.
83587     */
83588 #ifndef SQLITE_OMIT_VIRTUALTABLE
83589     if( IsVirtual(pTab) ){
83590       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
83591       sqlite3VtabMakeWritable(pParse, pTab);
83592       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
83593       sqlite3MayAbort(pParse);
83594     }else
83595 #endif
83596     {
83597       int isReplace;    /* Set to true if constraints may cause a replace */
83598       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
83599           keyColumn>=0, 0, onError, endOfLoop, &isReplace
83600       );
83601       sqlite3FkCheck(pParse, pTab, 0, regIns);
83602       sqlite3CompleteInsertion(
83603           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
83604       );
83605     }
83606   }
83607
83608   /* Update the count of rows that are inserted
83609   */
83610   if( (db->flags & SQLITE_CountRows)!=0 ){
83611     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
83612   }
83613
83614   if( pTrigger ){
83615     /* Code AFTER triggers */
83616     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
83617         pTab, regData-2-pTab->nCol, onError, endOfLoop);
83618   }
83619
83620   /* The bottom of the main insertion loop, if the data source
83621   ** is a SELECT statement.
83622   */
83623   sqlite3VdbeResolveLabel(v, endOfLoop);
83624   if( useTempTable ){
83625     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
83626     sqlite3VdbeJumpHere(v, addrInsTop);
83627     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
83628   }else if( pSelect ){
83629     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
83630     sqlite3VdbeJumpHere(v, addrInsTop);
83631   }
83632
83633   if( !IsVirtual(pTab) && !isView ){
83634     /* Close all tables opened */
83635     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
83636     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
83637       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
83638     }
83639   }
83640
83641 insert_end:
83642   /* Update the sqlite_sequence table by storing the content of the
83643   ** maximum rowid counter values recorded while inserting into
83644   ** autoincrement tables.
83645   */
83646   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
83647     sqlite3AutoincrementEnd(pParse);
83648   }
83649
83650   /*
83651   ** Return the number of rows inserted. If this routine is 
83652   ** generating code because of a call to sqlite3NestedParse(), do not
83653   ** invoke the callback function.
83654   */
83655   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
83656     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
83657     sqlite3VdbeSetNumCols(v, 1);
83658     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
83659   }
83660
83661 insert_cleanup:
83662   sqlite3SrcListDelete(db, pTabList);
83663   sqlite3ExprListDelete(db, pList);
83664   sqlite3SelectDelete(db, pSelect);
83665   sqlite3IdListDelete(db, pColumn);
83666   sqlite3DbFree(db, aRegIdx);
83667 }
83668
83669 /* Make sure "isView" and other macros defined above are undefined. Otherwise
83670 ** thely may interfere with compilation of other functions in this file
83671 ** (or in another file, if this file becomes part of the amalgamation).  */
83672 #ifdef isView
83673  #undef isView
83674 #endif
83675 #ifdef pTrigger
83676  #undef pTrigger
83677 #endif
83678 #ifdef tmask
83679  #undef tmask
83680 #endif
83681
83682
83683 /*
83684 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
83685 **
83686 ** The input is a range of consecutive registers as follows:
83687 **
83688 **    1.  The rowid of the row after the update.
83689 **
83690 **    2.  The data in the first column of the entry after the update.
83691 **
83692 **    i.  Data from middle columns...
83693 **
83694 **    N.  The data in the last column of the entry after the update.
83695 **
83696 ** The regRowid parameter is the index of the register containing (1).
83697 **
83698 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
83699 ** the address of a register containing the rowid before the update takes
83700 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
83701 ** is false, indicating an INSERT statement, then a non-zero rowidChng 
83702 ** indicates that the rowid was explicitly specified as part of the
83703 ** INSERT statement. If rowidChng is false, it means that  the rowid is
83704 ** computed automatically in an insert or that the rowid value is not 
83705 ** modified by an update.
83706 **
83707 ** The code generated by this routine store new index entries into
83708 ** registers identified by aRegIdx[].  No index entry is created for
83709 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
83710 ** the same as the order of indices on the linked list of indices
83711 ** attached to the table.
83712 **
83713 ** This routine also generates code to check constraints.  NOT NULL,
83714 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
83715 ** then the appropriate action is performed.  There are five possible
83716 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
83717 **
83718 **  Constraint type  Action       What Happens
83719 **  ---------------  ----------   ----------------------------------------
83720 **  any              ROLLBACK     The current transaction is rolled back and
83721 **                                sqlite3_exec() returns immediately with a
83722 **                                return code of SQLITE_CONSTRAINT.
83723 **
83724 **  any              ABORT        Back out changes from the current command
83725 **                                only (do not do a complete rollback) then
83726 **                                cause sqlite3_exec() to return immediately
83727 **                                with SQLITE_CONSTRAINT.
83728 **
83729 **  any              FAIL         Sqlite_exec() returns immediately with a
83730 **                                return code of SQLITE_CONSTRAINT.  The
83731 **                                transaction is not rolled back and any
83732 **                                prior changes are retained.
83733 **
83734 **  any              IGNORE       The record number and data is popped from
83735 **                                the stack and there is an immediate jump
83736 **                                to label ignoreDest.
83737 **
83738 **  NOT NULL         REPLACE      The NULL value is replace by the default
83739 **                                value for that column.  If the default value
83740 **                                is NULL, the action is the same as ABORT.
83741 **
83742 **  UNIQUE           REPLACE      The other row that conflicts with the row
83743 **                                being inserted is removed.
83744 **
83745 **  CHECK            REPLACE      Illegal.  The results in an exception.
83746 **
83747 ** Which action to take is determined by the overrideError parameter.
83748 ** Or if overrideError==OE_Default, then the pParse->onError parameter
83749 ** is used.  Or if pParse->onError==OE_Default then the onError value
83750 ** for the constraint is used.
83751 **
83752 ** The calling routine must open a read/write cursor for pTab with
83753 ** cursor number "baseCur".  All indices of pTab must also have open
83754 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
83755 ** Except, if there is no possibility of a REPLACE action then
83756 ** cursors do not need to be open for indices where aRegIdx[i]==0.
83757 */
83758 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
83759   Parse *pParse,      /* The parser context */
83760   Table *pTab,        /* the table into which we are inserting */
83761   int baseCur,        /* Index of a read/write cursor pointing at pTab */
83762   int regRowid,       /* Index of the range of input registers */
83763   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
83764   int rowidChng,      /* True if the rowid might collide with existing entry */
83765   int isUpdate,       /* True for UPDATE, False for INSERT */
83766   int overrideError,  /* Override onError to this if not OE_Default */
83767   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
83768   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
83769 ){
83770   int i;              /* loop counter */
83771   Vdbe *v;            /* VDBE under constrution */
83772   int nCol;           /* Number of columns */
83773   int onError;        /* Conflict resolution strategy */
83774   int j1;             /* Addresss of jump instruction */
83775   int j2 = 0, j3;     /* Addresses of jump instructions */
83776   int regData;        /* Register containing first data column */
83777   int iCur;           /* Table cursor number */
83778   Index *pIdx;         /* Pointer to one of the indices */
83779   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
83780   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
83781
83782   v = sqlite3GetVdbe(pParse);
83783   assert( v!=0 );
83784   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
83785   nCol = pTab->nCol;
83786   regData = regRowid + 1;
83787
83788   /* Test all NOT NULL constraints.
83789   */
83790   for(i=0; i<nCol; i++){
83791     if( i==pTab->iPKey ){
83792       continue;
83793     }
83794     onError = pTab->aCol[i].notNull;
83795     if( onError==OE_None ) continue;
83796     if( overrideError!=OE_Default ){
83797       onError = overrideError;
83798     }else if( onError==OE_Default ){
83799       onError = OE_Abort;
83800     }
83801     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
83802       onError = OE_Abort;
83803     }
83804     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
83805         || onError==OE_Ignore || onError==OE_Replace );
83806     switch( onError ){
83807       case OE_Abort:
83808         sqlite3MayAbort(pParse);
83809       case OE_Rollback:
83810       case OE_Fail: {
83811         char *zMsg;
83812         j1 = sqlite3VdbeAddOp3(v, OP_HaltIfNull,
83813                                   SQLITE_CONSTRAINT, onError, regData+i);
83814         zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
83815                               pTab->zName, pTab->aCol[i].zName);
83816         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
83817         break;
83818       }
83819       case OE_Ignore: {
83820         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
83821         break;
83822       }
83823       default: {
83824         assert( onError==OE_Replace );
83825         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
83826         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
83827         sqlite3VdbeJumpHere(v, j1);
83828         break;
83829       }
83830     }
83831   }
83832
83833   /* Test all CHECK constraints
83834   */
83835 #ifndef SQLITE_OMIT_CHECK
83836   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
83837     int allOk = sqlite3VdbeMakeLabel(v);
83838     pParse->ckBase = regData;
83839     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
83840     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
83841     if( onError==OE_Ignore ){
83842       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
83843     }else{
83844       if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
83845       sqlite3HaltConstraint(pParse, onError, 0, 0);
83846     }
83847     sqlite3VdbeResolveLabel(v, allOk);
83848   }
83849 #endif /* !defined(SQLITE_OMIT_CHECK) */
83850
83851   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
83852   ** of the new record does not previously exist.  Except, if this
83853   ** is an UPDATE and the primary key is not changing, that is OK.
83854   */
83855   if( rowidChng ){
83856     onError = pTab->keyConf;
83857     if( overrideError!=OE_Default ){
83858       onError = overrideError;
83859     }else if( onError==OE_Default ){
83860       onError = OE_Abort;
83861     }
83862     
83863     if( isUpdate ){
83864       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
83865     }
83866     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
83867     switch( onError ){
83868       default: {
83869         onError = OE_Abort;
83870         /* Fall thru into the next case */
83871       }
83872       case OE_Rollback:
83873       case OE_Abort:
83874       case OE_Fail: {
83875         sqlite3HaltConstraint(
83876           pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
83877         break;
83878       }
83879       case OE_Replace: {
83880         /* If there are DELETE triggers on this table and the
83881         ** recursive-triggers flag is set, call GenerateRowDelete() to
83882         ** remove the conflicting row from the the table. This will fire
83883         ** the triggers and remove both the table and index b-tree entries.
83884         **
83885         ** Otherwise, if there are no triggers or the recursive-triggers
83886         ** flag is not set, but the table has one or more indexes, call 
83887         ** GenerateRowIndexDelete(). This removes the index b-tree entries 
83888         ** only. The table b-tree entry will be replaced by the new entry 
83889         ** when it is inserted.  
83890         **
83891         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
83892         ** also invoke MultiWrite() to indicate that this VDBE may require
83893         ** statement rollback (if the statement is aborted after the delete
83894         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
83895         ** but being more selective here allows statements like:
83896         **
83897         **   REPLACE INTO t(rowid) VALUES($newrowid)
83898         **
83899         ** to run without a statement journal if there are no indexes on the
83900         ** table.
83901         */
83902         Trigger *pTrigger = 0;
83903         if( pParse->db->flags&SQLITE_RecTriggers ){
83904           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
83905         }
83906         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
83907           sqlite3MultiWrite(pParse);
83908           sqlite3GenerateRowDelete(
83909               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
83910           );
83911         }else if( pTab->pIndex ){
83912           sqlite3MultiWrite(pParse);
83913           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
83914         }
83915         seenReplace = 1;
83916         break;
83917       }
83918       case OE_Ignore: {
83919         assert( seenReplace==0 );
83920         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
83921         break;
83922       }
83923     }
83924     sqlite3VdbeJumpHere(v, j3);
83925     if( isUpdate ){
83926       sqlite3VdbeJumpHere(v, j2);
83927     }
83928   }
83929
83930   /* Test all UNIQUE constraints by creating entries for each UNIQUE
83931   ** index and making sure that duplicate entries do not already exist.
83932   ** Add the new records to the indices as we go.
83933   */
83934   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
83935     int regIdx;
83936     int regR;
83937
83938     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
83939
83940     /* Create a key for accessing the index entry */
83941     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
83942     for(i=0; i<pIdx->nColumn; i++){
83943       int idx = pIdx->aiColumn[i];
83944       if( idx==pTab->iPKey ){
83945         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
83946       }else{
83947         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
83948       }
83949     }
83950     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
83951     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
83952     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
83953     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
83954
83955     /* Find out what action to take in case there is an indexing conflict */
83956     onError = pIdx->onError;
83957     if( onError==OE_None ){ 
83958       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
83959       continue;  /* pIdx is not a UNIQUE index */
83960     }
83961     if( overrideError!=OE_Default ){
83962       onError = overrideError;
83963     }else if( onError==OE_Default ){
83964       onError = OE_Abort;
83965     }
83966     if( seenReplace ){
83967       if( onError==OE_Ignore ) onError = OE_Replace;
83968       else if( onError==OE_Fail ) onError = OE_Abort;
83969     }
83970     
83971     /* Check to see if the new index entry will be unique */
83972     regR = sqlite3GetTempReg(pParse);
83973     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
83974     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
83975                            regR, SQLITE_INT_TO_PTR(regIdx),
83976                            P4_INT32);
83977     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
83978
83979     /* Generate code that executes if the new index entry is not unique */
83980     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
83981         || onError==OE_Ignore || onError==OE_Replace );
83982     switch( onError ){
83983       case OE_Rollback:
83984       case OE_Abort:
83985       case OE_Fail: {
83986         int j;
83987         StrAccum errMsg;
83988         const char *zSep;
83989         char *zErr;
83990
83991         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
83992         errMsg.db = pParse->db;
83993         zSep = pIdx->nColumn>1 ? "columns " : "column ";
83994         for(j=0; j<pIdx->nColumn; j++){
83995           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
83996           sqlite3StrAccumAppend(&errMsg, zSep, -1);
83997           zSep = ", ";
83998           sqlite3StrAccumAppend(&errMsg, zCol, -1);
83999         }
84000         sqlite3StrAccumAppend(&errMsg,
84001             pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
84002         zErr = sqlite3StrAccumFinish(&errMsg);
84003         sqlite3HaltConstraint(pParse, onError, zErr, 0);
84004         sqlite3DbFree(errMsg.db, zErr);
84005         break;
84006       }
84007       case OE_Ignore: {
84008         assert( seenReplace==0 );
84009         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
84010         break;
84011       }
84012       default: {
84013         Trigger *pTrigger = 0;
84014         assert( onError==OE_Replace );
84015         sqlite3MultiWrite(pParse);
84016         if( pParse->db->flags&SQLITE_RecTriggers ){
84017           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
84018         }
84019         sqlite3GenerateRowDelete(
84020             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
84021         );
84022         seenReplace = 1;
84023         break;
84024       }
84025     }
84026     sqlite3VdbeJumpHere(v, j3);
84027     sqlite3ReleaseTempReg(pParse, regR);
84028   }
84029   
84030   if( pbMayReplace ){
84031     *pbMayReplace = seenReplace;
84032   }
84033 }
84034
84035 /*
84036 ** This routine generates code to finish the INSERT or UPDATE operation
84037 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
84038 ** A consecutive range of registers starting at regRowid contains the
84039 ** rowid and the content to be inserted.
84040 **
84041 ** The arguments to this routine should be the same as the first six
84042 ** arguments to sqlite3GenerateConstraintChecks.
84043 */
84044 SQLITE_PRIVATE void sqlite3CompleteInsertion(
84045   Parse *pParse,      /* The parser context */
84046   Table *pTab,        /* the table into which we are inserting */
84047   int baseCur,        /* Index of a read/write cursor pointing at pTab */
84048   int regRowid,       /* Range of content */
84049   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
84050   int isUpdate,       /* True for UPDATE, False for INSERT */
84051   int appendBias,     /* True if this is likely to be an append */
84052   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
84053 ){
84054   int i;
84055   Vdbe *v;
84056   int nIdx;
84057   Index *pIdx;
84058   u8 pik_flags;
84059   int regData;
84060   int regRec;
84061
84062   v = sqlite3GetVdbe(pParse);
84063   assert( v!=0 );
84064   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
84065   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
84066   for(i=nIdx-1; i>=0; i--){
84067     if( aRegIdx[i]==0 ) continue;
84068     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
84069     if( useSeekResult ){
84070       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
84071     }
84072   }
84073   regData = regRowid + 1;
84074   regRec = sqlite3GetTempReg(pParse);
84075   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
84076   sqlite3TableAffinityStr(v, pTab);
84077   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
84078   if( pParse->nested ){
84079     pik_flags = 0;
84080   }else{
84081     pik_flags = OPFLAG_NCHANGE;
84082     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
84083   }
84084   if( appendBias ){
84085     pik_flags |= OPFLAG_APPEND;
84086   }
84087   if( useSeekResult ){
84088     pik_flags |= OPFLAG_USESEEKRESULT;
84089   }
84090   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
84091   if( !pParse->nested ){
84092     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
84093   }
84094   sqlite3VdbeChangeP5(v, pik_flags);
84095 }
84096
84097 /*
84098 ** Generate code that will open cursors for a table and for all
84099 ** indices of that table.  The "baseCur" parameter is the cursor number used
84100 ** for the table.  Indices are opened on subsequent cursors.
84101 **
84102 ** Return the number of indices on the table.
84103 */
84104 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
84105   Parse *pParse,   /* Parsing context */
84106   Table *pTab,     /* Table to be opened */
84107   int baseCur,     /* Cursor number assigned to the table */
84108   int op           /* OP_OpenRead or OP_OpenWrite */
84109 ){
84110   int i;
84111   int iDb;
84112   Index *pIdx;
84113   Vdbe *v;
84114
84115   if( IsVirtual(pTab) ) return 0;
84116   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
84117   v = sqlite3GetVdbe(pParse);
84118   assert( v!=0 );
84119   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
84120   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
84121     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
84122     assert( pIdx->pSchema==pTab->pSchema );
84123     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
84124                       (char*)pKey, P4_KEYINFO_HANDOFF);
84125     VdbeComment((v, "%s", pIdx->zName));
84126   }
84127   if( pParse->nTab<baseCur+i ){
84128     pParse->nTab = baseCur+i;
84129   }
84130   return i-1;
84131 }
84132
84133
84134 #ifdef SQLITE_TEST
84135 /*
84136 ** The following global variable is incremented whenever the
84137 ** transfer optimization is used.  This is used for testing
84138 ** purposes only - to make sure the transfer optimization really
84139 ** is happening when it is suppose to.
84140 */
84141 SQLITE_API int sqlite3_xferopt_count;
84142 #endif /* SQLITE_TEST */
84143
84144
84145 #ifndef SQLITE_OMIT_XFER_OPT
84146 /*
84147 ** Check to collation names to see if they are compatible.
84148 */
84149 static int xferCompatibleCollation(const char *z1, const char *z2){
84150   if( z1==0 ){
84151     return z2==0;
84152   }
84153   if( z2==0 ){
84154     return 0;
84155   }
84156   return sqlite3StrICmp(z1, z2)==0;
84157 }
84158
84159
84160 /*
84161 ** Check to see if index pSrc is compatible as a source of data
84162 ** for index pDest in an insert transfer optimization.  The rules
84163 ** for a compatible index:
84164 **
84165 **    *   The index is over the same set of columns
84166 **    *   The same DESC and ASC markings occurs on all columns
84167 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
84168 **    *   The same collating sequence on each column
84169 */
84170 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
84171   int i;
84172   assert( pDest && pSrc );
84173   assert( pDest->pTable!=pSrc->pTable );
84174   if( pDest->nColumn!=pSrc->nColumn ){
84175     return 0;   /* Different number of columns */
84176   }
84177   if( pDest->onError!=pSrc->onError ){
84178     return 0;   /* Different conflict resolution strategies */
84179   }
84180   for(i=0; i<pSrc->nColumn; i++){
84181     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
84182       return 0;   /* Different columns indexed */
84183     }
84184     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
84185       return 0;   /* Different sort orders */
84186     }
84187     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
84188       return 0;   /* Different collating sequences */
84189     }
84190   }
84191
84192   /* If no test above fails then the indices must be compatible */
84193   return 1;
84194 }
84195
84196 /*
84197 ** Attempt the transfer optimization on INSERTs of the form
84198 **
84199 **     INSERT INTO tab1 SELECT * FROM tab2;
84200 **
84201 ** This optimization is only attempted if
84202 **
84203 **    (1)  tab1 and tab2 have identical schemas including all the
84204 **         same indices and constraints
84205 **
84206 **    (2)  tab1 and tab2 are different tables
84207 **
84208 **    (3)  There must be no triggers on tab1
84209 **
84210 **    (4)  The result set of the SELECT statement is "*"
84211 **
84212 **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
84213 **         or LIMIT clause.
84214 **
84215 **    (6)  The SELECT statement is a simple (not a compound) select that
84216 **         contains only tab2 in its FROM clause
84217 **
84218 ** This method for implementing the INSERT transfers raw records from
84219 ** tab2 over to tab1.  The columns are not decoded.  Raw records from
84220 ** the indices of tab2 are transfered to tab1 as well.  In so doing,
84221 ** the resulting tab1 has much less fragmentation.
84222 **
84223 ** This routine returns TRUE if the optimization is attempted.  If any
84224 ** of the conditions above fail so that the optimization should not
84225 ** be attempted, then this routine returns FALSE.
84226 */
84227 static int xferOptimization(
84228   Parse *pParse,        /* Parser context */
84229   Table *pDest,         /* The table we are inserting into */
84230   Select *pSelect,      /* A SELECT statement to use as the data source */
84231   int onError,          /* How to handle constraint errors */
84232   int iDbDest           /* The database of pDest */
84233 ){
84234   ExprList *pEList;                /* The result set of the SELECT */
84235   Table *pSrc;                     /* The table in the FROM clause of SELECT */
84236   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
84237   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
84238   int i;                           /* Loop counter */
84239   int iDbSrc;                      /* The database of pSrc */
84240   int iSrc, iDest;                 /* Cursors from source and destination */
84241   int addr1, addr2;                /* Loop addresses */
84242   int emptyDestTest;               /* Address of test for empty pDest */
84243   int emptySrcTest;                /* Address of test for empty pSrc */
84244   Vdbe *v;                         /* The VDBE we are building */
84245   KeyInfo *pKey;                   /* Key information for an index */
84246   int regAutoinc;                  /* Memory register used by AUTOINC */
84247   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
84248   int regData, regRowid;           /* Registers holding data and rowid */
84249
84250   if( pSelect==0 ){
84251     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
84252   }
84253   if( sqlite3TriggerList(pParse, pDest) ){
84254     return 0;   /* tab1 must not have triggers */
84255   }
84256 #ifndef SQLITE_OMIT_VIRTUALTABLE
84257   if( pDest->tabFlags & TF_Virtual ){
84258     return 0;   /* tab1 must not be a virtual table */
84259   }
84260 #endif
84261   if( onError==OE_Default ){
84262     onError = OE_Abort;
84263   }
84264   if( onError!=OE_Abort && onError!=OE_Rollback ){
84265     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
84266   }
84267   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
84268   if( pSelect->pSrc->nSrc!=1 ){
84269     return 0;   /* FROM clause must have exactly one term */
84270   }
84271   if( pSelect->pSrc->a[0].pSelect ){
84272     return 0;   /* FROM clause cannot contain a subquery */
84273   }
84274   if( pSelect->pWhere ){
84275     return 0;   /* SELECT may not have a WHERE clause */
84276   }
84277   if( pSelect->pOrderBy ){
84278     return 0;   /* SELECT may not have an ORDER BY clause */
84279   }
84280   /* Do not need to test for a HAVING clause.  If HAVING is present but
84281   ** there is no ORDER BY, we will get an error. */
84282   if( pSelect->pGroupBy ){
84283     return 0;   /* SELECT may not have a GROUP BY clause */
84284   }
84285   if( pSelect->pLimit ){
84286     return 0;   /* SELECT may not have a LIMIT clause */
84287   }
84288   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
84289   if( pSelect->pPrior ){
84290     return 0;   /* SELECT may not be a compound query */
84291   }
84292   if( pSelect->selFlags & SF_Distinct ){
84293     return 0;   /* SELECT may not be DISTINCT */
84294   }
84295   pEList = pSelect->pEList;
84296   assert( pEList!=0 );
84297   if( pEList->nExpr!=1 ){
84298     return 0;   /* The result set must have exactly one column */
84299   }
84300   assert( pEList->a[0].pExpr );
84301   if( pEList->a[0].pExpr->op!=TK_ALL ){
84302     return 0;   /* The result set must be the special operator "*" */
84303   }
84304
84305   /* At this point we have established that the statement is of the
84306   ** correct syntactic form to participate in this optimization.  Now
84307   ** we have to check the semantics.
84308   */
84309   pItem = pSelect->pSrc->a;
84310   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
84311   if( pSrc==0 ){
84312     return 0;   /* FROM clause does not contain a real table */
84313   }
84314   if( pSrc==pDest ){
84315     return 0;   /* tab1 and tab2 may not be the same table */
84316   }
84317 #ifndef SQLITE_OMIT_VIRTUALTABLE
84318   if( pSrc->tabFlags & TF_Virtual ){
84319     return 0;   /* tab2 must not be a virtual table */
84320   }
84321 #endif
84322   if( pSrc->pSelect ){
84323     return 0;   /* tab2 may not be a view */
84324   }
84325   if( pDest->nCol!=pSrc->nCol ){
84326     return 0;   /* Number of columns must be the same in tab1 and tab2 */
84327   }
84328   if( pDest->iPKey!=pSrc->iPKey ){
84329     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
84330   }
84331   for(i=0; i<pDest->nCol; i++){
84332     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
84333       return 0;    /* Affinity must be the same on all columns */
84334     }
84335     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
84336       return 0;    /* Collating sequence must be the same on all columns */
84337     }
84338     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
84339       return 0;    /* tab2 must be NOT NULL if tab1 is */
84340     }
84341   }
84342   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
84343     if( pDestIdx->onError!=OE_None ){
84344       destHasUniqueIdx = 1;
84345     }
84346     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
84347       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
84348     }
84349     if( pSrcIdx==0 ){
84350       return 0;    /* pDestIdx has no corresponding index in pSrc */
84351     }
84352   }
84353 #ifndef SQLITE_OMIT_CHECK
84354   if( pDest->pCheck && sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
84355     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
84356   }
84357 #endif
84358
84359   /* If we get this far, it means either:
84360   **
84361   **    *   We can always do the transfer if the table contains an
84362   **        an integer primary key
84363   **
84364   **    *   We can conditionally do the transfer if the destination
84365   **        table is empty.
84366   */
84367 #ifdef SQLITE_TEST
84368   sqlite3_xferopt_count++;
84369 #endif
84370   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
84371   v = sqlite3GetVdbe(pParse);
84372   sqlite3CodeVerifySchema(pParse, iDbSrc);
84373   iSrc = pParse->nTab++;
84374   iDest = pParse->nTab++;
84375   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
84376   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
84377   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
84378     /* If tables do not have an INTEGER PRIMARY KEY and there
84379     ** are indices to be copied and the destination is not empty,
84380     ** we have to disallow the transfer optimization because the
84381     ** the rowids might change which will mess up indexing.
84382     **
84383     ** Or if the destination has a UNIQUE index and is not empty,
84384     ** we also disallow the transfer optimization because we cannot
84385     ** insure that all entries in the union of DEST and SRC will be
84386     ** unique.
84387     */
84388     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
84389     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
84390     sqlite3VdbeJumpHere(v, addr1);
84391   }else{
84392     emptyDestTest = 0;
84393   }
84394   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
84395   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
84396   regData = sqlite3GetTempReg(pParse);
84397   regRowid = sqlite3GetTempReg(pParse);
84398   if( pDest->iPKey>=0 ){
84399     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
84400     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
84401     sqlite3HaltConstraint(
84402         pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
84403     sqlite3VdbeJumpHere(v, addr2);
84404     autoIncStep(pParse, regAutoinc, regRowid);
84405   }else if( pDest->pIndex==0 ){
84406     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
84407   }else{
84408     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
84409     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
84410   }
84411   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
84412   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
84413   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
84414   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
84415   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
84416   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
84417     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
84418       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
84419     }
84420     assert( pSrcIdx );
84421     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
84422     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
84423     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
84424     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
84425                       (char*)pKey, P4_KEYINFO_HANDOFF);
84426     VdbeComment((v, "%s", pSrcIdx->zName));
84427     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
84428     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
84429                       (char*)pKey, P4_KEYINFO_HANDOFF);
84430     VdbeComment((v, "%s", pDestIdx->zName));
84431     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
84432     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
84433     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
84434     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
84435     sqlite3VdbeJumpHere(v, addr1);
84436   }
84437   sqlite3VdbeJumpHere(v, emptySrcTest);
84438   sqlite3ReleaseTempReg(pParse, regRowid);
84439   sqlite3ReleaseTempReg(pParse, regData);
84440   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
84441   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
84442   if( emptyDestTest ){
84443     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
84444     sqlite3VdbeJumpHere(v, emptyDestTest);
84445     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
84446     return 0;
84447   }else{
84448     return 1;
84449   }
84450 }
84451 #endif /* SQLITE_OMIT_XFER_OPT */
84452
84453 /************** End of insert.c **********************************************/
84454 /************** Begin file legacy.c ******************************************/
84455 /*
84456 ** 2001 September 15
84457 **
84458 ** The author disclaims copyright to this source code.  In place of
84459 ** a legal notice, here is a blessing:
84460 **
84461 **    May you do good and not evil.
84462 **    May you find forgiveness for yourself and forgive others.
84463 **    May you share freely, never taking more than you give.
84464 **
84465 *************************************************************************
84466 ** Main file for the SQLite library.  The routines in this file
84467 ** implement the programmer interface to the library.  Routines in
84468 ** other files are for internal use by SQLite and should not be
84469 ** accessed by users of the library.
84470 */
84471
84472
84473 /*
84474 ** Execute SQL code.  Return one of the SQLITE_ success/failure
84475 ** codes.  Also write an error message into memory obtained from
84476 ** malloc() and make *pzErrMsg point to that message.
84477 **
84478 ** If the SQL is a query, then for each row in the query result
84479 ** the xCallback() function is called.  pArg becomes the first
84480 ** argument to xCallback().  If xCallback=NULL then no callback
84481 ** is invoked, even for queries.
84482 */
84483 SQLITE_API int sqlite3_exec(
84484   sqlite3 *db,                /* The database on which the SQL executes */
84485   const char *zSql,           /* The SQL to be executed */
84486   sqlite3_callback xCallback, /* Invoke this callback routine */
84487   void *pArg,                 /* First argument to xCallback() */
84488   char **pzErrMsg             /* Write error messages here */
84489 ){
84490   int rc = SQLITE_OK;         /* Return code */
84491   const char *zLeftover;      /* Tail of unprocessed SQL */
84492   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
84493   char **azCols = 0;          /* Names of result columns */
84494   int nRetry = 0;             /* Number of retry attempts */
84495   int callbackIsInit;         /* True if callback data is initialized */
84496
84497   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
84498   if( zSql==0 ) zSql = "";
84499
84500   sqlite3_mutex_enter(db->mutex);
84501   sqlite3Error(db, SQLITE_OK, 0);
84502   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
84503     int nCol;
84504     char **azVals = 0;
84505
84506     pStmt = 0;
84507     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
84508     assert( rc==SQLITE_OK || pStmt==0 );
84509     if( rc!=SQLITE_OK ){
84510       continue;
84511     }
84512     if( !pStmt ){
84513       /* this happens for a comment or white-space */
84514       zSql = zLeftover;
84515       continue;
84516     }
84517
84518     callbackIsInit = 0;
84519     nCol = sqlite3_column_count(pStmt);
84520
84521     while( 1 ){
84522       int i;
84523       rc = sqlite3_step(pStmt);
84524
84525       /* Invoke the callback function if required */
84526       if( xCallback && (SQLITE_ROW==rc || 
84527           (SQLITE_DONE==rc && !callbackIsInit
84528                            && db->flags&SQLITE_NullCallback)) ){
84529         if( !callbackIsInit ){
84530           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
84531           if( azCols==0 ){
84532             goto exec_out;
84533           }
84534           for(i=0; i<nCol; i++){
84535             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
84536             /* sqlite3VdbeSetColName() installs column names as UTF8
84537             ** strings so there is no way for sqlite3_column_name() to fail. */
84538             assert( azCols[i]!=0 );
84539           }
84540           callbackIsInit = 1;
84541         }
84542         if( rc==SQLITE_ROW ){
84543           azVals = &azCols[nCol];
84544           for(i=0; i<nCol; i++){
84545             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
84546             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
84547               db->mallocFailed = 1;
84548               goto exec_out;
84549             }
84550           }
84551         }
84552         if( xCallback(pArg, nCol, azVals, azCols) ){
84553           rc = SQLITE_ABORT;
84554           sqlite3VdbeFinalize((Vdbe *)pStmt);
84555           pStmt = 0;
84556           sqlite3Error(db, SQLITE_ABORT, 0);
84557           goto exec_out;
84558         }
84559       }
84560
84561       if( rc!=SQLITE_ROW ){
84562         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
84563         pStmt = 0;
84564         if( rc!=SQLITE_SCHEMA ){
84565           nRetry = 0;
84566           zSql = zLeftover;
84567           while( sqlite3Isspace(zSql[0]) ) zSql++;
84568         }
84569         break;
84570       }
84571     }
84572
84573     sqlite3DbFree(db, azCols);
84574     azCols = 0;
84575   }
84576
84577 exec_out:
84578   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
84579   sqlite3DbFree(db, azCols);
84580
84581   rc = sqlite3ApiExit(db, rc);
84582   if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
84583     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
84584     *pzErrMsg = sqlite3Malloc(nErrMsg);
84585     if( *pzErrMsg ){
84586       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
84587     }else{
84588       rc = SQLITE_NOMEM;
84589       sqlite3Error(db, SQLITE_NOMEM, 0);
84590     }
84591   }else if( pzErrMsg ){
84592     *pzErrMsg = 0;
84593   }
84594
84595   assert( (rc&db->errMask)==rc );
84596   sqlite3_mutex_leave(db->mutex);
84597   return rc;
84598 }
84599
84600 /************** End of legacy.c **********************************************/
84601 /************** Begin file loadext.c *****************************************/
84602 /*
84603 ** 2006 June 7
84604 **
84605 ** The author disclaims copyright to this source code.  In place of
84606 ** a legal notice, here is a blessing:
84607 **
84608 **    May you do good and not evil.
84609 **    May you find forgiveness for yourself and forgive others.
84610 **    May you share freely, never taking more than you give.
84611 **
84612 *************************************************************************
84613 ** This file contains code used to dynamically load extensions into
84614 ** the SQLite library.
84615 */
84616
84617 #ifndef SQLITE_CORE
84618   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
84619 #endif
84620 /************** Include sqlite3ext.h in the middle of loadext.c **************/
84621 /************** Begin file sqlite3ext.h **************************************/
84622 /*
84623 ** 2006 June 7
84624 **
84625 ** The author disclaims copyright to this source code.  In place of
84626 ** a legal notice, here is a blessing:
84627 **
84628 **    May you do good and not evil.
84629 **    May you find forgiveness for yourself and forgive others.
84630 **    May you share freely, never taking more than you give.
84631 **
84632 *************************************************************************
84633 ** This header file defines the SQLite interface for use by
84634 ** shared libraries that want to be imported as extensions into
84635 ** an SQLite instance.  Shared libraries that intend to be loaded
84636 ** as extensions by SQLite should #include this file instead of 
84637 ** sqlite3.h.
84638 */
84639 #ifndef _SQLITE3EXT_H_
84640 #define _SQLITE3EXT_H_
84641
84642 typedef struct sqlite3_api_routines sqlite3_api_routines;
84643
84644 /*
84645 ** The following structure holds pointers to all of the SQLite API
84646 ** routines.
84647 **
84648 ** WARNING:  In order to maintain backwards compatibility, add new
84649 ** interfaces to the end of this structure only.  If you insert new
84650 ** interfaces in the middle of this structure, then older different
84651 ** versions of SQLite will not be able to load each others' shared
84652 ** libraries!
84653 */
84654 struct sqlite3_api_routines {
84655   void * (*aggregate_context)(sqlite3_context*,int nBytes);
84656   int  (*aggregate_count)(sqlite3_context*);
84657   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
84658   int  (*bind_double)(sqlite3_stmt*,int,double);
84659   int  (*bind_int)(sqlite3_stmt*,int,int);
84660   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
84661   int  (*bind_null)(sqlite3_stmt*,int);
84662   int  (*bind_parameter_count)(sqlite3_stmt*);
84663   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
84664   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
84665   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
84666   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
84667   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
84668   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
84669   int  (*busy_timeout)(sqlite3*,int ms);
84670   int  (*changes)(sqlite3*);
84671   int  (*close)(sqlite3*);
84672   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
84673   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
84674   const void * (*column_blob)(sqlite3_stmt*,int iCol);
84675   int  (*column_bytes)(sqlite3_stmt*,int iCol);
84676   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
84677   int  (*column_count)(sqlite3_stmt*pStmt);
84678   const char * (*column_database_name)(sqlite3_stmt*,int);
84679   const void * (*column_database_name16)(sqlite3_stmt*,int);
84680   const char * (*column_decltype)(sqlite3_stmt*,int i);
84681   const void * (*column_decltype16)(sqlite3_stmt*,int);
84682   double  (*column_double)(sqlite3_stmt*,int iCol);
84683   int  (*column_int)(sqlite3_stmt*,int iCol);
84684   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
84685   const char * (*column_name)(sqlite3_stmt*,int);
84686   const void * (*column_name16)(sqlite3_stmt*,int);
84687   const char * (*column_origin_name)(sqlite3_stmt*,int);
84688   const void * (*column_origin_name16)(sqlite3_stmt*,int);
84689   const char * (*column_table_name)(sqlite3_stmt*,int);
84690   const void * (*column_table_name16)(sqlite3_stmt*,int);
84691   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
84692   const void * (*column_text16)(sqlite3_stmt*,int iCol);
84693   int  (*column_type)(sqlite3_stmt*,int iCol);
84694   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
84695   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
84696   int  (*complete)(const char*sql);
84697   int  (*complete16)(const void*sql);
84698   int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
84699   int  (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
84700   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*));
84701   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*));
84702   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
84703   int  (*data_count)(sqlite3_stmt*pStmt);
84704   sqlite3 * (*db_handle)(sqlite3_stmt*);
84705   int (*declare_vtab)(sqlite3*,const char*);
84706   int  (*enable_shared_cache)(int);
84707   int  (*errcode)(sqlite3*db);
84708   const char * (*errmsg)(sqlite3*);
84709   const void * (*errmsg16)(sqlite3*);
84710   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
84711   int  (*expired)(sqlite3_stmt*);
84712   int  (*finalize)(sqlite3_stmt*pStmt);
84713   void  (*free)(void*);
84714   void  (*free_table)(char**result);
84715   int  (*get_autocommit)(sqlite3*);
84716   void * (*get_auxdata)(sqlite3_context*,int);
84717   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
84718   int  (*global_recover)(void);
84719   void  (*interruptx)(sqlite3*);
84720   sqlite_int64  (*last_insert_rowid)(sqlite3*);
84721   const char * (*libversion)(void);
84722   int  (*libversion_number)(void);
84723   void *(*malloc)(int);
84724   char * (*mprintf)(const char*,...);
84725   int  (*open)(const char*,sqlite3**);
84726   int  (*open16)(const void*,sqlite3**);
84727   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
84728   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
84729   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
84730   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
84731   void *(*realloc)(void*,int);
84732   int  (*reset)(sqlite3_stmt*pStmt);
84733   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
84734   void  (*result_double)(sqlite3_context*,double);
84735   void  (*result_error)(sqlite3_context*,const char*,int);
84736   void  (*result_error16)(sqlite3_context*,const void*,int);
84737   void  (*result_int)(sqlite3_context*,int);
84738   void  (*result_int64)(sqlite3_context*,sqlite_int64);
84739   void  (*result_null)(sqlite3_context*);
84740   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
84741   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
84742   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
84743   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
84744   void  (*result_value)(sqlite3_context*,sqlite3_value*);
84745   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
84746   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
84747   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
84748   char * (*snprintf)(int,char*,const char*,...);
84749   int  (*step)(sqlite3_stmt*);
84750   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
84751   void  (*thread_cleanup)(void);
84752   int  (*total_changes)(sqlite3*);
84753   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
84754   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
84755   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
84756   void * (*user_data)(sqlite3_context*);
84757   const void * (*value_blob)(sqlite3_value*);
84758   int  (*value_bytes)(sqlite3_value*);
84759   int  (*value_bytes16)(sqlite3_value*);
84760   double  (*value_double)(sqlite3_value*);
84761   int  (*value_int)(sqlite3_value*);
84762   sqlite_int64  (*value_int64)(sqlite3_value*);
84763   int  (*value_numeric_type)(sqlite3_value*);
84764   const unsigned char * (*value_text)(sqlite3_value*);
84765   const void * (*value_text16)(sqlite3_value*);
84766   const void * (*value_text16be)(sqlite3_value*);
84767   const void * (*value_text16le)(sqlite3_value*);
84768   int  (*value_type)(sqlite3_value*);
84769   char *(*vmprintf)(const char*,va_list);
84770   /* Added ??? */
84771   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
84772   /* Added by 3.3.13 */
84773   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
84774   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
84775   int (*clear_bindings)(sqlite3_stmt*);
84776   /* Added by 3.4.1 */
84777   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
84778   /* Added by 3.5.0 */
84779   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
84780   int (*blob_bytes)(sqlite3_blob*);
84781   int (*blob_close)(sqlite3_blob*);
84782   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
84783   int (*blob_read)(sqlite3_blob*,void*,int,int);
84784   int (*blob_write)(sqlite3_blob*,const void*,int,int);
84785   int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
84786   int (*file_control)(sqlite3*,const char*,int,void*);
84787   sqlite3_int64 (*memory_highwater)(int);
84788   sqlite3_int64 (*memory_used)(void);
84789   sqlite3_mutex *(*mutex_alloc)(int);
84790   void (*mutex_enter)(sqlite3_mutex*);
84791   void (*mutex_free)(sqlite3_mutex*);
84792   void (*mutex_leave)(sqlite3_mutex*);
84793   int (*mutex_try)(sqlite3_mutex*);
84794   int (*open_v2)(const char*,sqlite3**,int,const char*);
84795   int (*release_memory)(int);
84796   void (*result_error_nomem)(sqlite3_context*);
84797   void (*result_error_toobig)(sqlite3_context*);
84798   int (*sleep)(int);
84799   void (*soft_heap_limit)(int);
84800   sqlite3_vfs *(*vfs_find)(const char*);
84801   int (*vfs_register)(sqlite3_vfs*,int);
84802   int (*vfs_unregister)(sqlite3_vfs*);
84803   int (*xthreadsafe)(void);
84804   void (*result_zeroblob)(sqlite3_context*,int);
84805   void (*result_error_code)(sqlite3_context*,int);
84806   int (*test_control)(int, ...);
84807   void (*randomness)(int,void*);
84808   sqlite3 *(*context_db_handle)(sqlite3_context*);
84809   int (*extended_result_codes)(sqlite3*,int);
84810   int (*limit)(sqlite3*,int,int);
84811   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
84812   const char *(*sql)(sqlite3_stmt*);
84813   int (*status)(int,int*,int*,int);
84814   int (*backup_finish)(sqlite3_backup*);
84815   sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
84816   int (*backup_pagecount)(sqlite3_backup*);
84817   int (*backup_remaining)(sqlite3_backup*);
84818   int (*backup_step)(sqlite3_backup*,int);
84819   const char *(*compileoption_get)(int);
84820   int (*compileoption_used)(const char*);
84821   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*));
84822   int (*db_config)(sqlite3*,int,...);
84823   sqlite3_mutex *(*db_mutex)(sqlite3*);
84824   int (*db_status)(sqlite3*,int,int*,int*,int);
84825   int (*extended_errcode)(sqlite3*);
84826   void (*log)(int,const char*,...);
84827   sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
84828   const char *(*sourceid)(void);
84829   int (*stmt_status)(sqlite3_stmt*,int,int);
84830   int (*strnicmp)(const char*,const char*,int);
84831   int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
84832   int (*wal_autocheckpoint)(sqlite3*,int);
84833   int (*wal_checkpoint)(sqlite3*,const char*);
84834   void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
84835 };
84836
84837 /*
84838 ** The following macros redefine the API routines so that they are
84839 ** redirected throught the global sqlite3_api structure.
84840 **
84841 ** This header file is also used by the loadext.c source file
84842 ** (part of the main SQLite library - not an extension) so that
84843 ** it can get access to the sqlite3_api_routines structure
84844 ** definition.  But the main library does not want to redefine
84845 ** the API.  So the redefinition macros are only valid if the
84846 ** SQLITE_CORE macros is undefined.
84847 */
84848 #ifndef SQLITE_CORE
84849 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
84850 #ifndef SQLITE_OMIT_DEPRECATED
84851 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
84852 #endif
84853 #define sqlite3_bind_blob              sqlite3_api->bind_blob
84854 #define sqlite3_bind_double            sqlite3_api->bind_double
84855 #define sqlite3_bind_int               sqlite3_api->bind_int
84856 #define sqlite3_bind_int64             sqlite3_api->bind_int64
84857 #define sqlite3_bind_null              sqlite3_api->bind_null
84858 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
84859 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
84860 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
84861 #define sqlite3_bind_text              sqlite3_api->bind_text
84862 #define sqlite3_bind_text16            sqlite3_api->bind_text16
84863 #define sqlite3_bind_value             sqlite3_api->bind_value
84864 #define sqlite3_busy_handler           sqlite3_api->busy_handler
84865 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
84866 #define sqlite3_changes                sqlite3_api->changes
84867 #define sqlite3_close                  sqlite3_api->close
84868 #define sqlite3_collation_needed       sqlite3_api->collation_needed
84869 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
84870 #define sqlite3_column_blob            sqlite3_api->column_blob
84871 #define sqlite3_column_bytes           sqlite3_api->column_bytes
84872 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
84873 #define sqlite3_column_count           sqlite3_api->column_count
84874 #define sqlite3_column_database_name   sqlite3_api->column_database_name
84875 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
84876 #define sqlite3_column_decltype        sqlite3_api->column_decltype
84877 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
84878 #define sqlite3_column_double          sqlite3_api->column_double
84879 #define sqlite3_column_int             sqlite3_api->column_int
84880 #define sqlite3_column_int64           sqlite3_api->column_int64
84881 #define sqlite3_column_name            sqlite3_api->column_name
84882 #define sqlite3_column_name16          sqlite3_api->column_name16
84883 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
84884 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
84885 #define sqlite3_column_table_name      sqlite3_api->column_table_name
84886 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
84887 #define sqlite3_column_text            sqlite3_api->column_text
84888 #define sqlite3_column_text16          sqlite3_api->column_text16
84889 #define sqlite3_column_type            sqlite3_api->column_type
84890 #define sqlite3_column_value           sqlite3_api->column_value
84891 #define sqlite3_commit_hook            sqlite3_api->commit_hook
84892 #define sqlite3_complete               sqlite3_api->complete
84893 #define sqlite3_complete16             sqlite3_api->complete16
84894 #define sqlite3_create_collation       sqlite3_api->create_collation
84895 #define sqlite3_create_collation16     sqlite3_api->create_collation16
84896 #define sqlite3_create_function        sqlite3_api->create_function
84897 #define sqlite3_create_function16      sqlite3_api->create_function16
84898 #define sqlite3_create_module          sqlite3_api->create_module
84899 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
84900 #define sqlite3_data_count             sqlite3_api->data_count
84901 #define sqlite3_db_handle              sqlite3_api->db_handle
84902 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
84903 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
84904 #define sqlite3_errcode                sqlite3_api->errcode
84905 #define sqlite3_errmsg                 sqlite3_api->errmsg
84906 #define sqlite3_errmsg16               sqlite3_api->errmsg16
84907 #define sqlite3_exec                   sqlite3_api->exec
84908 #ifndef SQLITE_OMIT_DEPRECATED
84909 #define sqlite3_expired                sqlite3_api->expired
84910 #endif
84911 #define sqlite3_finalize               sqlite3_api->finalize
84912 #define sqlite3_free                   sqlite3_api->free
84913 #define sqlite3_free_table             sqlite3_api->free_table
84914 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
84915 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
84916 #define sqlite3_get_table              sqlite3_api->get_table
84917 #ifndef SQLITE_OMIT_DEPRECATED
84918 #define sqlite3_global_recover         sqlite3_api->global_recover
84919 #endif
84920 #define sqlite3_interrupt              sqlite3_api->interruptx
84921 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
84922 #define sqlite3_libversion             sqlite3_api->libversion
84923 #define sqlite3_libversion_number      sqlite3_api->libversion_number
84924 #define sqlite3_malloc                 sqlite3_api->malloc
84925 #define sqlite3_mprintf                sqlite3_api->mprintf
84926 #define sqlite3_open                   sqlite3_api->open
84927 #define sqlite3_open16                 sqlite3_api->open16
84928 #define sqlite3_prepare                sqlite3_api->prepare
84929 #define sqlite3_prepare16              sqlite3_api->prepare16
84930 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
84931 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
84932 #define sqlite3_profile                sqlite3_api->profile
84933 #define sqlite3_progress_handler       sqlite3_api->progress_handler
84934 #define sqlite3_realloc                sqlite3_api->realloc
84935 #define sqlite3_reset                  sqlite3_api->reset
84936 #define sqlite3_result_blob            sqlite3_api->result_blob
84937 #define sqlite3_result_double          sqlite3_api->result_double
84938 #define sqlite3_result_error           sqlite3_api->result_error
84939 #define sqlite3_result_error16         sqlite3_api->result_error16
84940 #define sqlite3_result_int             sqlite3_api->result_int
84941 #define sqlite3_result_int64           sqlite3_api->result_int64
84942 #define sqlite3_result_null            sqlite3_api->result_null
84943 #define sqlite3_result_text            sqlite3_api->result_text
84944 #define sqlite3_result_text16          sqlite3_api->result_text16
84945 #define sqlite3_result_text16be        sqlite3_api->result_text16be
84946 #define sqlite3_result_text16le        sqlite3_api->result_text16le
84947 #define sqlite3_result_value           sqlite3_api->result_value
84948 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
84949 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
84950 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
84951 #define sqlite3_snprintf               sqlite3_api->snprintf
84952 #define sqlite3_step                   sqlite3_api->step
84953 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
84954 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
84955 #define sqlite3_total_changes          sqlite3_api->total_changes
84956 #define sqlite3_trace                  sqlite3_api->trace
84957 #ifndef SQLITE_OMIT_DEPRECATED
84958 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
84959 #endif
84960 #define sqlite3_update_hook            sqlite3_api->update_hook
84961 #define sqlite3_user_data              sqlite3_api->user_data
84962 #define sqlite3_value_blob             sqlite3_api->value_blob
84963 #define sqlite3_value_bytes            sqlite3_api->value_bytes
84964 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
84965 #define sqlite3_value_double           sqlite3_api->value_double
84966 #define sqlite3_value_int              sqlite3_api->value_int
84967 #define sqlite3_value_int64            sqlite3_api->value_int64
84968 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
84969 #define sqlite3_value_text             sqlite3_api->value_text
84970 #define sqlite3_value_text16           sqlite3_api->value_text16
84971 #define sqlite3_value_text16be         sqlite3_api->value_text16be
84972 #define sqlite3_value_text16le         sqlite3_api->value_text16le
84973 #define sqlite3_value_type             sqlite3_api->value_type
84974 #define sqlite3_vmprintf               sqlite3_api->vmprintf
84975 #define sqlite3_overload_function      sqlite3_api->overload_function
84976 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
84977 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
84978 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
84979 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
84980 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
84981 #define sqlite3_blob_close             sqlite3_api->blob_close
84982 #define sqlite3_blob_open              sqlite3_api->blob_open
84983 #define sqlite3_blob_read              sqlite3_api->blob_read
84984 #define sqlite3_blob_write             sqlite3_api->blob_write
84985 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
84986 #define sqlite3_file_control           sqlite3_api->file_control
84987 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
84988 #define sqlite3_memory_used            sqlite3_api->memory_used
84989 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
84990 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
84991 #define sqlite3_mutex_free             sqlite3_api->mutex_free
84992 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
84993 #define sqlite3_mutex_try              sqlite3_api->mutex_try
84994 #define sqlite3_open_v2                sqlite3_api->open_v2
84995 #define sqlite3_release_memory         sqlite3_api->release_memory
84996 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
84997 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
84998 #define sqlite3_sleep                  sqlite3_api->sleep
84999 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
85000 #define sqlite3_vfs_find               sqlite3_api->vfs_find
85001 #define sqlite3_vfs_register           sqlite3_api->vfs_register
85002 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
85003 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
85004 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
85005 #define sqlite3_result_error_code      sqlite3_api->result_error_code
85006 #define sqlite3_test_control           sqlite3_api->test_control
85007 #define sqlite3_randomness             sqlite3_api->randomness
85008 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
85009 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
85010 #define sqlite3_limit                  sqlite3_api->limit
85011 #define sqlite3_next_stmt              sqlite3_api->next_stmt
85012 #define sqlite3_sql                    sqlite3_api->sql
85013 #define sqlite3_status                 sqlite3_api->status
85014 #define sqlite3_backup_finish          sqlite3_api->backup_finish
85015 #define sqlite3_backup_init            sqlite3_api->backup_init
85016 #define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
85017 #define sqlite3_backup_remaining       sqlite3_api->backup_remaining
85018 #define sqlite3_backup_step            sqlite3_api->backup_step
85019 #define sqlite3_compileoption_get      sqlite3_api->compileoption_get
85020 #define sqlite3_compileoption_used     sqlite3_api->compileoption_used
85021 #define sqlite3_create_function_v2     sqlite3_api->create_function_v2
85022 #define sqlite3_db_config              sqlite3_api->db_config
85023 #define sqlite3_db_mutex               sqlite3_api->db_mutex
85024 #define sqlite3_db_status              sqlite3_api->db_status
85025 #define sqlite3_extended_errcode       sqlite3_api->extended_errcode
85026 #define sqlite3_log                    sqlite3_api->log
85027 #define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
85028 #define sqlite3_sourceid               sqlite3_api->sourceid
85029 #define sqlite3_stmt_status            sqlite3_api->stmt_status
85030 #define sqlite3_strnicmp               sqlite3_api->strnicmp
85031 #define sqlite3_unlock_notify          sqlite3_api->unlock_notify
85032 #define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
85033 #define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
85034 #define sqlite3_wal_hook               sqlite3_api->wal_hook
85035 #endif /* SQLITE_CORE */
85036
85037 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
85038 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
85039
85040 #endif /* _SQLITE3EXT_H_ */
85041
85042 /************** End of sqlite3ext.h ******************************************/
85043 /************** Continuing where we left off in loadext.c ********************/
85044
85045 #ifndef SQLITE_OMIT_LOAD_EXTENSION
85046
85047 /*
85048 ** Some API routines are omitted when various features are
85049 ** excluded from a build of SQLite.  Substitute a NULL pointer
85050 ** for any missing APIs.
85051 */
85052 #ifndef SQLITE_ENABLE_COLUMN_METADATA
85053 # define sqlite3_column_database_name   0
85054 # define sqlite3_column_database_name16 0
85055 # define sqlite3_column_table_name      0
85056 # define sqlite3_column_table_name16    0
85057 # define sqlite3_column_origin_name     0
85058 # define sqlite3_column_origin_name16   0
85059 # define sqlite3_table_column_metadata  0
85060 #endif
85061
85062 #ifdef SQLITE_OMIT_AUTHORIZATION
85063 # define sqlite3_set_authorizer         0
85064 #endif
85065
85066 #ifdef SQLITE_OMIT_UTF16
85067 # define sqlite3_bind_text16            0
85068 # define sqlite3_collation_needed16     0
85069 # define sqlite3_column_decltype16      0
85070 # define sqlite3_column_name16          0
85071 # define sqlite3_column_text16          0
85072 # define sqlite3_complete16             0
85073 # define sqlite3_create_collation16     0
85074 # define sqlite3_create_function16      0
85075 # define sqlite3_errmsg16               0
85076 # define sqlite3_open16                 0
85077 # define sqlite3_prepare16              0
85078 # define sqlite3_prepare16_v2           0
85079 # define sqlite3_result_error16         0
85080 # define sqlite3_result_text16          0
85081 # define sqlite3_result_text16be        0
85082 # define sqlite3_result_text16le        0
85083 # define sqlite3_value_text16           0
85084 # define sqlite3_value_text16be         0
85085 # define sqlite3_value_text16le         0
85086 # define sqlite3_column_database_name16 0
85087 # define sqlite3_column_table_name16    0
85088 # define sqlite3_column_origin_name16   0
85089 #endif
85090
85091 #ifdef SQLITE_OMIT_COMPLETE
85092 # define sqlite3_complete 0
85093 # define sqlite3_complete16 0
85094 #endif
85095
85096 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
85097 # define sqlite3_progress_handler 0
85098 #endif
85099
85100 #ifdef SQLITE_OMIT_VIRTUALTABLE
85101 # define sqlite3_create_module 0
85102 # define sqlite3_create_module_v2 0
85103 # define sqlite3_declare_vtab 0
85104 #endif
85105
85106 #ifdef SQLITE_OMIT_SHARED_CACHE
85107 # define sqlite3_enable_shared_cache 0
85108 #endif
85109
85110 #ifdef SQLITE_OMIT_TRACE
85111 # define sqlite3_profile       0
85112 # define sqlite3_trace         0
85113 #endif
85114
85115 #ifdef SQLITE_OMIT_GET_TABLE
85116 # define sqlite3_free_table    0
85117 # define sqlite3_get_table     0
85118 #endif
85119
85120 #ifdef SQLITE_OMIT_INCRBLOB
85121 #define sqlite3_bind_zeroblob  0
85122 #define sqlite3_blob_bytes     0
85123 #define sqlite3_blob_close     0
85124 #define sqlite3_blob_open      0
85125 #define sqlite3_blob_read      0
85126 #define sqlite3_blob_write     0
85127 #endif
85128
85129 /*
85130 ** The following structure contains pointers to all SQLite API routines.
85131 ** A pointer to this structure is passed into extensions when they are
85132 ** loaded so that the extension can make calls back into the SQLite
85133 ** library.
85134 **
85135 ** When adding new APIs, add them to the bottom of this structure
85136 ** in order to preserve backwards compatibility.
85137 **
85138 ** Extensions that use newer APIs should first call the
85139 ** sqlite3_libversion_number() to make sure that the API they
85140 ** intend to use is supported by the library.  Extensions should
85141 ** also check to make sure that the pointer to the function is
85142 ** not NULL before calling it.
85143 */
85144 static const sqlite3_api_routines sqlite3Apis = {
85145   sqlite3_aggregate_context,
85146 #ifndef SQLITE_OMIT_DEPRECATED
85147   sqlite3_aggregate_count,
85148 #else
85149   0,
85150 #endif
85151   sqlite3_bind_blob,
85152   sqlite3_bind_double,
85153   sqlite3_bind_int,
85154   sqlite3_bind_int64,
85155   sqlite3_bind_null,
85156   sqlite3_bind_parameter_count,
85157   sqlite3_bind_parameter_index,
85158   sqlite3_bind_parameter_name,
85159   sqlite3_bind_text,
85160   sqlite3_bind_text16,
85161   sqlite3_bind_value,
85162   sqlite3_busy_handler,
85163   sqlite3_busy_timeout,
85164   sqlite3_changes,
85165   sqlite3_close,
85166   sqlite3_collation_needed,
85167   sqlite3_collation_needed16,
85168   sqlite3_column_blob,
85169   sqlite3_column_bytes,
85170   sqlite3_column_bytes16,
85171   sqlite3_column_count,
85172   sqlite3_column_database_name,
85173   sqlite3_column_database_name16,
85174   sqlite3_column_decltype,
85175   sqlite3_column_decltype16,
85176   sqlite3_column_double,
85177   sqlite3_column_int,
85178   sqlite3_column_int64,
85179   sqlite3_column_name,
85180   sqlite3_column_name16,
85181   sqlite3_column_origin_name,
85182   sqlite3_column_origin_name16,
85183   sqlite3_column_table_name,
85184   sqlite3_column_table_name16,
85185   sqlite3_column_text,
85186   sqlite3_column_text16,
85187   sqlite3_column_type,
85188   sqlite3_column_value,
85189   sqlite3_commit_hook,
85190   sqlite3_complete,
85191   sqlite3_complete16,
85192   sqlite3_create_collation,
85193   sqlite3_create_collation16,
85194   sqlite3_create_function,
85195   sqlite3_create_function16,
85196   sqlite3_create_module,
85197   sqlite3_data_count,
85198   sqlite3_db_handle,
85199   sqlite3_declare_vtab,
85200   sqlite3_enable_shared_cache,
85201   sqlite3_errcode,
85202   sqlite3_errmsg,
85203   sqlite3_errmsg16,
85204   sqlite3_exec,
85205 #ifndef SQLITE_OMIT_DEPRECATED
85206   sqlite3_expired,
85207 #else
85208   0,
85209 #endif
85210   sqlite3_finalize,
85211   sqlite3_free,
85212   sqlite3_free_table,
85213   sqlite3_get_autocommit,
85214   sqlite3_get_auxdata,
85215   sqlite3_get_table,
85216   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
85217   sqlite3_interrupt,
85218   sqlite3_last_insert_rowid,
85219   sqlite3_libversion,
85220   sqlite3_libversion_number,
85221   sqlite3_malloc,
85222   sqlite3_mprintf,
85223   sqlite3_open,
85224   sqlite3_open16,
85225   sqlite3_prepare,
85226   sqlite3_prepare16,
85227   sqlite3_profile,
85228   sqlite3_progress_handler,
85229   sqlite3_realloc,
85230   sqlite3_reset,
85231   sqlite3_result_blob,
85232   sqlite3_result_double,
85233   sqlite3_result_error,
85234   sqlite3_result_error16,
85235   sqlite3_result_int,
85236   sqlite3_result_int64,
85237   sqlite3_result_null,
85238   sqlite3_result_text,
85239   sqlite3_result_text16,
85240   sqlite3_result_text16be,
85241   sqlite3_result_text16le,
85242   sqlite3_result_value,
85243   sqlite3_rollback_hook,
85244   sqlite3_set_authorizer,
85245   sqlite3_set_auxdata,
85246   sqlite3_snprintf,
85247   sqlite3_step,
85248   sqlite3_table_column_metadata,
85249 #ifndef SQLITE_OMIT_DEPRECATED
85250   sqlite3_thread_cleanup,
85251 #else
85252   0,
85253 #endif
85254   sqlite3_total_changes,
85255   sqlite3_trace,
85256 #ifndef SQLITE_OMIT_DEPRECATED
85257   sqlite3_transfer_bindings,
85258 #else
85259   0,
85260 #endif
85261   sqlite3_update_hook,
85262   sqlite3_user_data,
85263   sqlite3_value_blob,
85264   sqlite3_value_bytes,
85265   sqlite3_value_bytes16,
85266   sqlite3_value_double,
85267   sqlite3_value_int,
85268   sqlite3_value_int64,
85269   sqlite3_value_numeric_type,
85270   sqlite3_value_text,
85271   sqlite3_value_text16,
85272   sqlite3_value_text16be,
85273   sqlite3_value_text16le,
85274   sqlite3_value_type,
85275   sqlite3_vmprintf,
85276   /*
85277   ** The original API set ends here.  All extensions can call any
85278   ** of the APIs above provided that the pointer is not NULL.  But
85279   ** before calling APIs that follow, extension should check the
85280   ** sqlite3_libversion_number() to make sure they are dealing with
85281   ** a library that is new enough to support that API.
85282   *************************************************************************
85283   */
85284   sqlite3_overload_function,
85285
85286   /*
85287   ** Added after 3.3.13
85288   */
85289   sqlite3_prepare_v2,
85290   sqlite3_prepare16_v2,
85291   sqlite3_clear_bindings,
85292
85293   /*
85294   ** Added for 3.4.1
85295   */
85296   sqlite3_create_module_v2,
85297
85298   /*
85299   ** Added for 3.5.0
85300   */
85301   sqlite3_bind_zeroblob,
85302   sqlite3_blob_bytes,
85303   sqlite3_blob_close,
85304   sqlite3_blob_open,
85305   sqlite3_blob_read,
85306   sqlite3_blob_write,
85307   sqlite3_create_collation_v2,
85308   sqlite3_file_control,
85309   sqlite3_memory_highwater,
85310   sqlite3_memory_used,
85311 #ifdef SQLITE_MUTEX_OMIT
85312   0, 
85313   0, 
85314   0,
85315   0,
85316   0,
85317 #else
85318   sqlite3_mutex_alloc,
85319   sqlite3_mutex_enter,
85320   sqlite3_mutex_free,
85321   sqlite3_mutex_leave,
85322   sqlite3_mutex_try,
85323 #endif
85324   sqlite3_open_v2,
85325   sqlite3_release_memory,
85326   sqlite3_result_error_nomem,
85327   sqlite3_result_error_toobig,
85328   sqlite3_sleep,
85329   sqlite3_soft_heap_limit,
85330   sqlite3_vfs_find,
85331   sqlite3_vfs_register,
85332   sqlite3_vfs_unregister,
85333
85334   /*
85335   ** Added for 3.5.8
85336   */
85337   sqlite3_threadsafe,
85338   sqlite3_result_zeroblob,
85339   sqlite3_result_error_code,
85340   sqlite3_test_control,
85341   sqlite3_randomness,
85342   sqlite3_context_db_handle,
85343
85344   /*
85345   ** Added for 3.6.0
85346   */
85347   sqlite3_extended_result_codes,
85348   sqlite3_limit,
85349   sqlite3_next_stmt,
85350   sqlite3_sql,
85351   sqlite3_status,
85352
85353   /*
85354   ** Added for 3.7.4
85355   */
85356   sqlite3_backup_finish,
85357   sqlite3_backup_init,
85358   sqlite3_backup_pagecount,
85359   sqlite3_backup_remaining,
85360   sqlite3_backup_step,
85361 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
85362   sqlite3_compileoption_get,
85363   sqlite3_compileoption_used,
85364 #else
85365   0,
85366   0,
85367 #endif
85368   sqlite3_create_function_v2,
85369   sqlite3_db_config,
85370   sqlite3_db_mutex,
85371   sqlite3_db_status,
85372   sqlite3_extended_errcode,
85373   sqlite3_log,
85374   sqlite3_soft_heap_limit64,
85375   sqlite3_sourceid,
85376   sqlite3_stmt_status,
85377   sqlite3_strnicmp,
85378 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
85379   sqlite3_unlock_notify,
85380 #else
85381   0,
85382 #endif
85383 #ifndef SQLITE_OMIT_WAL
85384   sqlite3_wal_autocheckpoint,
85385   sqlite3_wal_checkpoint,
85386   sqlite3_wal_hook,
85387 #else
85388   0,
85389   0,
85390   0,
85391 #endif
85392 };
85393
85394 /*
85395 ** Attempt to load an SQLite extension library contained in the file
85396 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
85397 ** default entry point name (sqlite3_extension_init) is used.  Use
85398 ** of the default name is recommended.
85399 **
85400 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
85401 **
85402 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
85403 ** error message text.  The calling function should free this memory
85404 ** by calling sqlite3DbFree(db, ).
85405 */
85406 static int sqlite3LoadExtension(
85407   sqlite3 *db,          /* Load the extension into this database connection */
85408   const char *zFile,    /* Name of the shared library containing extension */
85409   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
85410   char **pzErrMsg       /* Put error message here if not 0 */
85411 ){
85412   sqlite3_vfs *pVfs = db->pVfs;
85413   void *handle;
85414   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
85415   char *zErrmsg = 0;
85416   void **aHandle;
85417   const int nMsg = 300;
85418
85419   if( pzErrMsg ) *pzErrMsg = 0;
85420
85421   /* Ticket #1863.  To avoid a creating security problems for older
85422   ** applications that relink against newer versions of SQLite, the
85423   ** ability to run load_extension is turned off by default.  One
85424   ** must call sqlite3_enable_load_extension() to turn on extension
85425   ** loading.  Otherwise you get the following error.
85426   */
85427   if( (db->flags & SQLITE_LoadExtension)==0 ){
85428     if( pzErrMsg ){
85429       *pzErrMsg = sqlite3_mprintf("not authorized");
85430     }
85431     return SQLITE_ERROR;
85432   }
85433
85434   if( zProc==0 ){
85435     zProc = "sqlite3_extension_init";
85436   }
85437
85438   handle = sqlite3OsDlOpen(pVfs, zFile);
85439   if( handle==0 ){
85440     if( pzErrMsg ){
85441       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
85442       if( zErrmsg ){
85443         sqlite3_snprintf(nMsg, zErrmsg, 
85444             "unable to open shared library [%s]", zFile);
85445         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
85446       }
85447     }
85448     return SQLITE_ERROR;
85449   }
85450   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
85451                    sqlite3OsDlSym(pVfs, handle, zProc);
85452   if( xInit==0 ){
85453     if( pzErrMsg ){
85454       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
85455       if( zErrmsg ){
85456         sqlite3_snprintf(nMsg, zErrmsg,
85457             "no entry point [%s] in shared library [%s]", zProc,zFile);
85458         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
85459       }
85460       sqlite3OsDlClose(pVfs, handle);
85461     }
85462     return SQLITE_ERROR;
85463   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
85464     if( pzErrMsg ){
85465       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
85466     }
85467     sqlite3_free(zErrmsg);
85468     sqlite3OsDlClose(pVfs, handle);
85469     return SQLITE_ERROR;
85470   }
85471
85472   /* Append the new shared library handle to the db->aExtension array. */
85473   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
85474   if( aHandle==0 ){
85475     return SQLITE_NOMEM;
85476   }
85477   if( db->nExtension>0 ){
85478     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
85479   }
85480   sqlite3DbFree(db, db->aExtension);
85481   db->aExtension = aHandle;
85482
85483   db->aExtension[db->nExtension++] = handle;
85484   return SQLITE_OK;
85485 }
85486 SQLITE_API int sqlite3_load_extension(
85487   sqlite3 *db,          /* Load the extension into this database connection */
85488   const char *zFile,    /* Name of the shared library containing extension */
85489   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
85490   char **pzErrMsg       /* Put error message here if not 0 */
85491 ){
85492   int rc;
85493   sqlite3_mutex_enter(db->mutex);
85494   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
85495   rc = sqlite3ApiExit(db, rc);
85496   sqlite3_mutex_leave(db->mutex);
85497   return rc;
85498 }
85499
85500 /*
85501 ** Call this routine when the database connection is closing in order
85502 ** to clean up loaded extensions
85503 */
85504 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
85505   int i;
85506   assert( sqlite3_mutex_held(db->mutex) );
85507   for(i=0; i<db->nExtension; i++){
85508     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
85509   }
85510   sqlite3DbFree(db, db->aExtension);
85511 }
85512
85513 /*
85514 ** Enable or disable extension loading.  Extension loading is disabled by
85515 ** default so as not to open security holes in older applications.
85516 */
85517 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
85518   sqlite3_mutex_enter(db->mutex);
85519   if( onoff ){
85520     db->flags |= SQLITE_LoadExtension;
85521   }else{
85522     db->flags &= ~SQLITE_LoadExtension;
85523   }
85524   sqlite3_mutex_leave(db->mutex);
85525   return SQLITE_OK;
85526 }
85527
85528 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
85529
85530 /*
85531 ** The auto-extension code added regardless of whether or not extension
85532 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
85533 ** code if regular extension loading is not available.  This is that
85534 ** dummy pointer.
85535 */
85536 #ifdef SQLITE_OMIT_LOAD_EXTENSION
85537 static const sqlite3_api_routines sqlite3Apis = { 0 };
85538 #endif
85539
85540
85541 /*
85542 ** The following object holds the list of automatically loaded
85543 ** extensions.
85544 **
85545 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
85546 ** mutex must be held while accessing this list.
85547 */
85548 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
85549 static SQLITE_WSD struct sqlite3AutoExtList {
85550   int nExt;              /* Number of entries in aExt[] */          
85551   void (**aExt)(void);   /* Pointers to the extension init functions */
85552 } sqlite3Autoext = { 0, 0 };
85553
85554 /* The "wsdAutoext" macro will resolve to the autoextension
85555 ** state vector.  If writable static data is unsupported on the target,
85556 ** we have to locate the state vector at run-time.  In the more common
85557 ** case where writable static data is supported, wsdStat can refer directly
85558 ** to the "sqlite3Autoext" state vector declared above.
85559 */
85560 #ifdef SQLITE_OMIT_WSD
85561 # define wsdAutoextInit \
85562   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
85563 # define wsdAutoext x[0]
85564 #else
85565 # define wsdAutoextInit
85566 # define wsdAutoext sqlite3Autoext
85567 #endif
85568
85569
85570 /*
85571 ** Register a statically linked extension that is automatically
85572 ** loaded by every new database connection.
85573 */
85574 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
85575   int rc = SQLITE_OK;
85576 #ifndef SQLITE_OMIT_AUTOINIT
85577   rc = sqlite3_initialize();
85578   if( rc ){
85579     return rc;
85580   }else
85581 #endif
85582   {
85583     int i;
85584 #if SQLITE_THREADSAFE
85585     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
85586 #endif
85587     wsdAutoextInit;
85588     sqlite3_mutex_enter(mutex);
85589     for(i=0; i<wsdAutoext.nExt; i++){
85590       if( wsdAutoext.aExt[i]==xInit ) break;
85591     }
85592     if( i==wsdAutoext.nExt ){
85593       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
85594       void (**aNew)(void);
85595       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
85596       if( aNew==0 ){
85597         rc = SQLITE_NOMEM;
85598       }else{
85599         wsdAutoext.aExt = aNew;
85600         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
85601         wsdAutoext.nExt++;
85602       }
85603     }
85604     sqlite3_mutex_leave(mutex);
85605     assert( (rc&0xff)==rc );
85606     return rc;
85607   }
85608 }
85609
85610 /*
85611 ** Reset the automatic extension loading mechanism.
85612 */
85613 SQLITE_API void sqlite3_reset_auto_extension(void){
85614 #ifndef SQLITE_OMIT_AUTOINIT
85615   if( sqlite3_initialize()==SQLITE_OK )
85616 #endif
85617   {
85618 #if SQLITE_THREADSAFE
85619     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
85620 #endif
85621     wsdAutoextInit;
85622     sqlite3_mutex_enter(mutex);
85623     sqlite3_free(wsdAutoext.aExt);
85624     wsdAutoext.aExt = 0;
85625     wsdAutoext.nExt = 0;
85626     sqlite3_mutex_leave(mutex);
85627   }
85628 }
85629
85630 /*
85631 ** Load all automatic extensions.
85632 **
85633 ** If anything goes wrong, set an error in the database connection.
85634 */
85635 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
85636   int i;
85637   int go = 1;
85638   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
85639
85640   wsdAutoextInit;
85641   if( wsdAutoext.nExt==0 ){
85642     /* Common case: early out without every having to acquire a mutex */
85643     return;
85644   }
85645   for(i=0; go; i++){
85646     char *zErrmsg;
85647 #if SQLITE_THREADSAFE
85648     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
85649 #endif
85650     sqlite3_mutex_enter(mutex);
85651     if( i>=wsdAutoext.nExt ){
85652       xInit = 0;
85653       go = 0;
85654     }else{
85655       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
85656               wsdAutoext.aExt[i];
85657     }
85658     sqlite3_mutex_leave(mutex);
85659     zErrmsg = 0;
85660     if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
85661       sqlite3Error(db, SQLITE_ERROR,
85662             "automatic extension loading failed: %s", zErrmsg);
85663       go = 0;
85664     }
85665     sqlite3_free(zErrmsg);
85666   }
85667 }
85668
85669 /************** End of loadext.c *********************************************/
85670 /************** Begin file pragma.c ******************************************/
85671 /*
85672 ** 2003 April 6
85673 **
85674 ** The author disclaims copyright to this source code.  In place of
85675 ** a legal notice, here is a blessing:
85676 **
85677 **    May you do good and not evil.
85678 **    May you find forgiveness for yourself and forgive others.
85679 **    May you share freely, never taking more than you give.
85680 **
85681 *************************************************************************
85682 ** This file contains code used to implement the PRAGMA command.
85683 */
85684
85685 /* Ignore this whole file if pragmas are disabled
85686 */
85687 #if !defined(SQLITE_OMIT_PRAGMA)
85688
85689 /*
85690 ** Interpret the given string as a safety level.  Return 0 for OFF,
85691 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
85692 ** unrecognized string argument.
85693 **
85694 ** Note that the values returned are one less that the values that
85695 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
85696 ** to support legacy SQL code.  The safety level used to be boolean
85697 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
85698 */
85699 static u8 getSafetyLevel(const char *z){
85700                              /* 123456789 123456789 */
85701   static const char zText[] = "onoffalseyestruefull";
85702   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
85703   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
85704   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
85705   int i, n;
85706   if( sqlite3Isdigit(*z) ){
85707     return (u8)sqlite3Atoi(z);
85708   }
85709   n = sqlite3Strlen30(z);
85710   for(i=0; i<ArraySize(iLength); i++){
85711     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
85712       return iValue[i];
85713     }
85714   }
85715   return 1;
85716 }
85717
85718 /*
85719 ** Interpret the given string as a boolean value.
85720 */
85721 static u8 getBoolean(const char *z){
85722   return getSafetyLevel(z)&1;
85723 }
85724
85725 /*
85726 ** Interpret the given string as a locking mode value.
85727 */
85728 static int getLockingMode(const char *z){
85729   if( z ){
85730     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
85731     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
85732   }
85733   return PAGER_LOCKINGMODE_QUERY;
85734 }
85735
85736 #ifndef SQLITE_OMIT_AUTOVACUUM
85737 /*
85738 ** Interpret the given string as an auto-vacuum mode value.
85739 **
85740 ** The following strings, "none", "full" and "incremental" are 
85741 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
85742 */
85743 static int getAutoVacuum(const char *z){
85744   int i;
85745   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
85746   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
85747   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
85748   i = sqlite3Atoi(z);
85749   return (u8)((i>=0&&i<=2)?i:0);
85750 }
85751 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
85752
85753 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
85754 /*
85755 ** Interpret the given string as a temp db location. Return 1 for file
85756 ** backed temporary databases, 2 for the Red-Black tree in memory database
85757 ** and 0 to use the compile-time default.
85758 */
85759 static int getTempStore(const char *z){
85760   if( z[0]>='0' && z[0]<='2' ){
85761     return z[0] - '0';
85762   }else if( sqlite3StrICmp(z, "file")==0 ){
85763     return 1;
85764   }else if( sqlite3StrICmp(z, "memory")==0 ){
85765     return 2;
85766   }else{
85767     return 0;
85768   }
85769 }
85770 #endif /* SQLITE_PAGER_PRAGMAS */
85771
85772 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
85773 /*
85774 ** Invalidate temp storage, either when the temp storage is changed
85775 ** from default, or when 'file' and the temp_store_directory has changed
85776 */
85777 static int invalidateTempStorage(Parse *pParse){
85778   sqlite3 *db = pParse->db;
85779   if( db->aDb[1].pBt!=0 ){
85780     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
85781       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
85782         "from within a transaction");
85783       return SQLITE_ERROR;
85784     }
85785     sqlite3BtreeClose(db->aDb[1].pBt);
85786     db->aDb[1].pBt = 0;
85787     sqlite3ResetInternalSchema(db, 0);
85788   }
85789   return SQLITE_OK;
85790 }
85791 #endif /* SQLITE_PAGER_PRAGMAS */
85792
85793 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
85794 /*
85795 ** If the TEMP database is open, close it and mark the database schema
85796 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
85797 ** or DEFAULT_TEMP_STORE pragmas.
85798 */
85799 static int changeTempStorage(Parse *pParse, const char *zStorageType){
85800   int ts = getTempStore(zStorageType);
85801   sqlite3 *db = pParse->db;
85802   if( db->temp_store==ts ) return SQLITE_OK;
85803   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
85804     return SQLITE_ERROR;
85805   }
85806   db->temp_store = (u8)ts;
85807   return SQLITE_OK;
85808 }
85809 #endif /* SQLITE_PAGER_PRAGMAS */
85810
85811 /*
85812 ** Generate code to return a single integer value.
85813 */
85814 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
85815   Vdbe *v = sqlite3GetVdbe(pParse);
85816   int mem = ++pParse->nMem;
85817   i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
85818   if( pI64 ){
85819     memcpy(pI64, &value, sizeof(value));
85820   }
85821   sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
85822   sqlite3VdbeSetNumCols(v, 1);
85823   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
85824   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
85825 }
85826
85827 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
85828 /*
85829 ** Check to see if zRight and zLeft refer to a pragma that queries
85830 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
85831 ** Also, implement the pragma.
85832 */
85833 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
85834   static const struct sPragmaType {
85835     const char *zName;  /* Name of the pragma */
85836     int mask;           /* Mask for the db->flags value */
85837   } aPragma[] = {
85838     { "full_column_names",        SQLITE_FullColNames  },
85839     { "short_column_names",       SQLITE_ShortColNames },
85840     { "count_changes",            SQLITE_CountRows     },
85841     { "empty_result_callbacks",   SQLITE_NullCallback  },
85842     { "legacy_file_format",       SQLITE_LegacyFileFmt },
85843     { "fullfsync",                SQLITE_FullFSync     },
85844     { "checkpoint_fullfsync",     SQLITE_CkptFullFSync },
85845     { "reverse_unordered_selects", SQLITE_ReverseOrder  },
85846 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
85847     { "automatic_index",          SQLITE_AutoIndex     },
85848 #endif
85849 #ifdef SQLITE_DEBUG
85850     { "sql_trace",                SQLITE_SqlTrace      },
85851     { "vdbe_listing",             SQLITE_VdbeListing   },
85852     { "vdbe_trace",               SQLITE_VdbeTrace     },
85853 #endif
85854 #ifndef SQLITE_OMIT_CHECK
85855     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
85856 #endif
85857     /* The following is VERY experimental */
85858     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
85859     { "omit_readlock",            SQLITE_NoReadlock    },
85860
85861     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
85862     ** flag if there are any active statements. */
85863     { "read_uncommitted",         SQLITE_ReadUncommitted },
85864     { "recursive_triggers",       SQLITE_RecTriggers },
85865
85866     /* This flag may only be set if both foreign-key and trigger support
85867     ** are present in the build.  */
85868 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
85869     { "foreign_keys",             SQLITE_ForeignKeys },
85870 #endif
85871   };
85872   int i;
85873   const struct sPragmaType *p;
85874   for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
85875     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
85876       sqlite3 *db = pParse->db;
85877       Vdbe *v;
85878       v = sqlite3GetVdbe(pParse);
85879       assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
85880       if( ALWAYS(v) ){
85881         if( zRight==0 ){
85882           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
85883         }else{
85884           int mask = p->mask;          /* Mask of bits to set or clear. */
85885           if( db->autoCommit==0 ){
85886             /* Foreign key support may not be enabled or disabled while not
85887             ** in auto-commit mode.  */
85888             mask &= ~(SQLITE_ForeignKeys);
85889           }
85890
85891           if( getBoolean(zRight) ){
85892             db->flags |= mask;
85893           }else{
85894             db->flags &= ~mask;
85895           }
85896
85897           /* Many of the flag-pragmas modify the code generated by the SQL 
85898           ** compiler (eg. count_changes). So add an opcode to expire all
85899           ** compiled SQL statements after modifying a pragma value.
85900           */
85901           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
85902         }
85903       }
85904
85905       return 1;
85906     }
85907   }
85908   return 0;
85909 }
85910 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
85911
85912 /*
85913 ** Return a human-readable name for a constraint resolution action.
85914 */
85915 #ifndef SQLITE_OMIT_FOREIGN_KEY
85916 static const char *actionName(u8 action){
85917   const char *zName;
85918   switch( action ){
85919     case OE_SetNull:  zName = "SET NULL";        break;
85920     case OE_SetDflt:  zName = "SET DEFAULT";     break;
85921     case OE_Cascade:  zName = "CASCADE";         break;
85922     case OE_Restrict: zName = "RESTRICT";        break;
85923     default:          zName = "NO ACTION";  
85924                       assert( action==OE_None ); break;
85925   }
85926   return zName;
85927 }
85928 #endif
85929
85930
85931 /*
85932 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
85933 ** defined in pager.h. This function returns the associated lowercase
85934 ** journal-mode name.
85935 */
85936 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
85937   static char * const azModeName[] = {
85938     "delete", "persist", "off", "truncate", "memory"
85939 #ifndef SQLITE_OMIT_WAL
85940      , "wal"
85941 #endif
85942   };
85943   assert( PAGER_JOURNALMODE_DELETE==0 );
85944   assert( PAGER_JOURNALMODE_PERSIST==1 );
85945   assert( PAGER_JOURNALMODE_OFF==2 );
85946   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
85947   assert( PAGER_JOURNALMODE_MEMORY==4 );
85948   assert( PAGER_JOURNALMODE_WAL==5 );
85949   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
85950
85951   if( eMode==ArraySize(azModeName) ) return 0;
85952   return azModeName[eMode];
85953 }
85954
85955 /*
85956 ** Process a pragma statement.  
85957 **
85958 ** Pragmas are of this form:
85959 **
85960 **      PRAGMA [database.]id [= value]
85961 **
85962 ** The identifier might also be a string.  The value is a string, and
85963 ** identifier, or a number.  If minusFlag is true, then the value is
85964 ** a number that was preceded by a minus sign.
85965 **
85966 ** If the left side is "database.id" then pId1 is the database name
85967 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
85968 ** id and pId2 is any empty string.
85969 */
85970 SQLITE_PRIVATE void sqlite3Pragma(
85971   Parse *pParse, 
85972   Token *pId1,        /* First part of [database.]id field */
85973   Token *pId2,        /* Second part of [database.]id field, or NULL */
85974   Token *pValue,      /* Token for <value>, or NULL */
85975   int minusFlag       /* True if a '-' sign preceded <value> */
85976 ){
85977   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
85978   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
85979   const char *zDb = 0;   /* The database name */
85980   Token *pId;            /* Pointer to <id> token */
85981   int iDb;               /* Database index for <database> */
85982   sqlite3 *db = pParse->db;
85983   Db *pDb;
85984   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
85985   if( v==0 ) return;
85986   sqlite3VdbeRunOnlyOnce(v);
85987   pParse->nMem = 2;
85988
85989   /* Interpret the [database.] part of the pragma statement. iDb is the
85990   ** index of the database this pragma is being applied to in db.aDb[]. */
85991   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
85992   if( iDb<0 ) return;
85993   pDb = &db->aDb[iDb];
85994
85995   /* If the temp database has been explicitly named as part of the 
85996   ** pragma, make sure it is open. 
85997   */
85998   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
85999     return;
86000   }
86001
86002   zLeft = sqlite3NameFromToken(db, pId);
86003   if( !zLeft ) return;
86004   if( minusFlag ){
86005     zRight = sqlite3MPrintf(db, "-%T", pValue);
86006   }else{
86007     zRight = sqlite3NameFromToken(db, pValue);
86008   }
86009
86010   assert( pId2 );
86011   zDb = pId2->n>0 ? pDb->zName : 0;
86012   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
86013     goto pragma_out;
86014   }
86015  
86016 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
86017   /*
86018   **  PRAGMA [database.]default_cache_size
86019   **  PRAGMA [database.]default_cache_size=N
86020   **
86021   ** The first form reports the current persistent setting for the
86022   ** page cache size.  The value returned is the maximum number of
86023   ** pages in the page cache.  The second form sets both the current
86024   ** page cache size value and the persistent page cache size value
86025   ** stored in the database file.
86026   **
86027   ** Older versions of SQLite would set the default cache size to a
86028   ** negative number to indicate synchronous=OFF.  These days, synchronous
86029   ** is always on by default regardless of the sign of the default cache
86030   ** size.  But continue to take the absolute value of the default cache
86031   ** size of historical compatibility.
86032   */
86033   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
86034     static const VdbeOpList getCacheSize[] = {
86035       { OP_Transaction, 0, 0,        0},                         /* 0 */
86036       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
86037       { OP_IfPos,       1, 7,        0},
86038       { OP_Integer,     0, 2,        0},
86039       { OP_Subtract,    1, 2,        1},
86040       { OP_IfPos,       1, 7,        0},
86041       { OP_Integer,     0, 1,        0},                         /* 6 */
86042       { OP_ResultRow,   1, 1,        0},
86043     };
86044     int addr;
86045     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
86046     sqlite3VdbeUsesBtree(v, iDb);
86047     if( !zRight ){
86048       sqlite3VdbeSetNumCols(v, 1);
86049       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
86050       pParse->nMem += 2;
86051       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
86052       sqlite3VdbeChangeP1(v, addr, iDb);
86053       sqlite3VdbeChangeP1(v, addr+1, iDb);
86054       sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
86055     }else{
86056       int size = sqlite3Atoi(zRight);
86057       if( size<0 ) size = -size;
86058       sqlite3BeginWriteOperation(pParse, 0, iDb);
86059       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
86060       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
86061       pDb->pSchema->cache_size = size;
86062       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
86063     }
86064   }else
86065
86066   /*
86067   **  PRAGMA [database.]page_size
86068   **  PRAGMA [database.]page_size=N
86069   **
86070   ** The first form reports the current setting for the
86071   ** database page size in bytes.  The second form sets the
86072   ** database page size value.  The value can only be set if
86073   ** the database has not yet been created.
86074   */
86075   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
86076     Btree *pBt = pDb->pBt;
86077     assert( pBt!=0 );
86078     if( !zRight ){
86079       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
86080       returnSingleInt(pParse, "page_size", size);
86081     }else{
86082       /* Malloc may fail when setting the page-size, as there is an internal
86083       ** buffer that the pager module resizes using sqlite3_realloc().
86084       */
86085       db->nextPagesize = sqlite3Atoi(zRight);
86086       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
86087         db->mallocFailed = 1;
86088       }
86089     }
86090   }else
86091
86092   /*
86093   **  PRAGMA [database.]secure_delete
86094   **  PRAGMA [database.]secure_delete=ON/OFF
86095   **
86096   ** The first form reports the current setting for the
86097   ** secure_delete flag.  The second form changes the secure_delete
86098   ** flag setting and reports thenew value.
86099   */
86100   if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
86101     Btree *pBt = pDb->pBt;
86102     int b = -1;
86103     assert( pBt!=0 );
86104     if( zRight ){
86105       b = getBoolean(zRight);
86106     }
86107     if( pId2->n==0 && b>=0 ){
86108       int ii;
86109       for(ii=0; ii<db->nDb; ii++){
86110         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
86111       }
86112     }
86113     b = sqlite3BtreeSecureDelete(pBt, b);
86114     returnSingleInt(pParse, "secure_delete", b);
86115   }else
86116
86117   /*
86118   **  PRAGMA [database.]max_page_count
86119   **  PRAGMA [database.]max_page_count=N
86120   **
86121   ** The first form reports the current setting for the
86122   ** maximum number of pages in the database file.  The 
86123   ** second form attempts to change this setting.  Both
86124   ** forms return the current setting.
86125   **
86126   **  PRAGMA [database.]page_count
86127   **
86128   ** Return the number of pages in the specified database.
86129   */
86130   if( sqlite3StrICmp(zLeft,"page_count")==0
86131    || sqlite3StrICmp(zLeft,"max_page_count")==0
86132   ){
86133     int iReg;
86134     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
86135     sqlite3CodeVerifySchema(pParse, iDb);
86136     iReg = ++pParse->nMem;
86137     if( zLeft[0]=='p' ){
86138       sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
86139     }else{
86140       sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, sqlite3Atoi(zRight));
86141     }
86142     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
86143     sqlite3VdbeSetNumCols(v, 1);
86144     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
86145   }else
86146
86147   /*
86148   **  PRAGMA [database.]locking_mode
86149   **  PRAGMA [database.]locking_mode = (normal|exclusive)
86150   */
86151   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
86152     const char *zRet = "normal";
86153     int eMode = getLockingMode(zRight);
86154
86155     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
86156       /* Simple "PRAGMA locking_mode;" statement. This is a query for
86157       ** the current default locking mode (which may be different to
86158       ** the locking-mode of the main database).
86159       */
86160       eMode = db->dfltLockMode;
86161     }else{
86162       Pager *pPager;
86163       if( pId2->n==0 ){
86164         /* This indicates that no database name was specified as part
86165         ** of the PRAGMA command. In this case the locking-mode must be
86166         ** set on all attached databases, as well as the main db file.
86167         **
86168         ** Also, the sqlite3.dfltLockMode variable is set so that
86169         ** any subsequently attached databases also use the specified
86170         ** locking mode.
86171         */
86172         int ii;
86173         assert(pDb==&db->aDb[0]);
86174         for(ii=2; ii<db->nDb; ii++){
86175           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
86176           sqlite3PagerLockingMode(pPager, eMode);
86177         }
86178         db->dfltLockMode = (u8)eMode;
86179       }
86180       pPager = sqlite3BtreePager(pDb->pBt);
86181       eMode = sqlite3PagerLockingMode(pPager, eMode);
86182     }
86183
86184     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
86185     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
86186       zRet = "exclusive";
86187     }
86188     sqlite3VdbeSetNumCols(v, 1);
86189     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
86190     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
86191     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
86192   }else
86193
86194   /*
86195   **  PRAGMA [database.]journal_mode
86196   **  PRAGMA [database.]journal_mode =
86197   **                      (delete|persist|off|truncate|memory|wal|off)
86198   */
86199   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
86200     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
86201     int ii;           /* Loop counter */
86202
86203     /* Force the schema to be loaded on all databases.  This cases all
86204     ** database files to be opened and the journal_modes set. */
86205     if( sqlite3ReadSchema(pParse) ){
86206       goto pragma_out;
86207     }
86208
86209     sqlite3VdbeSetNumCols(v, 1);
86210     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
86211
86212     if( zRight==0 ){
86213       /* If there is no "=MODE" part of the pragma, do a query for the
86214       ** current mode */
86215       eMode = PAGER_JOURNALMODE_QUERY;
86216     }else{
86217       const char *zMode;
86218       int n = sqlite3Strlen30(zRight);
86219       for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
86220         if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
86221       }
86222       if( !zMode ){
86223         /* If the "=MODE" part does not match any known journal mode,
86224         ** then do a query */
86225         eMode = PAGER_JOURNALMODE_QUERY;
86226       }
86227     }
86228     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
86229       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
86230       iDb = 0;
86231       pId2->n = 1;
86232     }
86233     for(ii=db->nDb-1; ii>=0; ii--){
86234       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
86235         sqlite3VdbeUsesBtree(v, ii);
86236         sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
86237       }
86238     }
86239     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
86240   }else
86241
86242   /*
86243   **  PRAGMA [database.]journal_size_limit
86244   **  PRAGMA [database.]journal_size_limit=N
86245   **
86246   ** Get or set the size limit on rollback journal files.
86247   */
86248   if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
86249     Pager *pPager = sqlite3BtreePager(pDb->pBt);
86250     i64 iLimit = -2;
86251     if( zRight ){
86252       sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
86253       if( iLimit<-1 ) iLimit = -1;
86254     }
86255     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
86256     returnSingleInt(pParse, "journal_size_limit", iLimit);
86257   }else
86258
86259 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
86260
86261   /*
86262   **  PRAGMA [database.]auto_vacuum
86263   **  PRAGMA [database.]auto_vacuum=N
86264   **
86265   ** Get or set the value of the database 'auto-vacuum' parameter.
86266   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
86267   */
86268 #ifndef SQLITE_OMIT_AUTOVACUUM
86269   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
86270     Btree *pBt = pDb->pBt;
86271     assert( pBt!=0 );
86272     if( sqlite3ReadSchema(pParse) ){
86273       goto pragma_out;
86274     }
86275     if( !zRight ){
86276       int auto_vacuum;
86277       if( ALWAYS(pBt) ){
86278          auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
86279       }else{
86280          auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
86281       }
86282       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
86283     }else{
86284       int eAuto = getAutoVacuum(zRight);
86285       assert( eAuto>=0 && eAuto<=2 );
86286       db->nextAutovac = (u8)eAuto;
86287       if( ALWAYS(eAuto>=0) ){
86288         /* Call SetAutoVacuum() to set initialize the internal auto and
86289         ** incr-vacuum flags. This is required in case this connection
86290         ** creates the database file. It is important that it is created
86291         ** as an auto-vacuum capable db.
86292         */
86293         int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
86294         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
86295           /* When setting the auto_vacuum mode to either "full" or 
86296           ** "incremental", write the value of meta[6] in the database
86297           ** file. Before writing to meta[6], check that meta[3] indicates
86298           ** that this really is an auto-vacuum capable database.
86299           */
86300           static const VdbeOpList setMeta6[] = {
86301             { OP_Transaction,    0,         1,                 0},    /* 0 */
86302             { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
86303             { OP_If,             1,         0,                 0},    /* 2 */
86304             { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
86305             { OP_Integer,        0,         1,                 0},    /* 4 */
86306             { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
86307           };
86308           int iAddr;
86309           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
86310           sqlite3VdbeChangeP1(v, iAddr, iDb);
86311           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
86312           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
86313           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
86314           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
86315           sqlite3VdbeUsesBtree(v, iDb);
86316         }
86317       }
86318     }
86319   }else
86320 #endif
86321
86322   /*
86323   **  PRAGMA [database.]incremental_vacuum(N)
86324   **
86325   ** Do N steps of incremental vacuuming on a database.
86326   */
86327 #ifndef SQLITE_OMIT_AUTOVACUUM
86328   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
86329     int iLimit, addr;
86330     if( sqlite3ReadSchema(pParse) ){
86331       goto pragma_out;
86332     }
86333     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
86334       iLimit = 0x7fffffff;
86335     }
86336     sqlite3BeginWriteOperation(pParse, 0, iDb);
86337     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
86338     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
86339     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
86340     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
86341     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
86342     sqlite3VdbeJumpHere(v, addr);
86343   }else
86344 #endif
86345
86346 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
86347   /*
86348   **  PRAGMA [database.]cache_size
86349   **  PRAGMA [database.]cache_size=N
86350   **
86351   ** The first form reports the current local setting for the
86352   ** page cache size.  The local setting can be different from
86353   ** the persistent cache size value that is stored in the database
86354   ** file itself.  The value returned is the maximum number of
86355   ** pages in the page cache.  The second form sets the local
86356   ** page cache size value.  It does not change the persistent
86357   ** cache size stored on the disk so the cache size will revert
86358   ** to its default value when the database is closed and reopened.
86359   ** N should be a positive integer.
86360   */
86361   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
86362     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
86363     if( !zRight ){
86364       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
86365     }else{
86366       int size = sqlite3Atoi(zRight);
86367       if( size<0 ) size = -size;
86368       pDb->pSchema->cache_size = size;
86369       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
86370     }
86371   }else
86372
86373   /*
86374   **   PRAGMA temp_store
86375   **   PRAGMA temp_store = "default"|"memory"|"file"
86376   **
86377   ** Return or set the local value of the temp_store flag.  Changing
86378   ** the local value does not make changes to the disk file and the default
86379   ** value will be restored the next time the database is opened.
86380   **
86381   ** Note that it is possible for the library compile-time options to
86382   ** override this setting
86383   */
86384   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
86385     if( !zRight ){
86386       returnSingleInt(pParse, "temp_store", db->temp_store);
86387     }else{
86388       changeTempStorage(pParse, zRight);
86389     }
86390   }else
86391
86392   /*
86393   **   PRAGMA temp_store_directory
86394   **   PRAGMA temp_store_directory = ""|"directory_name"
86395   **
86396   ** Return or set the local value of the temp_store_directory flag.  Changing
86397   ** the value sets a specific directory to be used for temporary files.
86398   ** Setting to a null string reverts to the default temporary directory search.
86399   ** If temporary directory is changed, then invalidateTempStorage.
86400   **
86401   */
86402   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
86403     if( !zRight ){
86404       if( sqlite3_temp_directory ){
86405         sqlite3VdbeSetNumCols(v, 1);
86406         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
86407             "temp_store_directory", SQLITE_STATIC);
86408         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
86409         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
86410       }
86411     }else{
86412 #ifndef SQLITE_OMIT_WSD
86413       if( zRight[0] ){
86414         int rc;
86415         int res;
86416         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
86417         if( rc!=SQLITE_OK || res==0 ){
86418           sqlite3ErrorMsg(pParse, "not a writable directory");
86419           goto pragma_out;
86420         }
86421       }
86422       if( SQLITE_TEMP_STORE==0
86423        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
86424        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
86425       ){
86426         invalidateTempStorage(pParse);
86427       }
86428       sqlite3_free(sqlite3_temp_directory);
86429       if( zRight[0] ){
86430         sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
86431       }else{
86432         sqlite3_temp_directory = 0;
86433       }
86434 #endif /* SQLITE_OMIT_WSD */
86435     }
86436   }else
86437
86438 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
86439 #  if defined(__APPLE__)
86440 #    define SQLITE_ENABLE_LOCKING_STYLE 1
86441 #  else
86442 #    define SQLITE_ENABLE_LOCKING_STYLE 0
86443 #  endif
86444 #endif
86445 #if SQLITE_ENABLE_LOCKING_STYLE
86446   /*
86447    **   PRAGMA [database.]lock_proxy_file
86448    **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
86449    **
86450    ** Return or set the value of the lock_proxy_file flag.  Changing
86451    ** the value sets a specific file to be used for database access locks.
86452    **
86453    */
86454   if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
86455     if( !zRight ){
86456       Pager *pPager = sqlite3BtreePager(pDb->pBt);
86457       char *proxy_file_path = NULL;
86458       sqlite3_file *pFile = sqlite3PagerFile(pPager);
86459       sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE, 
86460                            &proxy_file_path);
86461       
86462       if( proxy_file_path ){
86463         sqlite3VdbeSetNumCols(v, 1);
86464         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
86465                               "lock_proxy_file", SQLITE_STATIC);
86466         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
86467         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
86468       }
86469     }else{
86470       Pager *pPager = sqlite3BtreePager(pDb->pBt);
86471       sqlite3_file *pFile = sqlite3PagerFile(pPager);
86472       int res;
86473       if( zRight[0] ){
86474         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
86475                                      zRight);
86476       } else {
86477         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
86478                                      NULL);
86479       }
86480       if( res!=SQLITE_OK ){
86481         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
86482         goto pragma_out;
86483       }
86484     }
86485   }else
86486 #endif /* SQLITE_ENABLE_LOCKING_STYLE */      
86487     
86488   /*
86489   **   PRAGMA [database.]synchronous
86490   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
86491   **
86492   ** Return or set the local value of the synchronous flag.  Changing
86493   ** the local value does not make changes to the disk file and the
86494   ** default value will be restored the next time the database is
86495   ** opened.
86496   */
86497   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
86498     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
86499     if( !zRight ){
86500       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
86501     }else{
86502       if( !db->autoCommit ){
86503         sqlite3ErrorMsg(pParse, 
86504             "Safety level may not be changed inside a transaction");
86505       }else{
86506         pDb->safety_level = getSafetyLevel(zRight)+1;
86507       }
86508     }
86509   }else
86510 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
86511
86512 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
86513   if( flagPragma(pParse, zLeft, zRight) ){
86514     /* The flagPragma() subroutine also generates any necessary code
86515     ** there is nothing more to do here */
86516   }else
86517 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
86518
86519 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
86520   /*
86521   **   PRAGMA table_info(<table>)
86522   **
86523   ** Return a single row for each column of the named table. The columns of
86524   ** the returned data set are:
86525   **
86526   ** cid:        Column id (numbered from left to right, starting at 0)
86527   ** name:       Column name
86528   ** type:       Column declaration type.
86529   ** notnull:    True if 'NOT NULL' is part of column declaration
86530   ** dflt_value: The default value for the column, if any.
86531   */
86532   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
86533     Table *pTab;
86534     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
86535     pTab = sqlite3FindTable(db, zRight, zDb);
86536     if( pTab ){
86537       int i;
86538       int nHidden = 0;
86539       Column *pCol;
86540       sqlite3VdbeSetNumCols(v, 6);
86541       pParse->nMem = 6;
86542       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
86543       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
86544       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
86545       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
86546       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
86547       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
86548       sqlite3ViewGetColumnNames(pParse, pTab);
86549       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
86550         if( IsHiddenColumn(pCol) ){
86551           nHidden++;
86552           continue;
86553         }
86554         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
86555         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
86556         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
86557            pCol->zType ? pCol->zType : "", 0);
86558         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
86559         if( pCol->zDflt ){
86560           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
86561         }else{
86562           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
86563         }
86564         sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
86565         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
86566       }
86567     }
86568   }else
86569
86570   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
86571     Index *pIdx;
86572     Table *pTab;
86573     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
86574     pIdx = sqlite3FindIndex(db, zRight, zDb);
86575     if( pIdx ){
86576       int i;
86577       pTab = pIdx->pTable;
86578       sqlite3VdbeSetNumCols(v, 3);
86579       pParse->nMem = 3;
86580       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
86581       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
86582       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
86583       for(i=0; i<pIdx->nColumn; i++){
86584         int cnum = pIdx->aiColumn[i];
86585         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
86586         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
86587         assert( pTab->nCol>cnum );
86588         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
86589         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
86590       }
86591     }
86592   }else
86593
86594   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
86595     Index *pIdx;
86596     Table *pTab;
86597     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
86598     pTab = sqlite3FindTable(db, zRight, zDb);
86599     if( pTab ){
86600       v = sqlite3GetVdbe(pParse);
86601       pIdx = pTab->pIndex;
86602       if( pIdx ){
86603         int i = 0; 
86604         sqlite3VdbeSetNumCols(v, 3);
86605         pParse->nMem = 3;
86606         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
86607         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
86608         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
86609         while(pIdx){
86610           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
86611           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
86612           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
86613           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
86614           ++i;
86615           pIdx = pIdx->pNext;
86616         }
86617       }
86618     }
86619   }else
86620
86621   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
86622     int i;
86623     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
86624     sqlite3VdbeSetNumCols(v, 3);
86625     pParse->nMem = 3;
86626     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
86627     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
86628     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
86629     for(i=0; i<db->nDb; i++){
86630       if( db->aDb[i].pBt==0 ) continue;
86631       assert( db->aDb[i].zName!=0 );
86632       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
86633       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
86634       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
86635            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
86636       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
86637     }
86638   }else
86639
86640   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
86641     int i = 0;
86642     HashElem *p;
86643     sqlite3VdbeSetNumCols(v, 2);
86644     pParse->nMem = 2;
86645     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
86646     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
86647     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
86648       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
86649       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
86650       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
86651       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
86652     }
86653   }else
86654 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
86655
86656 #ifndef SQLITE_OMIT_FOREIGN_KEY
86657   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
86658     FKey *pFK;
86659     Table *pTab;
86660     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
86661     pTab = sqlite3FindTable(db, zRight, zDb);
86662     if( pTab ){
86663       v = sqlite3GetVdbe(pParse);
86664       pFK = pTab->pFKey;
86665       if( pFK ){
86666         int i = 0; 
86667         sqlite3VdbeSetNumCols(v, 8);
86668         pParse->nMem = 8;
86669         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
86670         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
86671         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
86672         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
86673         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
86674         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
86675         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
86676         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
86677         while(pFK){
86678           int j;
86679           for(j=0; j<pFK->nCol; j++){
86680             char *zCol = pFK->aCol[j].zCol;
86681             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
86682             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
86683             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
86684             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
86685             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
86686             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
86687                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
86688             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
86689             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
86690             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
86691             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
86692             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
86693           }
86694           ++i;
86695           pFK = pFK->pNextFrom;
86696         }
86697       }
86698     }
86699   }else
86700 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
86701
86702 #ifndef NDEBUG
86703   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
86704     if( zRight ){
86705       if( getBoolean(zRight) ){
86706         sqlite3ParserTrace(stderr, "parser: ");
86707       }else{
86708         sqlite3ParserTrace(0, 0);
86709       }
86710     }
86711   }else
86712 #endif
86713
86714   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
86715   ** used will be case sensitive or not depending on the RHS.
86716   */
86717   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
86718     if( zRight ){
86719       sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
86720     }
86721   }else
86722
86723 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
86724 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
86725 #endif
86726
86727 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
86728   /* Pragma "quick_check" is an experimental reduced version of 
86729   ** integrity_check designed to detect most database corruption
86730   ** without most of the overhead of a full integrity-check.
86731   */
86732   if( sqlite3StrICmp(zLeft, "integrity_check")==0
86733    || sqlite3StrICmp(zLeft, "quick_check")==0 
86734   ){
86735     int i, j, addr, mxErr;
86736
86737     /* Code that appears at the end of the integrity check.  If no error
86738     ** messages have been generated, output OK.  Otherwise output the
86739     ** error message
86740     */
86741     static const VdbeOpList endCode[] = {
86742       { OP_AddImm,      1, 0,        0},    /* 0 */
86743       { OP_IfNeg,       1, 0,        0},    /* 1 */
86744       { OP_String8,     0, 3,        0},    /* 2 */
86745       { OP_ResultRow,   3, 1,        0},
86746     };
86747
86748     int isQuick = (zLeft[0]=='q');
86749
86750     /* Initialize the VDBE program */
86751     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
86752     pParse->nMem = 6;
86753     sqlite3VdbeSetNumCols(v, 1);
86754     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
86755
86756     /* Set the maximum error count */
86757     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
86758     if( zRight ){
86759       sqlite3GetInt32(zRight, &mxErr);
86760       if( mxErr<=0 ){
86761         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
86762       }
86763     }
86764     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
86765
86766     /* Do an integrity check on each database file */
86767     for(i=0; i<db->nDb; i++){
86768       HashElem *x;
86769       Hash *pTbls;
86770       int cnt = 0;
86771
86772       if( OMIT_TEMPDB && i==1 ) continue;
86773
86774       sqlite3CodeVerifySchema(pParse, i);
86775       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
86776       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
86777       sqlite3VdbeJumpHere(v, addr);
86778
86779       /* Do an integrity check of the B-Tree
86780       **
86781       ** Begin by filling registers 2, 3, ... with the root pages numbers
86782       ** for all tables and indices in the database.
86783       */
86784       pTbls = &db->aDb[i].pSchema->tblHash;
86785       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
86786         Table *pTab = sqliteHashData(x);
86787         Index *pIdx;
86788         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
86789         cnt++;
86790         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
86791           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
86792           cnt++;
86793         }
86794       }
86795
86796       /* Make sure sufficient number of registers have been allocated */
86797       if( pParse->nMem < cnt+4 ){
86798         pParse->nMem = cnt+4;
86799       }
86800
86801       /* Do the b-tree integrity checks */
86802       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
86803       sqlite3VdbeChangeP5(v, (u8)i);
86804       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
86805       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
86806          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
86807          P4_DYNAMIC);
86808       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
86809       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
86810       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
86811       sqlite3VdbeJumpHere(v, addr);
86812
86813       /* Make sure all the indices are constructed correctly.
86814       */
86815       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
86816         Table *pTab = sqliteHashData(x);
86817         Index *pIdx;
86818         int loopTop;
86819
86820         if( pTab->pIndex==0 ) continue;
86821         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
86822         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
86823         sqlite3VdbeJumpHere(v, addr);
86824         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
86825         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
86826         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
86827         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
86828         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
86829           int jmp2;
86830           int r1;
86831           static const VdbeOpList idxErr[] = {
86832             { OP_AddImm,      1, -1,  0},
86833             { OP_String8,     0,  3,  0},    /* 1 */
86834             { OP_Rowid,       1,  4,  0},
86835             { OP_String8,     0,  5,  0},    /* 3 */
86836             { OP_String8,     0,  6,  0},    /* 4 */
86837             { OP_Concat,      4,  3,  3},
86838             { OP_Concat,      5,  3,  3},
86839             { OP_Concat,      6,  3,  3},
86840             { OP_ResultRow,   3,  1,  0},
86841             { OP_IfPos,       1,  0,  0},    /* 9 */
86842             { OP_Halt,        0,  0,  0},
86843           };
86844           r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
86845           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
86846           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
86847           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
86848           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
86849           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_STATIC);
86850           sqlite3VdbeJumpHere(v, addr+9);
86851           sqlite3VdbeJumpHere(v, jmp2);
86852         }
86853         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
86854         sqlite3VdbeJumpHere(v, loopTop);
86855         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
86856           static const VdbeOpList cntIdx[] = {
86857              { OP_Integer,      0,  3,  0},
86858              { OP_Rewind,       0,  0,  0},  /* 1 */
86859              { OP_AddImm,       3,  1,  0},
86860              { OP_Next,         0,  0,  0},  /* 3 */
86861              { OP_Eq,           2,  0,  3},  /* 4 */
86862              { OP_AddImm,       1, -1,  0},
86863              { OP_String8,      0,  2,  0},  /* 6 */
86864              { OP_String8,      0,  3,  0},  /* 7 */
86865              { OP_Concat,       3,  2,  2},
86866              { OP_ResultRow,    2,  1,  0},
86867           };
86868           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
86869           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
86870           sqlite3VdbeJumpHere(v, addr);
86871           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
86872           sqlite3VdbeChangeP1(v, addr+1, j+2);
86873           sqlite3VdbeChangeP2(v, addr+1, addr+4);
86874           sqlite3VdbeChangeP1(v, addr+3, j+2);
86875           sqlite3VdbeChangeP2(v, addr+3, addr+2);
86876           sqlite3VdbeJumpHere(v, addr+4);
86877           sqlite3VdbeChangeP4(v, addr+6, 
86878                      "wrong # of entries in index ", P4_STATIC);
86879           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_STATIC);
86880         }
86881       } 
86882     }
86883     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
86884     sqlite3VdbeChangeP2(v, addr, -mxErr);
86885     sqlite3VdbeJumpHere(v, addr+1);
86886     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
86887   }else
86888 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
86889
86890 #ifndef SQLITE_OMIT_UTF16
86891   /*
86892   **   PRAGMA encoding
86893   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
86894   **
86895   ** In its first form, this pragma returns the encoding of the main
86896   ** database. If the database is not initialized, it is initialized now.
86897   **
86898   ** The second form of this pragma is a no-op if the main database file
86899   ** has not already been initialized. In this case it sets the default
86900   ** encoding that will be used for the main database file if a new file
86901   ** is created. If an existing main database file is opened, then the
86902   ** default text encoding for the existing database is used.
86903   ** 
86904   ** In all cases new databases created using the ATTACH command are
86905   ** created to use the same default text encoding as the main database. If
86906   ** the main database has not been initialized and/or created when ATTACH
86907   ** is executed, this is done before the ATTACH operation.
86908   **
86909   ** In the second form this pragma sets the text encoding to be used in
86910   ** new database files created using this database handle. It is only
86911   ** useful if invoked immediately after the main database i
86912   */
86913   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
86914     static const struct EncName {
86915       char *zName;
86916       u8 enc;
86917     } encnames[] = {
86918       { "UTF8",     SQLITE_UTF8        },
86919       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
86920       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
86921       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
86922       { "UTF16le",  SQLITE_UTF16LE     },
86923       { "UTF16be",  SQLITE_UTF16BE     },
86924       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
86925       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
86926       { 0, 0 }
86927     };
86928     const struct EncName *pEnc;
86929     if( !zRight ){    /* "PRAGMA encoding" */
86930       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
86931       sqlite3VdbeSetNumCols(v, 1);
86932       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
86933       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
86934       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
86935       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
86936       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
86937       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
86938       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
86939     }else{                        /* "PRAGMA encoding = XXX" */
86940       /* Only change the value of sqlite.enc if the database handle is not
86941       ** initialized. If the main database exists, the new sqlite.enc value
86942       ** will be overwritten when the schema is next loaded. If it does not
86943       ** already exists, it will be created to use the new encoding value.
86944       */
86945       if( 
86946         !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
86947         DbHasProperty(db, 0, DB_Empty) 
86948       ){
86949         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
86950           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
86951             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
86952             break;
86953           }
86954         }
86955         if( !pEnc->zName ){
86956           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
86957         }
86958       }
86959     }
86960   }else
86961 #endif /* SQLITE_OMIT_UTF16 */
86962
86963 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
86964   /*
86965   **   PRAGMA [database.]schema_version
86966   **   PRAGMA [database.]schema_version = <integer>
86967   **
86968   **   PRAGMA [database.]user_version
86969   **   PRAGMA [database.]user_version = <integer>
86970   **
86971   ** The pragma's schema_version and user_version are used to set or get
86972   ** the value of the schema-version and user-version, respectively. Both
86973   ** the schema-version and the user-version are 32-bit signed integers
86974   ** stored in the database header.
86975   **
86976   ** The schema-cookie is usually only manipulated internally by SQLite. It
86977   ** is incremented by SQLite whenever the database schema is modified (by
86978   ** creating or dropping a table or index). The schema version is used by
86979   ** SQLite each time a query is executed to ensure that the internal cache
86980   ** of the schema used when compiling the SQL query matches the schema of
86981   ** the database against which the compiled query is actually executed.
86982   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
86983   ** the schema-version is potentially dangerous and may lead to program
86984   ** crashes or database corruption. Use with caution!
86985   **
86986   ** The user-version is not used internally by SQLite. It may be used by
86987   ** applications for any purpose.
86988   */
86989   if( sqlite3StrICmp(zLeft, "schema_version")==0 
86990    || sqlite3StrICmp(zLeft, "user_version")==0 
86991    || sqlite3StrICmp(zLeft, "freelist_count")==0 
86992   ){
86993     int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
86994     sqlite3VdbeUsesBtree(v, iDb);
86995     switch( zLeft[0] ){
86996       case 'f': case 'F':
86997         iCookie = BTREE_FREE_PAGE_COUNT;
86998         break;
86999       case 's': case 'S':
87000         iCookie = BTREE_SCHEMA_VERSION;
87001         break;
87002       default:
87003         iCookie = BTREE_USER_VERSION;
87004         break;
87005     }
87006
87007     if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
87008       /* Write the specified cookie value */
87009       static const VdbeOpList setCookie[] = {
87010         { OP_Transaction,    0,  1,  0},    /* 0 */
87011         { OP_Integer,        0,  1,  0},    /* 1 */
87012         { OP_SetCookie,      0,  0,  1},    /* 2 */
87013       };
87014       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
87015       sqlite3VdbeChangeP1(v, addr, iDb);
87016       sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
87017       sqlite3VdbeChangeP1(v, addr+2, iDb);
87018       sqlite3VdbeChangeP2(v, addr+2, iCookie);
87019     }else{
87020       /* Read the specified cookie value */
87021       static const VdbeOpList readCookie[] = {
87022         { OP_Transaction,     0,  0,  0},    /* 0 */
87023         { OP_ReadCookie,      0,  1,  0},    /* 1 */
87024         { OP_ResultRow,       1,  1,  0}
87025       };
87026       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
87027       sqlite3VdbeChangeP1(v, addr, iDb);
87028       sqlite3VdbeChangeP1(v, addr+1, iDb);
87029       sqlite3VdbeChangeP3(v, addr+1, iCookie);
87030       sqlite3VdbeSetNumCols(v, 1);
87031       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
87032     }
87033   }else
87034 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
87035
87036 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
87037   /*
87038   **   PRAGMA compile_options
87039   **
87040   ** Return the names of all compile-time options used in this build,
87041   ** one option per row.
87042   */
87043   if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
87044     int i = 0;
87045     const char *zOpt;
87046     sqlite3VdbeSetNumCols(v, 1);
87047     pParse->nMem = 1;
87048     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
87049     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
87050       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
87051       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
87052     }
87053   }else
87054 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
87055
87056 #ifndef SQLITE_OMIT_WAL
87057   /*
87058   **   PRAGMA [database.]wal_checkpoint
87059   **
87060   ** Checkpoint the database.
87061   */
87062   if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
87063     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
87064     sqlite3VdbeAddOp3(v, OP_Checkpoint, pId2->z?iDb:SQLITE_MAX_ATTACHED, 0, 0);
87065   }else
87066
87067   /*
87068   **   PRAGMA wal_autocheckpoint
87069   **   PRAGMA wal_autocheckpoint = N
87070   **
87071   ** Configure a database connection to automatically checkpoint a database
87072   ** after accumulating N frames in the log. Or query for the current value
87073   ** of N.
87074   */
87075   if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
87076     if( zRight ){
87077       sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
87078     }
87079     returnSingleInt(pParse, "wal_autocheckpoint", 
87080        db->xWalCallback==sqlite3WalDefaultHook ? 
87081            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
87082   }else
87083 #endif
87084
87085 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
87086   /*
87087   ** Report the current state of file logs for all databases
87088   */
87089   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
87090     static const char *const azLockName[] = {
87091       "unlocked", "shared", "reserved", "pending", "exclusive"
87092     };
87093     int i;
87094     sqlite3VdbeSetNumCols(v, 2);
87095     pParse->nMem = 2;
87096     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
87097     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
87098     for(i=0; i<db->nDb; i++){
87099       Btree *pBt;
87100       Pager *pPager;
87101       const char *zState = "unknown";
87102       int j;
87103       if( db->aDb[i].zName==0 ) continue;
87104       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
87105       pBt = db->aDb[i].pBt;
87106       if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
87107         zState = "closed";
87108       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
87109                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
87110          zState = azLockName[j];
87111       }
87112       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
87113       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
87114     }
87115
87116   }else
87117 #endif
87118
87119 #ifdef SQLITE_HAS_CODEC
87120   if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
87121     sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
87122   }else
87123   if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
87124     sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
87125   }else
87126   if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
87127                  sqlite3StrICmp(zLeft, "hexrekey")==0) ){
87128     int i, h1, h2;
87129     char zKey[40];
87130     for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
87131       h1 += 9*(1&(h1>>6));
87132       h2 += 9*(1&(h2>>6));
87133       zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
87134     }
87135     if( (zLeft[3] & 0xf)==0xb ){
87136       sqlite3_key(db, zKey, i/2);
87137     }else{
87138       sqlite3_rekey(db, zKey, i/2);
87139     }
87140   }else
87141 #endif
87142 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
87143   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
87144 #ifdef SQLITE_HAS_CODEC
87145     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
87146       sqlite3_activate_see(&zRight[4]);
87147     }
87148 #endif
87149 #ifdef SQLITE_ENABLE_CEROD
87150     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
87151       sqlite3_activate_cerod(&zRight[6]);
87152     }
87153 #endif
87154   }else
87155 #endif
87156
87157  
87158   {/* Empty ELSE clause */}
87159
87160   /*
87161   ** Reset the safety level, in case the fullfsync flag or synchronous
87162   ** setting changed.
87163   */
87164 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
87165   if( db->autoCommit ){
87166     sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
87167                (db->flags&SQLITE_FullFSync)!=0,
87168                (db->flags&SQLITE_CkptFullFSync)!=0);
87169   }
87170 #endif
87171 pragma_out:
87172   sqlite3DbFree(db, zLeft);
87173   sqlite3DbFree(db, zRight);
87174 }
87175
87176 #endif /* SQLITE_OMIT_PRAGMA */
87177
87178 /************** End of pragma.c **********************************************/
87179 /************** Begin file prepare.c *****************************************/
87180 /*
87181 ** 2005 May 25
87182 **
87183 ** The author disclaims copyright to this source code.  In place of
87184 ** a legal notice, here is a blessing:
87185 **
87186 **    May you do good and not evil.
87187 **    May you find forgiveness for yourself and forgive others.
87188 **    May you share freely, never taking more than you give.
87189 **
87190 *************************************************************************
87191 ** This file contains the implementation of the sqlite3_prepare()
87192 ** interface, and routines that contribute to loading the database schema
87193 ** from disk.
87194 */
87195
87196 /*
87197 ** Fill the InitData structure with an error message that indicates
87198 ** that the database is corrupt.
87199 */
87200 static void corruptSchema(
87201   InitData *pData,     /* Initialization context */
87202   const char *zObj,    /* Object being parsed at the point of error */
87203   const char *zExtra   /* Error information */
87204 ){
87205   sqlite3 *db = pData->db;
87206   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
87207     if( zObj==0 ) zObj = "?";
87208     sqlite3SetString(pData->pzErrMsg, db,
87209       "malformed database schema (%s)", zObj);
87210     if( zExtra ){
87211       *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg, 
87212                                  "%s - %s", *pData->pzErrMsg, zExtra);
87213     }
87214   }
87215   pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT;
87216 }
87217
87218 /*
87219 ** This is the callback routine for the code that initializes the
87220 ** database.  See sqlite3Init() below for additional information.
87221 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
87222 **
87223 ** Each callback contains the following information:
87224 **
87225 **     argv[0] = name of thing being created
87226 **     argv[1] = root page number for table or index. 0 for trigger or view.
87227 **     argv[2] = SQL text for the CREATE statement.
87228 **
87229 */
87230 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
87231   InitData *pData = (InitData*)pInit;
87232   sqlite3 *db = pData->db;
87233   int iDb = pData->iDb;
87234
87235   assert( argc==3 );
87236   UNUSED_PARAMETER2(NotUsed, argc);
87237   assert( sqlite3_mutex_held(db->mutex) );
87238   DbClearProperty(db, iDb, DB_Empty);
87239   if( db->mallocFailed ){
87240     corruptSchema(pData, argv[0], 0);
87241     return 1;
87242   }
87243
87244   assert( iDb>=0 && iDb<db->nDb );
87245   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
87246   if( argv[1]==0 ){
87247     corruptSchema(pData, argv[0], 0);
87248   }else if( argv[2] && argv[2][0] ){
87249     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
87250     ** But because db->init.busy is set to 1, no VDBE code is generated
87251     ** or executed.  All the parser does is build the internal data
87252     ** structures that describe the table, index, or view.
87253     */
87254     int rc;
87255     sqlite3_stmt *pStmt;
87256     TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
87257
87258     assert( db->init.busy );
87259     db->init.iDb = iDb;
87260     db->init.newTnum = sqlite3Atoi(argv[1]);
87261     db->init.orphanTrigger = 0;
87262     TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
87263     rc = db->errCode;
87264     assert( (rc&0xFF)==(rcp&0xFF) );
87265     db->init.iDb = 0;
87266     if( SQLITE_OK!=rc ){
87267       if( db->init.orphanTrigger ){
87268         assert( iDb==1 );
87269       }else{
87270         pData->rc = rc;
87271         if( rc==SQLITE_NOMEM ){
87272           db->mallocFailed = 1;
87273         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
87274           corruptSchema(pData, argv[0], sqlite3_errmsg(db));
87275         }
87276       }
87277     }
87278     sqlite3_finalize(pStmt);
87279   }else if( argv[0]==0 ){
87280     corruptSchema(pData, 0, 0);
87281   }else{
87282     /* If the SQL column is blank it means this is an index that
87283     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
87284     ** constraint for a CREATE TABLE.  The index should have already
87285     ** been created when we processed the CREATE TABLE.  All we have
87286     ** to do here is record the root page number for that index.
87287     */
87288     Index *pIndex;
87289     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
87290     if( pIndex==0 ){
87291       /* This can occur if there exists an index on a TEMP table which
87292       ** has the same name as another index on a permanent index.  Since
87293       ** the permanent table is hidden by the TEMP table, we can also
87294       ** safely ignore the index on the permanent table.
87295       */
87296       /* Do Nothing */;
87297     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
87298       corruptSchema(pData, argv[0], "invalid rootpage");
87299     }
87300   }
87301   return 0;
87302 }
87303
87304 /*
87305 ** Attempt to read the database schema and initialize internal
87306 ** data structures for a single database file.  The index of the
87307 ** database file is given by iDb.  iDb==0 is used for the main
87308 ** database.  iDb==1 should never be used.  iDb>=2 is used for
87309 ** auxiliary databases.  Return one of the SQLITE_ error codes to
87310 ** indicate success or failure.
87311 */
87312 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
87313   int rc;
87314   int i;
87315   int size;
87316   Table *pTab;
87317   Db *pDb;
87318   char const *azArg[4];
87319   int meta[5];
87320   InitData initData;
87321   char const *zMasterSchema;
87322   char const *zMasterName = SCHEMA_TABLE(iDb);
87323   int openedTransaction = 0;
87324
87325   /*
87326   ** The master database table has a structure like this
87327   */
87328   static const char master_schema[] = 
87329      "CREATE TABLE sqlite_master(\n"
87330      "  type text,\n"
87331      "  name text,\n"
87332      "  tbl_name text,\n"
87333      "  rootpage integer,\n"
87334      "  sql text\n"
87335      ")"
87336   ;
87337 #ifndef SQLITE_OMIT_TEMPDB
87338   static const char temp_master_schema[] = 
87339      "CREATE TEMP TABLE sqlite_temp_master(\n"
87340      "  type text,\n"
87341      "  name text,\n"
87342      "  tbl_name text,\n"
87343      "  rootpage integer,\n"
87344      "  sql text\n"
87345      ")"
87346   ;
87347 #else
87348   #define temp_master_schema 0
87349 #endif
87350
87351   assert( iDb>=0 && iDb<db->nDb );
87352   assert( db->aDb[iDb].pSchema );
87353   assert( sqlite3_mutex_held(db->mutex) );
87354   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
87355
87356   /* zMasterSchema and zInitScript are set to point at the master schema
87357   ** and initialisation script appropriate for the database being
87358   ** initialised. zMasterName is the name of the master table.
87359   */
87360   if( !OMIT_TEMPDB && iDb==1 ){
87361     zMasterSchema = temp_master_schema;
87362   }else{
87363     zMasterSchema = master_schema;
87364   }
87365   zMasterName = SCHEMA_TABLE(iDb);
87366
87367   /* Construct the schema tables.  */
87368   azArg[0] = zMasterName;
87369   azArg[1] = "1";
87370   azArg[2] = zMasterSchema;
87371   azArg[3] = 0;
87372   initData.db = db;
87373   initData.iDb = iDb;
87374   initData.rc = SQLITE_OK;
87375   initData.pzErrMsg = pzErrMsg;
87376   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
87377   if( initData.rc ){
87378     rc = initData.rc;
87379     goto error_out;
87380   }
87381   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
87382   if( ALWAYS(pTab) ){
87383     pTab->tabFlags |= TF_Readonly;
87384   }
87385
87386   /* Create a cursor to hold the database open
87387   */
87388   pDb = &db->aDb[iDb];
87389   if( pDb->pBt==0 ){
87390     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
87391       DbSetProperty(db, 1, DB_SchemaLoaded);
87392     }
87393     return SQLITE_OK;
87394   }
87395
87396   /* If there is not already a read-only (or read-write) transaction opened
87397   ** on the b-tree database, open one now. If a transaction is opened, it 
87398   ** will be closed before this function returns.  */
87399   sqlite3BtreeEnter(pDb->pBt);
87400   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
87401     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
87402     if( rc!=SQLITE_OK ){
87403       sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
87404       goto initone_error_out;
87405     }
87406     openedTransaction = 1;
87407   }
87408
87409   /* Get the database meta information.
87410   **
87411   ** Meta values are as follows:
87412   **    meta[0]   Schema cookie.  Changes with each schema change.
87413   **    meta[1]   File format of schema layer.
87414   **    meta[2]   Size of the page cache.
87415   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
87416   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
87417   **    meta[5]   User version
87418   **    meta[6]   Incremental vacuum mode
87419   **    meta[7]   unused
87420   **    meta[8]   unused
87421   **    meta[9]   unused
87422   **
87423   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
87424   ** the possible values of meta[4].
87425   */
87426   for(i=0; i<ArraySize(meta); i++){
87427     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
87428   }
87429   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
87430
87431   /* If opening a non-empty database, check the text encoding. For the
87432   ** main database, set sqlite3.enc to the encoding of the main database.
87433   ** For an attached db, it is an error if the encoding is not the same
87434   ** as sqlite3.enc.
87435   */
87436   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
87437     if( iDb==0 ){
87438       u8 encoding;
87439       /* If opening the main database, set ENC(db). */
87440       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
87441       if( encoding==0 ) encoding = SQLITE_UTF8;
87442       ENC(db) = encoding;
87443       db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
87444     }else{
87445       /* If opening an attached database, the encoding much match ENC(db) */
87446       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
87447         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
87448             " text encoding as main database");
87449         rc = SQLITE_ERROR;
87450         goto initone_error_out;
87451       }
87452     }
87453   }else{
87454     DbSetProperty(db, iDb, DB_Empty);
87455   }
87456   pDb->pSchema->enc = ENC(db);
87457
87458   if( pDb->pSchema->cache_size==0 ){
87459     size = meta[BTREE_DEFAULT_CACHE_SIZE-1];
87460     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
87461     if( size<0 ) size = -size;
87462     pDb->pSchema->cache_size = size;
87463     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
87464   }
87465
87466   /*
87467   ** file_format==1    Version 3.0.0.
87468   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
87469   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
87470   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
87471   */
87472   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
87473   if( pDb->pSchema->file_format==0 ){
87474     pDb->pSchema->file_format = 1;
87475   }
87476   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
87477     sqlite3SetString(pzErrMsg, db, "unsupported file format");
87478     rc = SQLITE_ERROR;
87479     goto initone_error_out;
87480   }
87481
87482   /* Ticket #2804:  When we open a database in the newer file format,
87483   ** clear the legacy_file_format pragma flag so that a VACUUM will
87484   ** not downgrade the database and thus invalidate any descending
87485   ** indices that the user might have created.
87486   */
87487   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
87488     db->flags &= ~SQLITE_LegacyFileFmt;
87489   }
87490
87491   /* Read the schema information out of the schema tables
87492   */
87493   assert( db->init.busy );
87494   {
87495     char *zSql;
87496     zSql = sqlite3MPrintf(db, 
87497         "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
87498         db->aDb[iDb].zName, zMasterName);
87499 #ifndef SQLITE_OMIT_AUTHORIZATION
87500     {
87501       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
87502       xAuth = db->xAuth;
87503       db->xAuth = 0;
87504 #endif
87505       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
87506 #ifndef SQLITE_OMIT_AUTHORIZATION
87507       db->xAuth = xAuth;
87508     }
87509 #endif
87510     if( rc==SQLITE_OK ) rc = initData.rc;
87511     sqlite3DbFree(db, zSql);
87512 #ifndef SQLITE_OMIT_ANALYZE
87513     if( rc==SQLITE_OK ){
87514       sqlite3AnalysisLoad(db, iDb);
87515     }
87516 #endif
87517   }
87518   if( db->mallocFailed ){
87519     rc = SQLITE_NOMEM;
87520     sqlite3ResetInternalSchema(db, 0);
87521   }
87522   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
87523     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
87524     ** the schema loaded, even if errors occurred. In this situation the 
87525     ** current sqlite3_prepare() operation will fail, but the following one
87526     ** will attempt to compile the supplied statement against whatever subset
87527     ** of the schema was loaded before the error occurred. The primary
87528     ** purpose of this is to allow access to the sqlite_master table
87529     ** even when its contents have been corrupted.
87530     */
87531     DbSetProperty(db, iDb, DB_SchemaLoaded);
87532     rc = SQLITE_OK;
87533   }
87534
87535   /* Jump here for an error that occurs after successfully allocating
87536   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
87537   ** before that point, jump to error_out.
87538   */
87539 initone_error_out:
87540   if( openedTransaction ){
87541     sqlite3BtreeCommit(pDb->pBt);
87542   }
87543   sqlite3BtreeLeave(pDb->pBt);
87544
87545 error_out:
87546   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
87547     db->mallocFailed = 1;
87548   }
87549   return rc;
87550 }
87551
87552 /*
87553 ** Initialize all database files - the main database file, the file
87554 ** used to store temporary tables, and any additional database files
87555 ** created using ATTACH statements.  Return a success code.  If an
87556 ** error occurs, write an error message into *pzErrMsg.
87557 **
87558 ** After a database is initialized, the DB_SchemaLoaded bit is set
87559 ** bit is set in the flags field of the Db structure. If the database
87560 ** file was of zero-length, then the DB_Empty flag is also set.
87561 */
87562 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
87563   int i, rc;
87564   int commit_internal = !(db->flags&SQLITE_InternChanges);
87565   
87566   assert( sqlite3_mutex_held(db->mutex) );
87567   rc = SQLITE_OK;
87568   db->init.busy = 1;
87569   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
87570     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
87571     rc = sqlite3InitOne(db, i, pzErrMsg);
87572     if( rc ){
87573       sqlite3ResetInternalSchema(db, i);
87574     }
87575   }
87576
87577   /* Once all the other databases have been initialised, load the schema
87578   ** for the TEMP database. This is loaded last, as the TEMP database
87579   ** schema may contain references to objects in other databases.
87580   */
87581 #ifndef SQLITE_OMIT_TEMPDB
87582   if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
87583                     && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
87584     rc = sqlite3InitOne(db, 1, pzErrMsg);
87585     if( rc ){
87586       sqlite3ResetInternalSchema(db, 1);
87587     }
87588   }
87589 #endif
87590
87591   db->init.busy = 0;
87592   if( rc==SQLITE_OK && commit_internal ){
87593     sqlite3CommitInternalChanges(db);
87594   }
87595
87596   return rc; 
87597 }
87598
87599 /*
87600 ** This routine is a no-op if the database schema is already initialised.
87601 ** Otherwise, the schema is loaded. An error code is returned.
87602 */
87603 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
87604   int rc = SQLITE_OK;
87605   sqlite3 *db = pParse->db;
87606   assert( sqlite3_mutex_held(db->mutex) );
87607   if( !db->init.busy ){
87608     rc = sqlite3Init(db, &pParse->zErrMsg);
87609   }
87610   if( rc!=SQLITE_OK ){
87611     pParse->rc = rc;
87612     pParse->nErr++;
87613   }
87614   return rc;
87615 }
87616
87617
87618 /*
87619 ** Check schema cookies in all databases.  If any cookie is out
87620 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
87621 ** make no changes to pParse->rc.
87622 */
87623 static void schemaIsValid(Parse *pParse){
87624   sqlite3 *db = pParse->db;
87625   int iDb;
87626   int rc;
87627   int cookie;
87628
87629   assert( pParse->checkSchema );
87630   assert( sqlite3_mutex_held(db->mutex) );
87631   for(iDb=0; iDb<db->nDb; iDb++){
87632     int openedTransaction = 0;         /* True if a transaction is opened */
87633     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
87634     if( pBt==0 ) continue;
87635
87636     /* If there is not already a read-only (or read-write) transaction opened
87637     ** on the b-tree database, open one now. If a transaction is opened, it 
87638     ** will be closed immediately after reading the meta-value. */
87639     if( !sqlite3BtreeIsInReadTrans(pBt) ){
87640       rc = sqlite3BtreeBeginTrans(pBt, 0);
87641       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
87642         db->mallocFailed = 1;
87643       }
87644       if( rc!=SQLITE_OK ) return;
87645       openedTransaction = 1;
87646     }
87647
87648     /* Read the schema cookie from the database. If it does not match the 
87649     ** value stored as part of the in-memory schema representation,
87650     ** set Parse.rc to SQLITE_SCHEMA. */
87651     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
87652     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
87653       pParse->rc = SQLITE_SCHEMA;
87654     }
87655
87656     /* Close the transaction, if one was opened. */
87657     if( openedTransaction ){
87658       sqlite3BtreeCommit(pBt);
87659     }
87660   }
87661 }
87662
87663 /*
87664 ** Convert a schema pointer into the iDb index that indicates
87665 ** which database file in db->aDb[] the schema refers to.
87666 **
87667 ** If the same database is attached more than once, the first
87668 ** attached database is returned.
87669 */
87670 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
87671   int i = -1000000;
87672
87673   /* If pSchema is NULL, then return -1000000. This happens when code in 
87674   ** expr.c is trying to resolve a reference to a transient table (i.e. one
87675   ** created by a sub-select). In this case the return value of this 
87676   ** function should never be used.
87677   **
87678   ** We return -1000000 instead of the more usual -1 simply because using
87679   ** -1000000 as the incorrect index into db->aDb[] is much 
87680   ** more likely to cause a segfault than -1 (of course there are assert()
87681   ** statements too, but it never hurts to play the odds).
87682   */
87683   assert( sqlite3_mutex_held(db->mutex) );
87684   if( pSchema ){
87685     for(i=0; ALWAYS(i<db->nDb); i++){
87686       if( db->aDb[i].pSchema==pSchema ){
87687         break;
87688       }
87689     }
87690     assert( i>=0 && i<db->nDb );
87691   }
87692   return i;
87693 }
87694
87695 /*
87696 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
87697 */
87698 static int sqlite3Prepare(
87699   sqlite3 *db,              /* Database handle. */
87700   const char *zSql,         /* UTF-8 encoded SQL statement. */
87701   int nBytes,               /* Length of zSql in bytes. */
87702   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
87703   Vdbe *pReprepare,         /* VM being reprepared */
87704   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
87705   const char **pzTail       /* OUT: End of parsed string */
87706 ){
87707   Parse *pParse;            /* Parsing context */
87708   char *zErrMsg = 0;        /* Error message */
87709   int rc = SQLITE_OK;       /* Result code */
87710   int i;                    /* Loop counter */
87711
87712   /* Allocate the parsing context */
87713   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
87714   if( pParse==0 ){
87715     rc = SQLITE_NOMEM;
87716     goto end_prepare;
87717   }
87718   pParse->pReprepare = pReprepare;
87719   assert( ppStmt && *ppStmt==0 );
87720   assert( !db->mallocFailed );
87721   assert( sqlite3_mutex_held(db->mutex) );
87722
87723   /* Check to verify that it is possible to get a read lock on all
87724   ** database schemas.  The inability to get a read lock indicates that
87725   ** some other database connection is holding a write-lock, which in
87726   ** turn means that the other connection has made uncommitted changes
87727   ** to the schema.
87728   **
87729   ** Were we to proceed and prepare the statement against the uncommitted
87730   ** schema changes and if those schema changes are subsequently rolled
87731   ** back and different changes are made in their place, then when this
87732   ** prepared statement goes to run the schema cookie would fail to detect
87733   ** the schema change.  Disaster would follow.
87734   **
87735   ** This thread is currently holding mutexes on all Btrees (because
87736   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
87737   ** is not possible for another thread to start a new schema change
87738   ** while this routine is running.  Hence, we do not need to hold 
87739   ** locks on the schema, we just need to make sure nobody else is 
87740   ** holding them.
87741   **
87742   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
87743   ** but it does *not* override schema lock detection, so this all still
87744   ** works even if READ_UNCOMMITTED is set.
87745   */
87746   for(i=0; i<db->nDb; i++) {
87747     Btree *pBt = db->aDb[i].pBt;
87748     if( pBt ){
87749       assert( sqlite3BtreeHoldsMutex(pBt) );
87750       rc = sqlite3BtreeSchemaLocked(pBt);
87751       if( rc ){
87752         const char *zDb = db->aDb[i].zName;
87753         sqlite3Error(db, rc, "database schema is locked: %s", zDb);
87754         testcase( db->flags & SQLITE_ReadUncommitted );
87755         goto end_prepare;
87756       }
87757     }
87758   }
87759
87760   sqlite3VtabUnlockList(db);
87761
87762   pParse->db = db;
87763   pParse->nQueryLoop = (double)1;
87764   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
87765     char *zSqlCopy;
87766     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
87767     testcase( nBytes==mxLen );
87768     testcase( nBytes==mxLen+1 );
87769     if( nBytes>mxLen ){
87770       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
87771       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
87772       goto end_prepare;
87773     }
87774     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
87775     if( zSqlCopy ){
87776       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
87777       sqlite3DbFree(db, zSqlCopy);
87778       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
87779     }else{
87780       pParse->zTail = &zSql[nBytes];
87781     }
87782   }else{
87783     sqlite3RunParser(pParse, zSql, &zErrMsg);
87784   }
87785   assert( 1==(int)pParse->nQueryLoop );
87786
87787   if( db->mallocFailed ){
87788     pParse->rc = SQLITE_NOMEM;
87789   }
87790   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
87791   if( pParse->checkSchema ){
87792     schemaIsValid(pParse);
87793   }
87794   if( pParse->rc==SQLITE_SCHEMA ){
87795     sqlite3ResetInternalSchema(db, 0);
87796   }
87797   if( db->mallocFailed ){
87798     pParse->rc = SQLITE_NOMEM;
87799   }
87800   if( pzTail ){
87801     *pzTail = pParse->zTail;
87802   }
87803   rc = pParse->rc;
87804
87805 #ifndef SQLITE_OMIT_EXPLAIN
87806   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
87807     static const char * const azColName[] = {
87808        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
87809        "selectid", "order", "from", "detail"
87810     };
87811     int iFirst, mx;
87812     if( pParse->explain==2 ){
87813       sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
87814       iFirst = 8;
87815       mx = 12;
87816     }else{
87817       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
87818       iFirst = 0;
87819       mx = 8;
87820     }
87821     for(i=iFirst; i<mx; i++){
87822       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
87823                             azColName[i], SQLITE_STATIC);
87824     }
87825   }
87826 #endif
87827
87828   assert( db->init.busy==0 || saveSqlFlag==0 );
87829   if( db->init.busy==0 ){
87830     Vdbe *pVdbe = pParse->pVdbe;
87831     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
87832   }
87833   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
87834     sqlite3VdbeFinalize(pParse->pVdbe);
87835     assert(!(*ppStmt));
87836   }else{
87837     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
87838   }
87839
87840   if( zErrMsg ){
87841     sqlite3Error(db, rc, "%s", zErrMsg);
87842     sqlite3DbFree(db, zErrMsg);
87843   }else{
87844     sqlite3Error(db, rc, 0);
87845   }
87846
87847   /* Delete any TriggerPrg structures allocated while parsing this statement. */
87848   while( pParse->pTriggerPrg ){
87849     TriggerPrg *pT = pParse->pTriggerPrg;
87850     pParse->pTriggerPrg = pT->pNext;
87851     sqlite3DbFree(db, pT);
87852   }
87853
87854 end_prepare:
87855
87856   sqlite3StackFree(db, pParse);
87857   rc = sqlite3ApiExit(db, rc);
87858   assert( (rc&db->errMask)==rc );
87859   return rc;
87860 }
87861 static int sqlite3LockAndPrepare(
87862   sqlite3 *db,              /* Database handle. */
87863   const char *zSql,         /* UTF-8 encoded SQL statement. */
87864   int nBytes,               /* Length of zSql in bytes. */
87865   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
87866   Vdbe *pOld,               /* VM being reprepared */
87867   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
87868   const char **pzTail       /* OUT: End of parsed string */
87869 ){
87870   int rc;
87871   assert( ppStmt!=0 );
87872   *ppStmt = 0;
87873   if( !sqlite3SafetyCheckOk(db) ){
87874     return SQLITE_MISUSE_BKPT;
87875   }
87876   sqlite3_mutex_enter(db->mutex);
87877   sqlite3BtreeEnterAll(db);
87878   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
87879   if( rc==SQLITE_SCHEMA ){
87880     sqlite3_finalize(*ppStmt);
87881     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
87882   }
87883   sqlite3BtreeLeaveAll(db);
87884   sqlite3_mutex_leave(db->mutex);
87885   return rc;
87886 }
87887
87888 /*
87889 ** Rerun the compilation of a statement after a schema change.
87890 **
87891 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
87892 ** if the statement cannot be recompiled because another connection has
87893 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
87894 ** occurs, return SQLITE_SCHEMA.
87895 */
87896 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
87897   int rc;
87898   sqlite3_stmt *pNew;
87899   const char *zSql;
87900   sqlite3 *db;
87901
87902   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
87903   zSql = sqlite3_sql((sqlite3_stmt *)p);
87904   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
87905   db = sqlite3VdbeDb(p);
87906   assert( sqlite3_mutex_held(db->mutex) );
87907   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
87908   if( rc ){
87909     if( rc==SQLITE_NOMEM ){
87910       db->mallocFailed = 1;
87911     }
87912     assert( pNew==0 );
87913     return rc;
87914   }else{
87915     assert( pNew!=0 );
87916   }
87917   sqlite3VdbeSwap((Vdbe*)pNew, p);
87918   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
87919   sqlite3VdbeResetStepResult((Vdbe*)pNew);
87920   sqlite3VdbeFinalize((Vdbe*)pNew);
87921   return SQLITE_OK;
87922 }
87923
87924
87925 /*
87926 ** Two versions of the official API.  Legacy and new use.  In the legacy
87927 ** version, the original SQL text is not saved in the prepared statement
87928 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
87929 ** sqlite3_step().  In the new version, the original SQL text is retained
87930 ** and the statement is automatically recompiled if an schema change
87931 ** occurs.
87932 */
87933 SQLITE_API int sqlite3_prepare(
87934   sqlite3 *db,              /* Database handle. */
87935   const char *zSql,         /* UTF-8 encoded SQL statement. */
87936   int nBytes,               /* Length of zSql in bytes. */
87937   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
87938   const char **pzTail       /* OUT: End of parsed string */
87939 ){
87940   int rc;
87941   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
87942   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
87943   return rc;
87944 }
87945 SQLITE_API int sqlite3_prepare_v2(
87946   sqlite3 *db,              /* Database handle. */
87947   const char *zSql,         /* UTF-8 encoded SQL statement. */
87948   int nBytes,               /* Length of zSql in bytes. */
87949   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
87950   const char **pzTail       /* OUT: End of parsed string */
87951 ){
87952   int rc;
87953   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
87954   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
87955   return rc;
87956 }
87957
87958
87959 #ifndef SQLITE_OMIT_UTF16
87960 /*
87961 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
87962 */
87963 static int sqlite3Prepare16(
87964   sqlite3 *db,              /* Database handle. */ 
87965   const void *zSql,         /* UTF-16 encoded SQL statement. */
87966   int nBytes,               /* Length of zSql in bytes. */
87967   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
87968   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
87969   const void **pzTail       /* OUT: End of parsed string */
87970 ){
87971   /* This function currently works by first transforming the UTF-16
87972   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
87973   ** tricky bit is figuring out the pointer to return in *pzTail.
87974   */
87975   char *zSql8;
87976   const char *zTail8 = 0;
87977   int rc = SQLITE_OK;
87978
87979   assert( ppStmt );
87980   *ppStmt = 0;
87981   if( !sqlite3SafetyCheckOk(db) ){
87982     return SQLITE_MISUSE_BKPT;
87983   }
87984   sqlite3_mutex_enter(db->mutex);
87985   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
87986   if( zSql8 ){
87987     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
87988   }
87989
87990   if( zTail8 && pzTail ){
87991     /* If sqlite3_prepare returns a tail pointer, we calculate the
87992     ** equivalent pointer into the UTF-16 string by counting the unicode
87993     ** characters between zSql8 and zTail8, and then returning a pointer
87994     ** the same number of characters into the UTF-16 string.
87995     */
87996     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
87997     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
87998   }
87999   sqlite3DbFree(db, zSql8); 
88000   rc = sqlite3ApiExit(db, rc);
88001   sqlite3_mutex_leave(db->mutex);
88002   return rc;
88003 }
88004
88005 /*
88006 ** Two versions of the official API.  Legacy and new use.  In the legacy
88007 ** version, the original SQL text is not saved in the prepared statement
88008 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
88009 ** sqlite3_step().  In the new version, the original SQL text is retained
88010 ** and the statement is automatically recompiled if an schema change
88011 ** occurs.
88012 */
88013 SQLITE_API int sqlite3_prepare16(
88014   sqlite3 *db,              /* Database handle. */ 
88015   const void *zSql,         /* UTF-16 encoded SQL statement. */
88016   int nBytes,               /* Length of zSql in bytes. */
88017   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
88018   const void **pzTail       /* OUT: End of parsed string */
88019 ){
88020   int rc;
88021   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
88022   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
88023   return rc;
88024 }
88025 SQLITE_API int sqlite3_prepare16_v2(
88026   sqlite3 *db,              /* Database handle. */ 
88027   const void *zSql,         /* UTF-16 encoded SQL statement. */
88028   int nBytes,               /* Length of zSql in bytes. */
88029   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
88030   const void **pzTail       /* OUT: End of parsed string */
88031 ){
88032   int rc;
88033   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
88034   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
88035   return rc;
88036 }
88037
88038 #endif /* SQLITE_OMIT_UTF16 */
88039
88040 /************** End of prepare.c *********************************************/
88041 /************** Begin file select.c ******************************************/
88042 /*
88043 ** 2001 September 15
88044 **
88045 ** The author disclaims copyright to this source code.  In place of
88046 ** a legal notice, here is a blessing:
88047 **
88048 **    May you do good and not evil.
88049 **    May you find forgiveness for yourself and forgive others.
88050 **    May you share freely, never taking more than you give.
88051 **
88052 *************************************************************************
88053 ** This file contains C code routines that are called by the parser
88054 ** to handle SELECT statements in SQLite.
88055 */
88056
88057
88058 /*
88059 ** Delete all the content of a Select structure but do not deallocate
88060 ** the select structure itself.
88061 */
88062 static void clearSelect(sqlite3 *db, Select *p){
88063   sqlite3ExprListDelete(db, p->pEList);
88064   sqlite3SrcListDelete(db, p->pSrc);
88065   sqlite3ExprDelete(db, p->pWhere);
88066   sqlite3ExprListDelete(db, p->pGroupBy);
88067   sqlite3ExprDelete(db, p->pHaving);
88068   sqlite3ExprListDelete(db, p->pOrderBy);
88069   sqlite3SelectDelete(db, p->pPrior);
88070   sqlite3ExprDelete(db, p->pLimit);
88071   sqlite3ExprDelete(db, p->pOffset);
88072 }
88073
88074 /*
88075 ** Initialize a SelectDest structure.
88076 */
88077 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
88078   pDest->eDest = (u8)eDest;
88079   pDest->iParm = iParm;
88080   pDest->affinity = 0;
88081   pDest->iMem = 0;
88082   pDest->nMem = 0;
88083 }
88084
88085
88086 /*
88087 ** Allocate a new Select structure and return a pointer to that
88088 ** structure.
88089 */
88090 SQLITE_PRIVATE Select *sqlite3SelectNew(
88091   Parse *pParse,        /* Parsing context */
88092   ExprList *pEList,     /* which columns to include in the result */
88093   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
88094   Expr *pWhere,         /* the WHERE clause */
88095   ExprList *pGroupBy,   /* the GROUP BY clause */
88096   Expr *pHaving,        /* the HAVING clause */
88097   ExprList *pOrderBy,   /* the ORDER BY clause */
88098   int isDistinct,       /* true if the DISTINCT keyword is present */
88099   Expr *pLimit,         /* LIMIT value.  NULL means not used */
88100   Expr *pOffset         /* OFFSET value.  NULL means no offset */
88101 ){
88102   Select *pNew;
88103   Select standin;
88104   sqlite3 *db = pParse->db;
88105   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
88106   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
88107   if( pNew==0 ){
88108     pNew = &standin;
88109     memset(pNew, 0, sizeof(*pNew));
88110   }
88111   if( pEList==0 ){
88112     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
88113   }
88114   pNew->pEList = pEList;
88115   pNew->pSrc = pSrc;
88116   pNew->pWhere = pWhere;
88117   pNew->pGroupBy = pGroupBy;
88118   pNew->pHaving = pHaving;
88119   pNew->pOrderBy = pOrderBy;
88120   pNew->selFlags = isDistinct ? SF_Distinct : 0;
88121   pNew->op = TK_SELECT;
88122   pNew->pLimit = pLimit;
88123   pNew->pOffset = pOffset;
88124   assert( pOffset==0 || pLimit!=0 );
88125   pNew->addrOpenEphm[0] = -1;
88126   pNew->addrOpenEphm[1] = -1;
88127   pNew->addrOpenEphm[2] = -1;
88128   if( db->mallocFailed ) {
88129     clearSelect(db, pNew);
88130     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
88131     pNew = 0;
88132   }
88133   return pNew;
88134 }
88135
88136 /*
88137 ** Delete the given Select structure and all of its substructures.
88138 */
88139 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
88140   if( p ){
88141     clearSelect(db, p);
88142     sqlite3DbFree(db, p);
88143   }
88144 }
88145
88146 /*
88147 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
88148 ** type of join.  Return an integer constant that expresses that type
88149 ** in terms of the following bit values:
88150 **
88151 **     JT_INNER
88152 **     JT_CROSS
88153 **     JT_OUTER
88154 **     JT_NATURAL
88155 **     JT_LEFT
88156 **     JT_RIGHT
88157 **
88158 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
88159 **
88160 ** If an illegal or unsupported join type is seen, then still return
88161 ** a join type, but put an error in the pParse structure.
88162 */
88163 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
88164   int jointype = 0;
88165   Token *apAll[3];
88166   Token *p;
88167                              /*   0123456789 123456789 123456789 123 */
88168   static const char zKeyText[] = "naturaleftouterightfullinnercross";
88169   static const struct {
88170     u8 i;        /* Beginning of keyword text in zKeyText[] */
88171     u8 nChar;    /* Length of the keyword in characters */
88172     u8 code;     /* Join type mask */
88173   } aKeyword[] = {
88174     /* natural */ { 0,  7, JT_NATURAL                },
88175     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
88176     /* outer   */ { 10, 5, JT_OUTER                  },
88177     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
88178     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
88179     /* inner   */ { 23, 5, JT_INNER                  },
88180     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
88181   };
88182   int i, j;
88183   apAll[0] = pA;
88184   apAll[1] = pB;
88185   apAll[2] = pC;
88186   for(i=0; i<3 && apAll[i]; i++){
88187     p = apAll[i];
88188     for(j=0; j<ArraySize(aKeyword); j++){
88189       if( p->n==aKeyword[j].nChar 
88190           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
88191         jointype |= aKeyword[j].code;
88192         break;
88193       }
88194     }
88195     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
88196     if( j>=ArraySize(aKeyword) ){
88197       jointype |= JT_ERROR;
88198       break;
88199     }
88200   }
88201   if(
88202      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
88203      (jointype & JT_ERROR)!=0
88204   ){
88205     const char *zSp = " ";
88206     assert( pB!=0 );
88207     if( pC==0 ){ zSp++; }
88208     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
88209        "%T %T%s%T", pA, pB, zSp, pC);
88210     jointype = JT_INNER;
88211   }else if( (jointype & JT_OUTER)!=0 
88212          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
88213     sqlite3ErrorMsg(pParse, 
88214       "RIGHT and FULL OUTER JOINs are not currently supported");
88215     jointype = JT_INNER;
88216   }
88217   return jointype;
88218 }
88219
88220 /*
88221 ** Return the index of a column in a table.  Return -1 if the column
88222 ** is not contained in the table.
88223 */
88224 static int columnIndex(Table *pTab, const char *zCol){
88225   int i;
88226   for(i=0; i<pTab->nCol; i++){
88227     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
88228   }
88229   return -1;
88230 }
88231
88232 /*
88233 ** Search the first N tables in pSrc, from left to right, looking for a
88234 ** table that has a column named zCol.  
88235 **
88236 ** When found, set *piTab and *piCol to the table index and column index
88237 ** of the matching column and return TRUE.
88238 **
88239 ** If not found, return FALSE.
88240 */
88241 static int tableAndColumnIndex(
88242   SrcList *pSrc,       /* Array of tables to search */
88243   int N,               /* Number of tables in pSrc->a[] to search */
88244   const char *zCol,    /* Name of the column we are looking for */
88245   int *piTab,          /* Write index of pSrc->a[] here */
88246   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
88247 ){
88248   int i;               /* For looping over tables in pSrc */
88249   int iCol;            /* Index of column matching zCol */
88250
88251   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
88252   for(i=0; i<N; i++){
88253     iCol = columnIndex(pSrc->a[i].pTab, zCol);
88254     if( iCol>=0 ){
88255       if( piTab ){
88256         *piTab = i;
88257         *piCol = iCol;
88258       }
88259       return 1;
88260     }
88261   }
88262   return 0;
88263 }
88264
88265 /*
88266 ** This function is used to add terms implied by JOIN syntax to the
88267 ** WHERE clause expression of a SELECT statement. The new term, which
88268 ** is ANDed with the existing WHERE clause, is of the form:
88269 **
88270 **    (tab1.col1 = tab2.col2)
88271 **
88272 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 
88273 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
88274 ** column iColRight of tab2.
88275 */
88276 static void addWhereTerm(
88277   Parse *pParse,                  /* Parsing context */
88278   SrcList *pSrc,                  /* List of tables in FROM clause */
88279   int iLeft,                      /* Index of first table to join in pSrc */
88280   int iColLeft,                   /* Index of column in first table */
88281   int iRight,                     /* Index of second table in pSrc */
88282   int iColRight,                  /* Index of column in second table */
88283   int isOuterJoin,                /* True if this is an OUTER join */
88284   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
88285 ){
88286   sqlite3 *db = pParse->db;
88287   Expr *pE1;
88288   Expr *pE2;
88289   Expr *pEq;
88290
88291   assert( iLeft<iRight );
88292   assert( pSrc->nSrc>iRight );
88293   assert( pSrc->a[iLeft].pTab );
88294   assert( pSrc->a[iRight].pTab );
88295
88296   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
88297   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
88298
88299   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
88300   if( pEq && isOuterJoin ){
88301     ExprSetProperty(pEq, EP_FromJoin);
88302     assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
88303     ExprSetIrreducible(pEq);
88304     pEq->iRightJoinTable = (i16)pE2->iTable;
88305   }
88306   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
88307 }
88308
88309 /*
88310 ** Set the EP_FromJoin property on all terms of the given expression.
88311 ** And set the Expr.iRightJoinTable to iTable for every term in the
88312 ** expression.
88313 **
88314 ** The EP_FromJoin property is used on terms of an expression to tell
88315 ** the LEFT OUTER JOIN processing logic that this term is part of the
88316 ** join restriction specified in the ON or USING clause and not a part
88317 ** of the more general WHERE clause.  These terms are moved over to the
88318 ** WHERE clause during join processing but we need to remember that they
88319 ** originated in the ON or USING clause.
88320 **
88321 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
88322 ** expression depends on table iRightJoinTable even if that table is not
88323 ** explicitly mentioned in the expression.  That information is needed
88324 ** for cases like this:
88325 **
88326 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
88327 **
88328 ** The where clause needs to defer the handling of the t1.x=5
88329 ** term until after the t2 loop of the join.  In that way, a
88330 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
88331 ** defer the handling of t1.x=5, it will be processed immediately
88332 ** after the t1 loop and rows with t1.x!=5 will never appear in
88333 ** the output, which is incorrect.
88334 */
88335 static void setJoinExpr(Expr *p, int iTable){
88336   while( p ){
88337     ExprSetProperty(p, EP_FromJoin);
88338     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
88339     ExprSetIrreducible(p);
88340     p->iRightJoinTable = (i16)iTable;
88341     setJoinExpr(p->pLeft, iTable);
88342     p = p->pRight;
88343   } 
88344 }
88345
88346 /*
88347 ** This routine processes the join information for a SELECT statement.
88348 ** ON and USING clauses are converted into extra terms of the WHERE clause.
88349 ** NATURAL joins also create extra WHERE clause terms.
88350 **
88351 ** The terms of a FROM clause are contained in the Select.pSrc structure.
88352 ** The left most table is the first entry in Select.pSrc.  The right-most
88353 ** table is the last entry.  The join operator is held in the entry to
88354 ** the left.  Thus entry 0 contains the join operator for the join between
88355 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
88356 ** also attached to the left entry.
88357 **
88358 ** This routine returns the number of errors encountered.
88359 */
88360 static int sqliteProcessJoin(Parse *pParse, Select *p){
88361   SrcList *pSrc;                  /* All tables in the FROM clause */
88362   int i, j;                       /* Loop counters */
88363   struct SrcList_item *pLeft;     /* Left table being joined */
88364   struct SrcList_item *pRight;    /* Right table being joined */
88365
88366   pSrc = p->pSrc;
88367   pLeft = &pSrc->a[0];
88368   pRight = &pLeft[1];
88369   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
88370     Table *pLeftTab = pLeft->pTab;
88371     Table *pRightTab = pRight->pTab;
88372     int isOuter;
88373
88374     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
88375     isOuter = (pRight->jointype & JT_OUTER)!=0;
88376
88377     /* When the NATURAL keyword is present, add WHERE clause terms for
88378     ** every column that the two tables have in common.
88379     */
88380     if( pRight->jointype & JT_NATURAL ){
88381       if( pRight->pOn || pRight->pUsing ){
88382         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
88383            "an ON or USING clause", 0);
88384         return 1;
88385       }
88386       for(j=0; j<pRightTab->nCol; j++){
88387         char *zName;   /* Name of column in the right table */
88388         int iLeft;     /* Matching left table */
88389         int iLeftCol;  /* Matching column in the left table */
88390
88391         zName = pRightTab->aCol[j].zName;
88392         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
88393           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
88394                        isOuter, &p->pWhere);
88395         }
88396       }
88397     }
88398
88399     /* Disallow both ON and USING clauses in the same join
88400     */
88401     if( pRight->pOn && pRight->pUsing ){
88402       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
88403         "clauses in the same join");
88404       return 1;
88405     }
88406
88407     /* Add the ON clause to the end of the WHERE clause, connected by
88408     ** an AND operator.
88409     */
88410     if( pRight->pOn ){
88411       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
88412       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
88413       pRight->pOn = 0;
88414     }
88415
88416     /* Create extra terms on the WHERE clause for each column named
88417     ** in the USING clause.  Example: If the two tables to be joined are 
88418     ** A and B and the USING clause names X, Y, and Z, then add this
88419     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
88420     ** Report an error if any column mentioned in the USING clause is
88421     ** not contained in both tables to be joined.
88422     */
88423     if( pRight->pUsing ){
88424       IdList *pList = pRight->pUsing;
88425       for(j=0; j<pList->nId; j++){
88426         char *zName;     /* Name of the term in the USING clause */
88427         int iLeft;       /* Table on the left with matching column name */
88428         int iLeftCol;    /* Column number of matching column on the left */
88429         int iRightCol;   /* Column number of matching column on the right */
88430
88431         zName = pList->a[j].zName;
88432         iRightCol = columnIndex(pRightTab, zName);
88433         if( iRightCol<0
88434          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
88435         ){
88436           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
88437             "not present in both tables", zName);
88438           return 1;
88439         }
88440         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
88441                      isOuter, &p->pWhere);
88442       }
88443     }
88444   }
88445   return 0;
88446 }
88447
88448 /*
88449 ** Insert code into "v" that will push the record on the top of the
88450 ** stack into the sorter.
88451 */
88452 static void pushOntoSorter(
88453   Parse *pParse,         /* Parser context */
88454   ExprList *pOrderBy,    /* The ORDER BY clause */
88455   Select *pSelect,       /* The whole SELECT statement */
88456   int regData            /* Register holding data to be sorted */
88457 ){
88458   Vdbe *v = pParse->pVdbe;
88459   int nExpr = pOrderBy->nExpr;
88460   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
88461   int regRecord = sqlite3GetTempReg(pParse);
88462   sqlite3ExprCacheClear(pParse);
88463   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
88464   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
88465   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
88466   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
88467   sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
88468   sqlite3ReleaseTempReg(pParse, regRecord);
88469   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
88470   if( pSelect->iLimit ){
88471     int addr1, addr2;
88472     int iLimit;
88473     if( pSelect->iOffset ){
88474       iLimit = pSelect->iOffset+1;
88475     }else{
88476       iLimit = pSelect->iLimit;
88477     }
88478     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
88479     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
88480     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
88481     sqlite3VdbeJumpHere(v, addr1);
88482     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
88483     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
88484     sqlite3VdbeJumpHere(v, addr2);
88485   }
88486 }
88487
88488 /*
88489 ** Add code to implement the OFFSET
88490 */
88491 static void codeOffset(
88492   Vdbe *v,          /* Generate code into this VM */
88493   Select *p,        /* The SELECT statement being coded */
88494   int iContinue     /* Jump here to skip the current record */
88495 ){
88496   if( p->iOffset && iContinue!=0 ){
88497     int addr;
88498     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
88499     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
88500     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
88501     VdbeComment((v, "skip OFFSET records"));
88502     sqlite3VdbeJumpHere(v, addr);
88503   }
88504 }
88505
88506 /*
88507 ** Add code that will check to make sure the N registers starting at iMem
88508 ** form a distinct entry.  iTab is a sorting index that holds previously
88509 ** seen combinations of the N values.  A new entry is made in iTab
88510 ** if the current N values are new.
88511 **
88512 ** A jump to addrRepeat is made and the N+1 values are popped from the
88513 ** stack if the top N elements are not distinct.
88514 */
88515 static void codeDistinct(
88516   Parse *pParse,     /* Parsing and code generating context */
88517   int iTab,          /* A sorting index used to test for distinctness */
88518   int addrRepeat,    /* Jump to here if not distinct */
88519   int N,             /* Number of elements */
88520   int iMem           /* First element */
88521 ){
88522   Vdbe *v;
88523   int r1;
88524
88525   v = pParse->pVdbe;
88526   r1 = sqlite3GetTempReg(pParse);
88527   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
88528   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
88529   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
88530   sqlite3ReleaseTempReg(pParse, r1);
88531 }
88532
88533 #ifndef SQLITE_OMIT_SUBQUERY
88534 /*
88535 ** Generate an error message when a SELECT is used within a subexpression
88536 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
88537 ** column.  We do this in a subroutine because the error used to occur
88538 ** in multiple places.  (The error only occurs in one place now, but we
88539 ** retain the subroutine to minimize code disruption.)
88540 */
88541 static int checkForMultiColumnSelectError(
88542   Parse *pParse,       /* Parse context. */
88543   SelectDest *pDest,   /* Destination of SELECT results */
88544   int nExpr            /* Number of result columns returned by SELECT */
88545 ){
88546   int eDest = pDest->eDest;
88547   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
88548     sqlite3ErrorMsg(pParse, "only a single result allowed for "
88549        "a SELECT that is part of an expression");
88550     return 1;
88551   }else{
88552     return 0;
88553   }
88554 }
88555 #endif
88556
88557 /*
88558 ** This routine generates the code for the inside of the inner loop
88559 ** of a SELECT.
88560 **
88561 ** If srcTab and nColumn are both zero, then the pEList expressions
88562 ** are evaluated in order to get the data for this row.  If nColumn>0
88563 ** then data is pulled from srcTab and pEList is used only to get the
88564 ** datatypes for each column.
88565 */
88566 static void selectInnerLoop(
88567   Parse *pParse,          /* The parser context */
88568   Select *p,              /* The complete select statement being coded */
88569   ExprList *pEList,       /* List of values being extracted */
88570   int srcTab,             /* Pull data from this table */
88571   int nColumn,            /* Number of columns in the source table */
88572   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
88573   int distinct,           /* If >=0, make sure results are distinct */
88574   SelectDest *pDest,      /* How to dispose of the results */
88575   int iContinue,          /* Jump here to continue with next row */
88576   int iBreak              /* Jump here to break out of the inner loop */
88577 ){
88578   Vdbe *v = pParse->pVdbe;
88579   int i;
88580   int hasDistinct;        /* True if the DISTINCT keyword is present */
88581   int regResult;              /* Start of memory holding result set */
88582   int eDest = pDest->eDest;   /* How to dispose of results */
88583   int iParm = pDest->iParm;   /* First argument to disposal method */
88584   int nResultCol;             /* Number of result columns */
88585
88586   assert( v );
88587   if( NEVER(v==0) ) return;
88588   assert( pEList!=0 );
88589   hasDistinct = distinct>=0;
88590   if( pOrderBy==0 && !hasDistinct ){
88591     codeOffset(v, p, iContinue);
88592   }
88593
88594   /* Pull the requested columns.
88595   */
88596   if( nColumn>0 ){
88597     nResultCol = nColumn;
88598   }else{
88599     nResultCol = pEList->nExpr;
88600   }
88601   if( pDest->iMem==0 ){
88602     pDest->iMem = pParse->nMem+1;
88603     pDest->nMem = nResultCol;
88604     pParse->nMem += nResultCol;
88605   }else{ 
88606     assert( pDest->nMem==nResultCol );
88607   }
88608   regResult = pDest->iMem;
88609   if( nColumn>0 ){
88610     for(i=0; i<nColumn; i++){
88611       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
88612     }
88613   }else if( eDest!=SRT_Exists ){
88614     /* If the destination is an EXISTS(...) expression, the actual
88615     ** values returned by the SELECT are not required.
88616     */
88617     sqlite3ExprCacheClear(pParse);
88618     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
88619   }
88620   nColumn = nResultCol;
88621
88622   /* If the DISTINCT keyword was present on the SELECT statement
88623   ** and this row has been seen before, then do not make this row
88624   ** part of the result.
88625   */
88626   if( hasDistinct ){
88627     assert( pEList!=0 );
88628     assert( pEList->nExpr==nColumn );
88629     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
88630     if( pOrderBy==0 ){
88631       codeOffset(v, p, iContinue);
88632     }
88633   }
88634
88635   switch( eDest ){
88636     /* In this mode, write each query result to the key of the temporary
88637     ** table iParm.
88638     */
88639 #ifndef SQLITE_OMIT_COMPOUND_SELECT
88640     case SRT_Union: {
88641       int r1;
88642       r1 = sqlite3GetTempReg(pParse);
88643       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
88644       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
88645       sqlite3ReleaseTempReg(pParse, r1);
88646       break;
88647     }
88648
88649     /* Construct a record from the query result, but instead of
88650     ** saving that record, use it as a key to delete elements from
88651     ** the temporary table iParm.
88652     */
88653     case SRT_Except: {
88654       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
88655       break;
88656     }
88657 #endif
88658
88659     /* Store the result as data using a unique key.
88660     */
88661     case SRT_Table:
88662     case SRT_EphemTab: {
88663       int r1 = sqlite3GetTempReg(pParse);
88664       testcase( eDest==SRT_Table );
88665       testcase( eDest==SRT_EphemTab );
88666       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
88667       if( pOrderBy ){
88668         pushOntoSorter(pParse, pOrderBy, p, r1);
88669       }else{
88670         int r2 = sqlite3GetTempReg(pParse);
88671         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
88672         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
88673         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
88674         sqlite3ReleaseTempReg(pParse, r2);
88675       }
88676       sqlite3ReleaseTempReg(pParse, r1);
88677       break;
88678     }
88679
88680 #ifndef SQLITE_OMIT_SUBQUERY
88681     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
88682     ** then there should be a single item on the stack.  Write this
88683     ** item into the set table with bogus data.
88684     */
88685     case SRT_Set: {
88686       assert( nColumn==1 );
88687       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
88688       if( pOrderBy ){
88689         /* At first glance you would think we could optimize out the
88690         ** ORDER BY in this case since the order of entries in the set
88691         ** does not matter.  But there might be a LIMIT clause, in which
88692         ** case the order does matter */
88693         pushOntoSorter(pParse, pOrderBy, p, regResult);
88694       }else{
88695         int r1 = sqlite3GetTempReg(pParse);
88696         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
88697         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
88698         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
88699         sqlite3ReleaseTempReg(pParse, r1);
88700       }
88701       break;
88702     }
88703
88704     /* If any row exist in the result set, record that fact and abort.
88705     */
88706     case SRT_Exists: {
88707       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
88708       /* The LIMIT clause will terminate the loop for us */
88709       break;
88710     }
88711
88712     /* If this is a scalar select that is part of an expression, then
88713     ** store the results in the appropriate memory cell and break out
88714     ** of the scan loop.
88715     */
88716     case SRT_Mem: {
88717       assert( nColumn==1 );
88718       if( pOrderBy ){
88719         pushOntoSorter(pParse, pOrderBy, p, regResult);
88720       }else{
88721         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
88722         /* The LIMIT clause will jump out of the loop for us */
88723       }
88724       break;
88725     }
88726 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
88727
88728     /* Send the data to the callback function or to a subroutine.  In the
88729     ** case of a subroutine, the subroutine itself is responsible for
88730     ** popping the data from the stack.
88731     */
88732     case SRT_Coroutine:
88733     case SRT_Output: {
88734       testcase( eDest==SRT_Coroutine );
88735       testcase( eDest==SRT_Output );
88736       if( pOrderBy ){
88737         int r1 = sqlite3GetTempReg(pParse);
88738         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
88739         pushOntoSorter(pParse, pOrderBy, p, r1);
88740         sqlite3ReleaseTempReg(pParse, r1);
88741       }else if( eDest==SRT_Coroutine ){
88742         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
88743       }else{
88744         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
88745         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
88746       }
88747       break;
88748     }
88749
88750 #if !defined(SQLITE_OMIT_TRIGGER)
88751     /* Discard the results.  This is used for SELECT statements inside
88752     ** the body of a TRIGGER.  The purpose of such selects is to call
88753     ** user-defined functions that have side effects.  We do not care
88754     ** about the actual results of the select.
88755     */
88756     default: {
88757       assert( eDest==SRT_Discard );
88758       break;
88759     }
88760 #endif
88761   }
88762
88763   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
88764   ** there is a sorter, in which case the sorter has already limited
88765   ** the output for us.
88766   */
88767   if( pOrderBy==0 && p->iLimit ){
88768     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
88769   }
88770 }
88771
88772 /*
88773 ** Given an expression list, generate a KeyInfo structure that records
88774 ** the collating sequence for each expression in that expression list.
88775 **
88776 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
88777 ** KeyInfo structure is appropriate for initializing a virtual index to
88778 ** implement that clause.  If the ExprList is the result set of a SELECT
88779 ** then the KeyInfo structure is appropriate for initializing a virtual
88780 ** index to implement a DISTINCT test.
88781 **
88782 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
88783 ** function is responsible for seeing that this structure is eventually
88784 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
88785 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
88786 */
88787 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
88788   sqlite3 *db = pParse->db;
88789   int nExpr;
88790   KeyInfo *pInfo;
88791   struct ExprList_item *pItem;
88792   int i;
88793
88794   nExpr = pList->nExpr;
88795   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
88796   if( pInfo ){
88797     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
88798     pInfo->nField = (u16)nExpr;
88799     pInfo->enc = ENC(db);
88800     pInfo->db = db;
88801     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
88802       CollSeq *pColl;
88803       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
88804       if( !pColl ){
88805         pColl = db->pDfltColl;
88806       }
88807       pInfo->aColl[i] = pColl;
88808       pInfo->aSortOrder[i] = pItem->sortOrder;
88809     }
88810   }
88811   return pInfo;
88812 }
88813
88814 #ifndef SQLITE_OMIT_COMPOUND_SELECT
88815 /*
88816 ** Name of the connection operator, used for error messages.
88817 */
88818 static const char *selectOpName(int id){
88819   char *z;
88820   switch( id ){
88821     case TK_ALL:       z = "UNION ALL";   break;
88822     case TK_INTERSECT: z = "INTERSECT";   break;
88823     case TK_EXCEPT:    z = "EXCEPT";      break;
88824     default:           z = "UNION";       break;
88825   }
88826   return z;
88827 }
88828 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
88829
88830 #ifndef SQLITE_OMIT_EXPLAIN
88831 /*
88832 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
88833 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
88834 ** where the caption is of the form:
88835 **
88836 **   "USE TEMP B-TREE FOR xxx"
88837 **
88838 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
88839 ** is determined by the zUsage argument.
88840 */
88841 static void explainTempTable(Parse *pParse, const char *zUsage){
88842   if( pParse->explain==2 ){
88843     Vdbe *v = pParse->pVdbe;
88844     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
88845     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
88846   }
88847 }
88848
88849 /*
88850 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
88851 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
88852 ** where the caption is of one of the two forms:
88853 **
88854 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
88855 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
88856 **
88857 ** where iSub1 and iSub2 are the integers passed as the corresponding
88858 ** function parameters, and op is the text representation of the parameter
88859 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
88860 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is 
88861 ** false, or the second form if it is true.
88862 */
88863 static void explainComposite(
88864   Parse *pParse,                  /* Parse context */
88865   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
88866   int iSub1,                      /* Subquery id 1 */
88867   int iSub2,                      /* Subquery id 2 */
88868   int bUseTmp                     /* True if a temp table was used */
88869 ){
88870   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
88871   if( pParse->explain==2 ){
88872     Vdbe *v = pParse->pVdbe;
88873     char *zMsg = sqlite3MPrintf(
88874         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
88875         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
88876     );
88877     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
88878   }
88879 }
88880
88881 /*
88882 ** Assign expression b to lvalue a. A second, no-op, version of this macro
88883 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
88884 ** in sqlite3Select() to assign values to structure member variables that
88885 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
88886 ** code with #ifndef directives.
88887 */
88888 # define explainSetInteger(a, b) a = b
88889
88890 #else
88891 /* No-op versions of the explainXXX() functions and macros. */
88892 # define explainTempTable(y,z)
88893 # define explainComposite(v,w,x,y,z)
88894 # define explainSetInteger(y,z)
88895 #endif
88896
88897 /*
88898 ** If the inner loop was generated using a non-null pOrderBy argument,
88899 ** then the results were placed in a sorter.  After the loop is terminated
88900 ** we need to run the sorter and output the results.  The following
88901 ** routine generates the code needed to do that.
88902 */
88903 static void generateSortTail(
88904   Parse *pParse,    /* Parsing context */
88905   Select *p,        /* The SELECT statement */
88906   Vdbe *v,          /* Generate code into this VDBE */
88907   int nColumn,      /* Number of columns of data */
88908   SelectDest *pDest /* Write the sorted results here */
88909 ){
88910   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
88911   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
88912   int addr;
88913   int iTab;
88914   int pseudoTab = 0;
88915   ExprList *pOrderBy = p->pOrderBy;
88916
88917   int eDest = pDest->eDest;
88918   int iParm = pDest->iParm;
88919
88920   int regRow;
88921   int regRowid;
88922
88923   iTab = pOrderBy->iECursor;
88924   regRow = sqlite3GetTempReg(pParse);
88925   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
88926     pseudoTab = pParse->nTab++;
88927     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
88928     regRowid = 0;
88929   }else{
88930     regRowid = sqlite3GetTempReg(pParse);
88931   }
88932   addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
88933   codeOffset(v, p, addrContinue);
88934   sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
88935   switch( eDest ){
88936     case SRT_Table:
88937     case SRT_EphemTab: {
88938       testcase( eDest==SRT_Table );
88939       testcase( eDest==SRT_EphemTab );
88940       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
88941       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
88942       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
88943       break;
88944     }
88945 #ifndef SQLITE_OMIT_SUBQUERY
88946     case SRT_Set: {
88947       assert( nColumn==1 );
88948       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
88949       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
88950       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
88951       break;
88952     }
88953     case SRT_Mem: {
88954       assert( nColumn==1 );
88955       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
88956       /* The LIMIT clause will terminate the loop for us */
88957       break;
88958     }
88959 #endif
88960     default: {
88961       int i;
88962       assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 
88963       testcase( eDest==SRT_Output );
88964       testcase( eDest==SRT_Coroutine );
88965       for(i=0; i<nColumn; i++){
88966         assert( regRow!=pDest->iMem+i );
88967         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
88968         if( i==0 ){
88969           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
88970         }
88971       }
88972       if( eDest==SRT_Output ){
88973         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
88974         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
88975       }else{
88976         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
88977       }
88978       break;
88979     }
88980   }
88981   sqlite3ReleaseTempReg(pParse, regRow);
88982   sqlite3ReleaseTempReg(pParse, regRowid);
88983
88984   /* The bottom of the loop
88985   */
88986   sqlite3VdbeResolveLabel(v, addrContinue);
88987   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
88988   sqlite3VdbeResolveLabel(v, addrBreak);
88989   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
88990     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
88991   }
88992 }
88993
88994 /*
88995 ** Return a pointer to a string containing the 'declaration type' of the
88996 ** expression pExpr. The string may be treated as static by the caller.
88997 **
88998 ** The declaration type is the exact datatype definition extracted from the
88999 ** original CREATE TABLE statement if the expression is a column. The
89000 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
89001 ** is considered a column can be complex in the presence of subqueries. The
89002 ** result-set expression in all of the following SELECT statements is 
89003 ** considered a column by this function.
89004 **
89005 **   SELECT col FROM tbl;
89006 **   SELECT (SELECT col FROM tbl;
89007 **   SELECT (SELECT col FROM tbl);
89008 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
89009 ** 
89010 ** The declaration type for any expression other than a column is NULL.
89011 */
89012 static const char *columnType(
89013   NameContext *pNC, 
89014   Expr *pExpr,
89015   const char **pzOriginDb,
89016   const char **pzOriginTab,
89017   const char **pzOriginCol
89018 ){
89019   char const *zType = 0;
89020   char const *zOriginDb = 0;
89021   char const *zOriginTab = 0;
89022   char const *zOriginCol = 0;
89023   int j;
89024   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
89025
89026   switch( pExpr->op ){
89027     case TK_AGG_COLUMN:
89028     case TK_COLUMN: {
89029       /* The expression is a column. Locate the table the column is being
89030       ** extracted from in NameContext.pSrcList. This table may be real
89031       ** database table or a subquery.
89032       */
89033       Table *pTab = 0;            /* Table structure column is extracted from */
89034       Select *pS = 0;             /* Select the column is extracted from */
89035       int iCol = pExpr->iColumn;  /* Index of column in pTab */
89036       testcase( pExpr->op==TK_AGG_COLUMN );
89037       testcase( pExpr->op==TK_COLUMN );
89038       while( pNC && !pTab ){
89039         SrcList *pTabList = pNC->pSrcList;
89040         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
89041         if( j<pTabList->nSrc ){
89042           pTab = pTabList->a[j].pTab;
89043           pS = pTabList->a[j].pSelect;
89044         }else{
89045           pNC = pNC->pNext;
89046         }
89047       }
89048
89049       if( pTab==0 ){
89050         /* At one time, code such as "SELECT new.x" within a trigger would
89051         ** cause this condition to run.  Since then, we have restructured how
89052         ** trigger code is generated and so this condition is no longer 
89053         ** possible. However, it can still be true for statements like
89054         ** the following:
89055         **
89056         **   CREATE TABLE t1(col INTEGER);
89057         **   SELECT (SELECT t1.col) FROM FROM t1;
89058         **
89059         ** when columnType() is called on the expression "t1.col" in the 
89060         ** sub-select. In this case, set the column type to NULL, even
89061         ** though it should really be "INTEGER".
89062         **
89063         ** This is not a problem, as the column type of "t1.col" is never
89064         ** used. When columnType() is called on the expression 
89065         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
89066         ** branch below.  */
89067         break;
89068       }
89069
89070       assert( pTab && pExpr->pTab==pTab );
89071       if( pS ){
89072         /* The "table" is actually a sub-select or a view in the FROM clause
89073         ** of the SELECT statement. Return the declaration type and origin
89074         ** data for the result-set column of the sub-select.
89075         */
89076         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
89077           /* If iCol is less than zero, then the expression requests the
89078           ** rowid of the sub-select or view. This expression is legal (see 
89079           ** test case misc2.2.2) - it always evaluates to NULL.
89080           */
89081           NameContext sNC;
89082           Expr *p = pS->pEList->a[iCol].pExpr;
89083           sNC.pSrcList = pS->pSrc;
89084           sNC.pNext = pNC;
89085           sNC.pParse = pNC->pParse;
89086           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
89087         }
89088       }else if( ALWAYS(pTab->pSchema) ){
89089         /* A real table */
89090         assert( !pS );
89091         if( iCol<0 ) iCol = pTab->iPKey;
89092         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
89093         if( iCol<0 ){
89094           zType = "INTEGER";
89095           zOriginCol = "rowid";
89096         }else{
89097           zType = pTab->aCol[iCol].zType;
89098           zOriginCol = pTab->aCol[iCol].zName;
89099         }
89100         zOriginTab = pTab->zName;
89101         if( pNC->pParse ){
89102           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
89103           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
89104         }
89105       }
89106       break;
89107     }
89108 #ifndef SQLITE_OMIT_SUBQUERY
89109     case TK_SELECT: {
89110       /* The expression is a sub-select. Return the declaration type and
89111       ** origin info for the single column in the result set of the SELECT
89112       ** statement.
89113       */
89114       NameContext sNC;
89115       Select *pS = pExpr->x.pSelect;
89116       Expr *p = pS->pEList->a[0].pExpr;
89117       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
89118       sNC.pSrcList = pS->pSrc;
89119       sNC.pNext = pNC;
89120       sNC.pParse = pNC->pParse;
89121       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
89122       break;
89123     }
89124 #endif
89125   }
89126   
89127   if( pzOriginDb ){
89128     assert( pzOriginTab && pzOriginCol );
89129     *pzOriginDb = zOriginDb;
89130     *pzOriginTab = zOriginTab;
89131     *pzOriginCol = zOriginCol;
89132   }
89133   return zType;
89134 }
89135
89136 /*
89137 ** Generate code that will tell the VDBE the declaration types of columns
89138 ** in the result set.
89139 */
89140 static void generateColumnTypes(
89141   Parse *pParse,      /* Parser context */
89142   SrcList *pTabList,  /* List of tables */
89143   ExprList *pEList    /* Expressions defining the result set */
89144 ){
89145 #ifndef SQLITE_OMIT_DECLTYPE
89146   Vdbe *v = pParse->pVdbe;
89147   int i;
89148   NameContext sNC;
89149   sNC.pSrcList = pTabList;
89150   sNC.pParse = pParse;
89151   for(i=0; i<pEList->nExpr; i++){
89152     Expr *p = pEList->a[i].pExpr;
89153     const char *zType;
89154 #ifdef SQLITE_ENABLE_COLUMN_METADATA
89155     const char *zOrigDb = 0;
89156     const char *zOrigTab = 0;
89157     const char *zOrigCol = 0;
89158     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
89159
89160     /* The vdbe must make its own copy of the column-type and other 
89161     ** column specific strings, in case the schema is reset before this
89162     ** virtual machine is deleted.
89163     */
89164     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
89165     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
89166     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
89167 #else
89168     zType = columnType(&sNC, p, 0, 0, 0);
89169 #endif
89170     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
89171   }
89172 #endif /* SQLITE_OMIT_DECLTYPE */
89173 }
89174
89175 /*
89176 ** Generate code that will tell the VDBE the names of columns
89177 ** in the result set.  This information is used to provide the
89178 ** azCol[] values in the callback.
89179 */
89180 static void generateColumnNames(
89181   Parse *pParse,      /* Parser context */
89182   SrcList *pTabList,  /* List of tables */
89183   ExprList *pEList    /* Expressions defining the result set */
89184 ){
89185   Vdbe *v = pParse->pVdbe;
89186   int i, j;
89187   sqlite3 *db = pParse->db;
89188   int fullNames, shortNames;
89189
89190 #ifndef SQLITE_OMIT_EXPLAIN
89191   /* If this is an EXPLAIN, skip this step */
89192   if( pParse->explain ){
89193     return;
89194   }
89195 #endif
89196
89197   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
89198   pParse->colNamesSet = 1;
89199   fullNames = (db->flags & SQLITE_FullColNames)!=0;
89200   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
89201   sqlite3VdbeSetNumCols(v, pEList->nExpr);
89202   for(i=0; i<pEList->nExpr; i++){
89203     Expr *p;
89204     p = pEList->a[i].pExpr;
89205     if( NEVER(p==0) ) continue;
89206     if( pEList->a[i].zName ){
89207       char *zName = pEList->a[i].zName;
89208       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
89209     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
89210       Table *pTab;
89211       char *zCol;
89212       int iCol = p->iColumn;
89213       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
89214         if( pTabList->a[j].iCursor==p->iTable ) break;
89215       }
89216       assert( j<pTabList->nSrc );
89217       pTab = pTabList->a[j].pTab;
89218       if( iCol<0 ) iCol = pTab->iPKey;
89219       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
89220       if( iCol<0 ){
89221         zCol = "rowid";
89222       }else{
89223         zCol = pTab->aCol[iCol].zName;
89224       }
89225       if( !shortNames && !fullNames ){
89226         sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
89227             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
89228       }else if( fullNames ){
89229         char *zName = 0;
89230         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
89231         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
89232       }else{
89233         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
89234       }
89235     }else{
89236       sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
89237           sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
89238     }
89239   }
89240   generateColumnTypes(pParse, pTabList, pEList);
89241 }
89242
89243 /*
89244 ** Given a an expression list (which is really the list of expressions
89245 ** that form the result set of a SELECT statement) compute appropriate
89246 ** column names for a table that would hold the expression list.
89247 **
89248 ** All column names will be unique.
89249 **
89250 ** Only the column names are computed.  Column.zType, Column.zColl,
89251 ** and other fields of Column are zeroed.
89252 **
89253 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
89254 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
89255 */
89256 static int selectColumnsFromExprList(
89257   Parse *pParse,          /* Parsing context */
89258   ExprList *pEList,       /* Expr list from which to derive column names */
89259   int *pnCol,             /* Write the number of columns here */
89260   Column **paCol          /* Write the new column list here */
89261 ){
89262   sqlite3 *db = pParse->db;   /* Database connection */
89263   int i, j;                   /* Loop counters */
89264   int cnt;                    /* Index added to make the name unique */
89265   Column *aCol, *pCol;        /* For looping over result columns */
89266   int nCol;                   /* Number of columns in the result set */
89267   Expr *p;                    /* Expression for a single result column */
89268   char *zName;                /* Column name */
89269   int nName;                  /* Size of name in zName[] */
89270
89271   *pnCol = nCol = pEList->nExpr;
89272   aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
89273   if( aCol==0 ) return SQLITE_NOMEM;
89274   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
89275     /* Get an appropriate name for the column
89276     */
89277     p = pEList->a[i].pExpr;
89278     assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
89279                || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
89280     if( (zName = pEList->a[i].zName)!=0 ){
89281       /* If the column contains an "AS <name>" phrase, use <name> as the name */
89282       zName = sqlite3DbStrDup(db, zName);
89283     }else{
89284       Expr *pColExpr = p;  /* The expression that is the result column name */
89285       Table *pTab;         /* Table associated with this expression */
89286       while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
89287       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
89288         /* For columns use the column name name */
89289         int iCol = pColExpr->iColumn;
89290         pTab = pColExpr->pTab;
89291         if( iCol<0 ) iCol = pTab->iPKey;
89292         zName = sqlite3MPrintf(db, "%s",
89293                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
89294       }else if( pColExpr->op==TK_ID ){
89295         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
89296         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
89297       }else{
89298         /* Use the original text of the column expression as its name */
89299         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
89300       }
89301     }
89302     if( db->mallocFailed ){
89303       sqlite3DbFree(db, zName);
89304       break;
89305     }
89306
89307     /* Make sure the column name is unique.  If the name is not unique,
89308     ** append a integer to the name so that it becomes unique.
89309     */
89310     nName = sqlite3Strlen30(zName);
89311     for(j=cnt=0; j<i; j++){
89312       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
89313         char *zNewName;
89314         zName[nName] = 0;
89315         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
89316         sqlite3DbFree(db, zName);
89317         zName = zNewName;
89318         j = -1;
89319         if( zName==0 ) break;
89320       }
89321     }
89322     pCol->zName = zName;
89323   }
89324   if( db->mallocFailed ){
89325     for(j=0; j<i; j++){
89326       sqlite3DbFree(db, aCol[j].zName);
89327     }
89328     sqlite3DbFree(db, aCol);
89329     *paCol = 0;
89330     *pnCol = 0;
89331     return SQLITE_NOMEM;
89332   }
89333   return SQLITE_OK;
89334 }
89335
89336 /*
89337 ** Add type and collation information to a column list based on
89338 ** a SELECT statement.
89339 ** 
89340 ** The column list presumably came from selectColumnNamesFromExprList().
89341 ** The column list has only names, not types or collations.  This
89342 ** routine goes through and adds the types and collations.
89343 **
89344 ** This routine requires that all identifiers in the SELECT
89345 ** statement be resolved.
89346 */
89347 static void selectAddColumnTypeAndCollation(
89348   Parse *pParse,        /* Parsing contexts */
89349   int nCol,             /* Number of columns */
89350   Column *aCol,         /* List of columns */
89351   Select *pSelect       /* SELECT used to determine types and collations */
89352 ){
89353   sqlite3 *db = pParse->db;
89354   NameContext sNC;
89355   Column *pCol;
89356   CollSeq *pColl;
89357   int i;
89358   Expr *p;
89359   struct ExprList_item *a;
89360
89361   assert( pSelect!=0 );
89362   assert( (pSelect->selFlags & SF_Resolved)!=0 );
89363   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
89364   if( db->mallocFailed ) return;
89365   memset(&sNC, 0, sizeof(sNC));
89366   sNC.pSrcList = pSelect->pSrc;
89367   a = pSelect->pEList->a;
89368   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
89369     p = a[i].pExpr;
89370     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
89371     pCol->affinity = sqlite3ExprAffinity(p);
89372     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
89373     pColl = sqlite3ExprCollSeq(pParse, p);
89374     if( pColl ){
89375       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
89376     }
89377   }
89378 }
89379
89380 /*
89381 ** Given a SELECT statement, generate a Table structure that describes
89382 ** the result set of that SELECT.
89383 */
89384 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
89385   Table *pTab;
89386   sqlite3 *db = pParse->db;
89387   int savedFlags;
89388
89389   savedFlags = db->flags;
89390   db->flags &= ~SQLITE_FullColNames;
89391   db->flags |= SQLITE_ShortColNames;
89392   sqlite3SelectPrep(pParse, pSelect, 0);
89393   if( pParse->nErr ) return 0;
89394   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
89395   db->flags = savedFlags;
89396   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
89397   if( pTab==0 ){
89398     return 0;
89399   }
89400   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
89401   ** is disabled */
89402   assert( db->lookaside.bEnabled==0 );
89403   pTab->nRef = 1;
89404   pTab->zName = 0;
89405   pTab->nRowEst = 1000000;
89406   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
89407   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
89408   pTab->iPKey = -1;
89409   if( db->mallocFailed ){
89410     sqlite3DeleteTable(db, pTab);
89411     return 0;
89412   }
89413   return pTab;
89414 }
89415
89416 /*
89417 ** Get a VDBE for the given parser context.  Create a new one if necessary.
89418 ** If an error occurs, return NULL and leave a message in pParse.
89419 */
89420 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
89421   Vdbe *v = pParse->pVdbe;
89422   if( v==0 ){
89423     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
89424 #ifndef SQLITE_OMIT_TRACE
89425     if( v ){
89426       sqlite3VdbeAddOp0(v, OP_Trace);
89427     }
89428 #endif
89429   }
89430   return v;
89431 }
89432
89433
89434 /*
89435 ** Compute the iLimit and iOffset fields of the SELECT based on the
89436 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
89437 ** that appear in the original SQL statement after the LIMIT and OFFSET
89438 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
89439 ** are the integer memory register numbers for counters used to compute 
89440 ** the limit and offset.  If there is no limit and/or offset, then 
89441 ** iLimit and iOffset are negative.
89442 **
89443 ** This routine changes the values of iLimit and iOffset only if
89444 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
89445 ** iOffset should have been preset to appropriate default values
89446 ** (usually but not always -1) prior to calling this routine.
89447 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
89448 ** redefined.  The UNION ALL operator uses this property to force
89449 ** the reuse of the same limit and offset registers across multiple
89450 ** SELECT statements.
89451 */
89452 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
89453   Vdbe *v = 0;
89454   int iLimit = 0;
89455   int iOffset;
89456   int addr1, n;
89457   if( p->iLimit ) return;
89458
89459   /* 
89460   ** "LIMIT -1" always shows all rows.  There is some
89461   ** contraversy about what the correct behavior should be.
89462   ** The current implementation interprets "LIMIT 0" to mean
89463   ** no rows.
89464   */
89465   sqlite3ExprCacheClear(pParse);
89466   assert( p->pOffset==0 || p->pLimit!=0 );
89467   if( p->pLimit ){
89468     p->iLimit = iLimit = ++pParse->nMem;
89469     v = sqlite3GetVdbe(pParse);
89470     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
89471     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
89472       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
89473       VdbeComment((v, "LIMIT counter"));
89474       if( n==0 ){
89475         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
89476       }else{
89477         if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
89478       }
89479     }else{
89480       sqlite3ExprCode(pParse, p->pLimit, iLimit);
89481       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
89482       VdbeComment((v, "LIMIT counter"));
89483       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
89484     }
89485     if( p->pOffset ){
89486       p->iOffset = iOffset = ++pParse->nMem;
89487       pParse->nMem++;   /* Allocate an extra register for limit+offset */
89488       sqlite3ExprCode(pParse, p->pOffset, iOffset);
89489       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
89490       VdbeComment((v, "OFFSET counter"));
89491       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
89492       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
89493       sqlite3VdbeJumpHere(v, addr1);
89494       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
89495       VdbeComment((v, "LIMIT+OFFSET"));
89496       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
89497       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
89498       sqlite3VdbeJumpHere(v, addr1);
89499     }
89500   }
89501 }
89502
89503 #ifndef SQLITE_OMIT_COMPOUND_SELECT
89504 /*
89505 ** Return the appropriate collating sequence for the iCol-th column of
89506 ** the result set for the compound-select statement "p".  Return NULL if
89507 ** the column has no default collating sequence.
89508 **
89509 ** The collating sequence for the compound select is taken from the
89510 ** left-most term of the select that has a collating sequence.
89511 */
89512 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
89513   CollSeq *pRet;
89514   if( p->pPrior ){
89515     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
89516   }else{
89517     pRet = 0;
89518   }
89519   assert( iCol>=0 );
89520   if( pRet==0 && iCol<p->pEList->nExpr ){
89521     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
89522   }
89523   return pRet;
89524 }
89525 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
89526
89527 /* Forward reference */
89528 static int multiSelectOrderBy(
89529   Parse *pParse,        /* Parsing context */
89530   Select *p,            /* The right-most of SELECTs to be coded */
89531   SelectDest *pDest     /* What to do with query results */
89532 );
89533
89534
89535 #ifndef SQLITE_OMIT_COMPOUND_SELECT
89536 /*
89537 ** This routine is called to process a compound query form from
89538 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
89539 ** INTERSECT
89540 **
89541 ** "p" points to the right-most of the two queries.  the query on the
89542 ** left is p->pPrior.  The left query could also be a compound query
89543 ** in which case this routine will be called recursively. 
89544 **
89545 ** The results of the total query are to be written into a destination
89546 ** of type eDest with parameter iParm.
89547 **
89548 ** Example 1:  Consider a three-way compound SQL statement.
89549 **
89550 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
89551 **
89552 ** This statement is parsed up as follows:
89553 **
89554 **     SELECT c FROM t3
89555 **      |
89556 **      `----->  SELECT b FROM t2
89557 **                |
89558 **                `------>  SELECT a FROM t1
89559 **
89560 ** The arrows in the diagram above represent the Select.pPrior pointer.
89561 ** So if this routine is called with p equal to the t3 query, then
89562 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
89563 **
89564 ** Notice that because of the way SQLite parses compound SELECTs, the
89565 ** individual selects always group from left to right.
89566 */
89567 static int multiSelect(
89568   Parse *pParse,        /* Parsing context */
89569   Select *p,            /* The right-most of SELECTs to be coded */
89570   SelectDest *pDest     /* What to do with query results */
89571 ){
89572   int rc = SQLITE_OK;   /* Success code from a subroutine */
89573   Select *pPrior;       /* Another SELECT immediately to our left */
89574   Vdbe *v;              /* Generate code to this VDBE */
89575   SelectDest dest;      /* Alternative data destination */
89576   Select *pDelete = 0;  /* Chain of simple selects to delete */
89577   sqlite3 *db;          /* Database connection */
89578 #ifndef SQLITE_OMIT_EXPLAIN
89579   int iSub1;            /* EQP id of left-hand query */
89580   int iSub2;            /* EQP id of right-hand query */
89581 #endif
89582
89583   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
89584   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
89585   */
89586   assert( p && p->pPrior );  /* Calling function guarantees this much */
89587   db = pParse->db;
89588   pPrior = p->pPrior;
89589   assert( pPrior->pRightmost!=pPrior );
89590   assert( pPrior->pRightmost==p->pRightmost );
89591   dest = *pDest;
89592   if( pPrior->pOrderBy ){
89593     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
89594       selectOpName(p->op));
89595     rc = 1;
89596     goto multi_select_end;
89597   }
89598   if( pPrior->pLimit ){
89599     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
89600       selectOpName(p->op));
89601     rc = 1;
89602     goto multi_select_end;
89603   }
89604
89605   v = sqlite3GetVdbe(pParse);
89606   assert( v!=0 );  /* The VDBE already created by calling function */
89607
89608   /* Create the destination temporary table if necessary
89609   */
89610   if( dest.eDest==SRT_EphemTab ){
89611     assert( p->pEList );
89612     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
89613     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
89614     dest.eDest = SRT_Table;
89615   }
89616
89617   /* Make sure all SELECTs in the statement have the same number of elements
89618   ** in their result sets.
89619   */
89620   assert( p->pEList && pPrior->pEList );
89621   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
89622     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
89623       " do not have the same number of result columns", selectOpName(p->op));
89624     rc = 1;
89625     goto multi_select_end;
89626   }
89627
89628   /* Compound SELECTs that have an ORDER BY clause are handled separately.
89629   */
89630   if( p->pOrderBy ){
89631     return multiSelectOrderBy(pParse, p, pDest);
89632   }
89633
89634   /* Generate code for the left and right SELECT statements.
89635   */
89636   switch( p->op ){
89637     case TK_ALL: {
89638       int addr = 0;
89639       int nLimit;
89640       assert( !pPrior->pLimit );
89641       pPrior->pLimit = p->pLimit;
89642       pPrior->pOffset = p->pOffset;
89643       explainSetInteger(iSub1, pParse->iNextSelectId);
89644       rc = sqlite3Select(pParse, pPrior, &dest);
89645       p->pLimit = 0;
89646       p->pOffset = 0;
89647       if( rc ){
89648         goto multi_select_end;
89649       }
89650       p->pPrior = 0;
89651       p->iLimit = pPrior->iLimit;
89652       p->iOffset = pPrior->iOffset;
89653       if( p->iLimit ){
89654         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
89655         VdbeComment((v, "Jump ahead if LIMIT reached"));
89656       }
89657       explainSetInteger(iSub2, pParse->iNextSelectId);
89658       rc = sqlite3Select(pParse, p, &dest);
89659       testcase( rc!=SQLITE_OK );
89660       pDelete = p->pPrior;
89661       p->pPrior = pPrior;
89662       p->nSelectRow += pPrior->nSelectRow;
89663       if( pPrior->pLimit
89664        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
89665        && p->nSelectRow > (double)nLimit 
89666       ){
89667         p->nSelectRow = (double)nLimit;
89668       }
89669       if( addr ){
89670         sqlite3VdbeJumpHere(v, addr);
89671       }
89672       break;
89673     }
89674     case TK_EXCEPT:
89675     case TK_UNION: {
89676       int unionTab;    /* Cursor number of the temporary table holding result */
89677       u8 op = 0;       /* One of the SRT_ operations to apply to self */
89678       int priorOp;     /* The SRT_ operation to apply to prior selects */
89679       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
89680       int addr;
89681       SelectDest uniondest;
89682
89683       testcase( p->op==TK_EXCEPT );
89684       testcase( p->op==TK_UNION );
89685       priorOp = SRT_Union;
89686       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
89687         /* We can reuse a temporary table generated by a SELECT to our
89688         ** right.
89689         */
89690         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
89691                                      ** of a 3-way or more compound */
89692         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
89693         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
89694         unionTab = dest.iParm;
89695       }else{
89696         /* We will need to create our own temporary table to hold the
89697         ** intermediate results.
89698         */
89699         unionTab = pParse->nTab++;
89700         assert( p->pOrderBy==0 );
89701         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
89702         assert( p->addrOpenEphm[0] == -1 );
89703         p->addrOpenEphm[0] = addr;
89704         p->pRightmost->selFlags |= SF_UsesEphemeral;
89705         assert( p->pEList );
89706       }
89707
89708       /* Code the SELECT statements to our left
89709       */
89710       assert( !pPrior->pOrderBy );
89711       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
89712       explainSetInteger(iSub1, pParse->iNextSelectId);
89713       rc = sqlite3Select(pParse, pPrior, &uniondest);
89714       if( rc ){
89715         goto multi_select_end;
89716       }
89717
89718       /* Code the current SELECT statement
89719       */
89720       if( p->op==TK_EXCEPT ){
89721         op = SRT_Except;
89722       }else{
89723         assert( p->op==TK_UNION );
89724         op = SRT_Union;
89725       }
89726       p->pPrior = 0;
89727       pLimit = p->pLimit;
89728       p->pLimit = 0;
89729       pOffset = p->pOffset;
89730       p->pOffset = 0;
89731       uniondest.eDest = op;
89732       explainSetInteger(iSub2, pParse->iNextSelectId);
89733       rc = sqlite3Select(pParse, p, &uniondest);
89734       testcase( rc!=SQLITE_OK );
89735       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
89736       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
89737       sqlite3ExprListDelete(db, p->pOrderBy);
89738       pDelete = p->pPrior;
89739       p->pPrior = pPrior;
89740       p->pOrderBy = 0;
89741       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
89742       sqlite3ExprDelete(db, p->pLimit);
89743       p->pLimit = pLimit;
89744       p->pOffset = pOffset;
89745       p->iLimit = 0;
89746       p->iOffset = 0;
89747
89748       /* Convert the data in the temporary table into whatever form
89749       ** it is that we currently need.
89750       */
89751       assert( unionTab==dest.iParm || dest.eDest!=priorOp );
89752       if( dest.eDest!=priorOp ){
89753         int iCont, iBreak, iStart;
89754         assert( p->pEList );
89755         if( dest.eDest==SRT_Output ){
89756           Select *pFirst = p;
89757           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
89758           generateColumnNames(pParse, 0, pFirst->pEList);
89759         }
89760         iBreak = sqlite3VdbeMakeLabel(v);
89761         iCont = sqlite3VdbeMakeLabel(v);
89762         computeLimitRegisters(pParse, p, iBreak);
89763         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
89764         iStart = sqlite3VdbeCurrentAddr(v);
89765         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
89766                         0, -1, &dest, iCont, iBreak);
89767         sqlite3VdbeResolveLabel(v, iCont);
89768         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
89769         sqlite3VdbeResolveLabel(v, iBreak);
89770         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
89771       }
89772       break;
89773     }
89774     default: assert( p->op==TK_INTERSECT ); {
89775       int tab1, tab2;
89776       int iCont, iBreak, iStart;
89777       Expr *pLimit, *pOffset;
89778       int addr;
89779       SelectDest intersectdest;
89780       int r1;
89781
89782       /* INTERSECT is different from the others since it requires
89783       ** two temporary tables.  Hence it has its own case.  Begin
89784       ** by allocating the tables we will need.
89785       */
89786       tab1 = pParse->nTab++;
89787       tab2 = pParse->nTab++;
89788       assert( p->pOrderBy==0 );
89789
89790       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
89791       assert( p->addrOpenEphm[0] == -1 );
89792       p->addrOpenEphm[0] = addr;
89793       p->pRightmost->selFlags |= SF_UsesEphemeral;
89794       assert( p->pEList );
89795
89796       /* Code the SELECTs to our left into temporary table "tab1".
89797       */
89798       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
89799       explainSetInteger(iSub1, pParse->iNextSelectId);
89800       rc = sqlite3Select(pParse, pPrior, &intersectdest);
89801       if( rc ){
89802         goto multi_select_end;
89803       }
89804
89805       /* Code the current SELECT into temporary table "tab2"
89806       */
89807       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
89808       assert( p->addrOpenEphm[1] == -1 );
89809       p->addrOpenEphm[1] = addr;
89810       p->pPrior = 0;
89811       pLimit = p->pLimit;
89812       p->pLimit = 0;
89813       pOffset = p->pOffset;
89814       p->pOffset = 0;
89815       intersectdest.iParm = tab2;
89816       explainSetInteger(iSub2, pParse->iNextSelectId);
89817       rc = sqlite3Select(pParse, p, &intersectdest);
89818       testcase( rc!=SQLITE_OK );
89819       pDelete = p->pPrior;
89820       p->pPrior = pPrior;
89821       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
89822       sqlite3ExprDelete(db, p->pLimit);
89823       p->pLimit = pLimit;
89824       p->pOffset = pOffset;
89825
89826       /* Generate code to take the intersection of the two temporary
89827       ** tables.
89828       */
89829       assert( p->pEList );
89830       if( dest.eDest==SRT_Output ){
89831         Select *pFirst = p;
89832         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
89833         generateColumnNames(pParse, 0, pFirst->pEList);
89834       }
89835       iBreak = sqlite3VdbeMakeLabel(v);
89836       iCont = sqlite3VdbeMakeLabel(v);
89837       computeLimitRegisters(pParse, p, iBreak);
89838       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
89839       r1 = sqlite3GetTempReg(pParse);
89840       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
89841       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
89842       sqlite3ReleaseTempReg(pParse, r1);
89843       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
89844                       0, -1, &dest, iCont, iBreak);
89845       sqlite3VdbeResolveLabel(v, iCont);
89846       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
89847       sqlite3VdbeResolveLabel(v, iBreak);
89848       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
89849       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
89850       break;
89851     }
89852   }
89853
89854   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
89855
89856   /* Compute collating sequences used by 
89857   ** temporary tables needed to implement the compound select.
89858   ** Attach the KeyInfo structure to all temporary tables.
89859   **
89860   ** This section is run by the right-most SELECT statement only.
89861   ** SELECT statements to the left always skip this part.  The right-most
89862   ** SELECT might also skip this part if it has no ORDER BY clause and
89863   ** no temp tables are required.
89864   */
89865   if( p->selFlags & SF_UsesEphemeral ){
89866     int i;                        /* Loop counter */
89867     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
89868     Select *pLoop;                /* For looping through SELECT statements */
89869     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
89870     int nCol;                     /* Number of columns in result set */
89871
89872     assert( p->pRightmost==p );
89873     nCol = p->pEList->nExpr;
89874     pKeyInfo = sqlite3DbMallocZero(db,
89875                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
89876     if( !pKeyInfo ){
89877       rc = SQLITE_NOMEM;
89878       goto multi_select_end;
89879     }
89880
89881     pKeyInfo->enc = ENC(db);
89882     pKeyInfo->nField = (u16)nCol;
89883
89884     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
89885       *apColl = multiSelectCollSeq(pParse, p, i);
89886       if( 0==*apColl ){
89887         *apColl = db->pDfltColl;
89888       }
89889     }
89890
89891     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
89892       for(i=0; i<2; i++){
89893         int addr = pLoop->addrOpenEphm[i];
89894         if( addr<0 ){
89895           /* If [0] is unused then [1] is also unused.  So we can
89896           ** always safely abort as soon as the first unused slot is found */
89897           assert( pLoop->addrOpenEphm[1]<0 );
89898           break;
89899         }
89900         sqlite3VdbeChangeP2(v, addr, nCol);
89901         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
89902         pLoop->addrOpenEphm[i] = -1;
89903       }
89904     }
89905     sqlite3DbFree(db, pKeyInfo);
89906   }
89907
89908 multi_select_end:
89909   pDest->iMem = dest.iMem;
89910   pDest->nMem = dest.nMem;
89911   sqlite3SelectDelete(db, pDelete);
89912   return rc;
89913 }
89914 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
89915
89916 /*
89917 ** Code an output subroutine for a coroutine implementation of a
89918 ** SELECT statment.
89919 **
89920 ** The data to be output is contained in pIn->iMem.  There are
89921 ** pIn->nMem columns to be output.  pDest is where the output should
89922 ** be sent.
89923 **
89924 ** regReturn is the number of the register holding the subroutine
89925 ** return address.
89926 **
89927 ** If regPrev>0 then it is the first register in a vector that
89928 ** records the previous output.  mem[regPrev] is a flag that is false
89929 ** if there has been no previous output.  If regPrev>0 then code is
89930 ** generated to suppress duplicates.  pKeyInfo is used for comparing
89931 ** keys.
89932 **
89933 ** If the LIMIT found in p->iLimit is reached, jump immediately to
89934 ** iBreak.
89935 */
89936 static int generateOutputSubroutine(
89937   Parse *pParse,          /* Parsing context */
89938   Select *p,              /* The SELECT statement */
89939   SelectDest *pIn,        /* Coroutine supplying data */
89940   SelectDest *pDest,      /* Where to send the data */
89941   int regReturn,          /* The return address register */
89942   int regPrev,            /* Previous result register.  No uniqueness if 0 */
89943   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
89944   int p4type,             /* The p4 type for pKeyInfo */
89945   int iBreak              /* Jump here if we hit the LIMIT */
89946 ){
89947   Vdbe *v = pParse->pVdbe;
89948   int iContinue;
89949   int addr;
89950
89951   addr = sqlite3VdbeCurrentAddr(v);
89952   iContinue = sqlite3VdbeMakeLabel(v);
89953
89954   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
89955   */
89956   if( regPrev ){
89957     int j1, j2;
89958     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
89959     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
89960                               (char*)pKeyInfo, p4type);
89961     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
89962     sqlite3VdbeJumpHere(v, j1);
89963     sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
89964     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
89965   }
89966   if( pParse->db->mallocFailed ) return 0;
89967
89968   /* Suppress the the first OFFSET entries if there is an OFFSET clause
89969   */
89970   codeOffset(v, p, iContinue);
89971
89972   switch( pDest->eDest ){
89973     /* Store the result as data using a unique key.
89974     */
89975     case SRT_Table:
89976     case SRT_EphemTab: {
89977       int r1 = sqlite3GetTempReg(pParse);
89978       int r2 = sqlite3GetTempReg(pParse);
89979       testcase( pDest->eDest==SRT_Table );
89980       testcase( pDest->eDest==SRT_EphemTab );
89981       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
89982       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
89983       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
89984       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
89985       sqlite3ReleaseTempReg(pParse, r2);
89986       sqlite3ReleaseTempReg(pParse, r1);
89987       break;
89988     }
89989
89990 #ifndef SQLITE_OMIT_SUBQUERY
89991     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
89992     ** then there should be a single item on the stack.  Write this
89993     ** item into the set table with bogus data.
89994     */
89995     case SRT_Set: {
89996       int r1;
89997       assert( pIn->nMem==1 );
89998       p->affinity = 
89999          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
90000       r1 = sqlite3GetTempReg(pParse);
90001       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
90002       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
90003       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
90004       sqlite3ReleaseTempReg(pParse, r1);
90005       break;
90006     }
90007
90008 #if 0  /* Never occurs on an ORDER BY query */
90009     /* If any row exist in the result set, record that fact and abort.
90010     */
90011     case SRT_Exists: {
90012       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
90013       /* The LIMIT clause will terminate the loop for us */
90014       break;
90015     }
90016 #endif
90017
90018     /* If this is a scalar select that is part of an expression, then
90019     ** store the results in the appropriate memory cell and break out
90020     ** of the scan loop.
90021     */
90022     case SRT_Mem: {
90023       assert( pIn->nMem==1 );
90024       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
90025       /* The LIMIT clause will jump out of the loop for us */
90026       break;
90027     }
90028 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
90029
90030     /* The results are stored in a sequence of registers
90031     ** starting at pDest->iMem.  Then the co-routine yields.
90032     */
90033     case SRT_Coroutine: {
90034       if( pDest->iMem==0 ){
90035         pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
90036         pDest->nMem = pIn->nMem;
90037       }
90038       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
90039       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
90040       break;
90041     }
90042
90043     /* If none of the above, then the result destination must be
90044     ** SRT_Output.  This routine is never called with any other
90045     ** destination other than the ones handled above or SRT_Output.
90046     **
90047     ** For SRT_Output, results are stored in a sequence of registers.  
90048     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
90049     ** return the next row of result.
90050     */
90051     default: {
90052       assert( pDest->eDest==SRT_Output );
90053       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
90054       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
90055       break;
90056     }
90057   }
90058
90059   /* Jump to the end of the loop if the LIMIT is reached.
90060   */
90061   if( p->iLimit ){
90062     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
90063   }
90064
90065   /* Generate the subroutine return
90066   */
90067   sqlite3VdbeResolveLabel(v, iContinue);
90068   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
90069
90070   return addr;
90071 }
90072
90073 /*
90074 ** Alternative compound select code generator for cases when there
90075 ** is an ORDER BY clause.
90076 **
90077 ** We assume a query of the following form:
90078 **
90079 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
90080 **
90081 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
90082 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
90083 ** co-routines.  Then run the co-routines in parallel and merge the results
90084 ** into the output.  In addition to the two coroutines (called selectA and
90085 ** selectB) there are 7 subroutines:
90086 **
90087 **    outA:    Move the output of the selectA coroutine into the output
90088 **             of the compound query.
90089 **
90090 **    outB:    Move the output of the selectB coroutine into the output
90091 **             of the compound query.  (Only generated for UNION and
90092 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
90093 **             appears only in B.)
90094 **
90095 **    AltB:    Called when there is data from both coroutines and A<B.
90096 **
90097 **    AeqB:    Called when there is data from both coroutines and A==B.
90098 **
90099 **    AgtB:    Called when there is data from both coroutines and A>B.
90100 **
90101 **    EofA:    Called when data is exhausted from selectA.
90102 **
90103 **    EofB:    Called when data is exhausted from selectB.
90104 **
90105 ** The implementation of the latter five subroutines depend on which 
90106 ** <operator> is used:
90107 **
90108 **
90109 **             UNION ALL         UNION            EXCEPT          INTERSECT
90110 **          -------------  -----------------  --------------  -----------------
90111 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
90112 **
90113 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
90114 **
90115 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
90116 **
90117 **   EofA:   outB, nextB      outB, nextB          halt             halt
90118 **
90119 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
90120 **
90121 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
90122 ** causes an immediate jump to EofA and an EOF on B following nextB causes
90123 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
90124 ** following nextX causes a jump to the end of the select processing.
90125 **
90126 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
90127 ** within the output subroutine.  The regPrev register set holds the previously
90128 ** output value.  A comparison is made against this value and the output
90129 ** is skipped if the next results would be the same as the previous.
90130 **
90131 ** The implementation plan is to implement the two coroutines and seven
90132 ** subroutines first, then put the control logic at the bottom.  Like this:
90133 **
90134 **          goto Init
90135 **     coA: coroutine for left query (A)
90136 **     coB: coroutine for right query (B)
90137 **    outA: output one row of A
90138 **    outB: output one row of B (UNION and UNION ALL only)
90139 **    EofA: ...
90140 **    EofB: ...
90141 **    AltB: ...
90142 **    AeqB: ...
90143 **    AgtB: ...
90144 **    Init: initialize coroutine registers
90145 **          yield coA
90146 **          if eof(A) goto EofA
90147 **          yield coB
90148 **          if eof(B) goto EofB
90149 **    Cmpr: Compare A, B
90150 **          Jump AltB, AeqB, AgtB
90151 **     End: ...
90152 **
90153 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
90154 ** actually called using Gosub and they do not Return.  EofA and EofB loop
90155 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
90156 ** and AgtB jump to either L2 or to one of EofA or EofB.
90157 */
90158 #ifndef SQLITE_OMIT_COMPOUND_SELECT
90159 static int multiSelectOrderBy(
90160   Parse *pParse,        /* Parsing context */
90161   Select *p,            /* The right-most of SELECTs to be coded */
90162   SelectDest *pDest     /* What to do with query results */
90163 ){
90164   int i, j;             /* Loop counters */
90165   Select *pPrior;       /* Another SELECT immediately to our left */
90166   Vdbe *v;              /* Generate code to this VDBE */
90167   SelectDest destA;     /* Destination for coroutine A */
90168   SelectDest destB;     /* Destination for coroutine B */
90169   int regAddrA;         /* Address register for select-A coroutine */
90170   int regEofA;          /* Flag to indicate when select-A is complete */
90171   int regAddrB;         /* Address register for select-B coroutine */
90172   int regEofB;          /* Flag to indicate when select-B is complete */
90173   int addrSelectA;      /* Address of the select-A coroutine */
90174   int addrSelectB;      /* Address of the select-B coroutine */
90175   int regOutA;          /* Address register for the output-A subroutine */
90176   int regOutB;          /* Address register for the output-B subroutine */
90177   int addrOutA;         /* Address of the output-A subroutine */
90178   int addrOutB = 0;     /* Address of the output-B subroutine */
90179   int addrEofA;         /* Address of the select-A-exhausted subroutine */
90180   int addrEofB;         /* Address of the select-B-exhausted subroutine */
90181   int addrAltB;         /* Address of the A<B subroutine */
90182   int addrAeqB;         /* Address of the A==B subroutine */
90183   int addrAgtB;         /* Address of the A>B subroutine */
90184   int regLimitA;        /* Limit register for select-A */
90185   int regLimitB;        /* Limit register for select-A */
90186   int regPrev;          /* A range of registers to hold previous output */
90187   int savedLimit;       /* Saved value of p->iLimit */
90188   int savedOffset;      /* Saved value of p->iOffset */
90189   int labelCmpr;        /* Label for the start of the merge algorithm */
90190   int labelEnd;         /* Label for the end of the overall SELECT stmt */
90191   int j1;               /* Jump instructions that get retargetted */
90192   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
90193   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
90194   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
90195   sqlite3 *db;          /* Database connection */
90196   ExprList *pOrderBy;   /* The ORDER BY clause */
90197   int nOrderBy;         /* Number of terms in the ORDER BY clause */
90198   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
90199 #ifndef SQLITE_OMIT_EXPLAIN
90200   int iSub1;            /* EQP id of left-hand query */
90201   int iSub2;            /* EQP id of right-hand query */
90202 #endif
90203
90204   assert( p->pOrderBy!=0 );
90205   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
90206   db = pParse->db;
90207   v = pParse->pVdbe;
90208   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
90209   labelEnd = sqlite3VdbeMakeLabel(v);
90210   labelCmpr = sqlite3VdbeMakeLabel(v);
90211
90212
90213   /* Patch up the ORDER BY clause
90214   */
90215   op = p->op;  
90216   pPrior = p->pPrior;
90217   assert( pPrior->pOrderBy==0 );
90218   pOrderBy = p->pOrderBy;
90219   assert( pOrderBy );
90220   nOrderBy = pOrderBy->nExpr;
90221
90222   /* For operators other than UNION ALL we have to make sure that
90223   ** the ORDER BY clause covers every term of the result set.  Add
90224   ** terms to the ORDER BY clause as necessary.
90225   */
90226   if( op!=TK_ALL ){
90227     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
90228       struct ExprList_item *pItem;
90229       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
90230         assert( pItem->iCol>0 );
90231         if( pItem->iCol==i ) break;
90232       }
90233       if( j==nOrderBy ){
90234         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
90235         if( pNew==0 ) return SQLITE_NOMEM;
90236         pNew->flags |= EP_IntValue;
90237         pNew->u.iValue = i;
90238         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
90239         pOrderBy->a[nOrderBy++].iCol = (u16)i;
90240       }
90241     }
90242   }
90243
90244   /* Compute the comparison permutation and keyinfo that is used with
90245   ** the permutation used to determine if the next
90246   ** row of results comes from selectA or selectB.  Also add explicit
90247   ** collations to the ORDER BY clause terms so that when the subqueries
90248   ** to the right and the left are evaluated, they use the correct
90249   ** collation.
90250   */
90251   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
90252   if( aPermute ){
90253     struct ExprList_item *pItem;
90254     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
90255       assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
90256       aPermute[i] = pItem->iCol - 1;
90257     }
90258     pKeyMerge =
90259       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
90260     if( pKeyMerge ){
90261       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
90262       pKeyMerge->nField = (u16)nOrderBy;
90263       pKeyMerge->enc = ENC(db);
90264       for(i=0; i<nOrderBy; i++){
90265         CollSeq *pColl;
90266         Expr *pTerm = pOrderBy->a[i].pExpr;
90267         if( pTerm->flags & EP_ExpCollate ){
90268           pColl = pTerm->pColl;
90269         }else{
90270           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
90271           pTerm->flags |= EP_ExpCollate;
90272           pTerm->pColl = pColl;
90273         }
90274         pKeyMerge->aColl[i] = pColl;
90275         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
90276       }
90277     }
90278   }else{
90279     pKeyMerge = 0;
90280   }
90281
90282   /* Reattach the ORDER BY clause to the query.
90283   */
90284   p->pOrderBy = pOrderBy;
90285   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
90286
90287   /* Allocate a range of temporary registers and the KeyInfo needed
90288   ** for the logic that removes duplicate result rows when the
90289   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
90290   */
90291   if( op==TK_ALL ){
90292     regPrev = 0;
90293   }else{
90294     int nExpr = p->pEList->nExpr;
90295     assert( nOrderBy>=nExpr || db->mallocFailed );
90296     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
90297     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
90298     pKeyDup = sqlite3DbMallocZero(db,
90299                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
90300     if( pKeyDup ){
90301       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
90302       pKeyDup->nField = (u16)nExpr;
90303       pKeyDup->enc = ENC(db);
90304       for(i=0; i<nExpr; i++){
90305         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
90306         pKeyDup->aSortOrder[i] = 0;
90307       }
90308     }
90309   }
90310  
90311   /* Separate the left and the right query from one another
90312   */
90313   p->pPrior = 0;
90314   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
90315   if( pPrior->pPrior==0 ){
90316     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
90317   }
90318
90319   /* Compute the limit registers */
90320   computeLimitRegisters(pParse, p, labelEnd);
90321   if( p->iLimit && op==TK_ALL ){
90322     regLimitA = ++pParse->nMem;
90323     regLimitB = ++pParse->nMem;
90324     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
90325                                   regLimitA);
90326     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
90327   }else{
90328     regLimitA = regLimitB = 0;
90329   }
90330   sqlite3ExprDelete(db, p->pLimit);
90331   p->pLimit = 0;
90332   sqlite3ExprDelete(db, p->pOffset);
90333   p->pOffset = 0;
90334
90335   regAddrA = ++pParse->nMem;
90336   regEofA = ++pParse->nMem;
90337   regAddrB = ++pParse->nMem;
90338   regEofB = ++pParse->nMem;
90339   regOutA = ++pParse->nMem;
90340   regOutB = ++pParse->nMem;
90341   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
90342   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
90343
90344   /* Jump past the various subroutines and coroutines to the main
90345   ** merge loop
90346   */
90347   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
90348   addrSelectA = sqlite3VdbeCurrentAddr(v);
90349
90350
90351   /* Generate a coroutine to evaluate the SELECT statement to the
90352   ** left of the compound operator - the "A" select.
90353   */
90354   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
90355   pPrior->iLimit = regLimitA;
90356   explainSetInteger(iSub1, pParse->iNextSelectId);
90357   sqlite3Select(pParse, pPrior, &destA);
90358   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
90359   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
90360   VdbeNoopComment((v, "End coroutine for left SELECT"));
90361
90362   /* Generate a coroutine to evaluate the SELECT statement on 
90363   ** the right - the "B" select
90364   */
90365   addrSelectB = sqlite3VdbeCurrentAddr(v);
90366   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
90367   savedLimit = p->iLimit;
90368   savedOffset = p->iOffset;
90369   p->iLimit = regLimitB;
90370   p->iOffset = 0;  
90371   explainSetInteger(iSub2, pParse->iNextSelectId);
90372   sqlite3Select(pParse, p, &destB);
90373   p->iLimit = savedLimit;
90374   p->iOffset = savedOffset;
90375   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
90376   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
90377   VdbeNoopComment((v, "End coroutine for right SELECT"));
90378
90379   /* Generate a subroutine that outputs the current row of the A
90380   ** select as the next output row of the compound select.
90381   */
90382   VdbeNoopComment((v, "Output routine for A"));
90383   addrOutA = generateOutputSubroutine(pParse,
90384                  p, &destA, pDest, regOutA,
90385                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
90386   
90387   /* Generate a subroutine that outputs the current row of the B
90388   ** select as the next output row of the compound select.
90389   */
90390   if( op==TK_ALL || op==TK_UNION ){
90391     VdbeNoopComment((v, "Output routine for B"));
90392     addrOutB = generateOutputSubroutine(pParse,
90393                  p, &destB, pDest, regOutB,
90394                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
90395   }
90396
90397   /* Generate a subroutine to run when the results from select A
90398   ** are exhausted and only data in select B remains.
90399   */
90400   VdbeNoopComment((v, "eof-A subroutine"));
90401   if( op==TK_EXCEPT || op==TK_INTERSECT ){
90402     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
90403   }else{  
90404     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
90405     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
90406     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
90407     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
90408     p->nSelectRow += pPrior->nSelectRow;
90409   }
90410
90411   /* Generate a subroutine to run when the results from select B
90412   ** are exhausted and only data in select A remains.
90413   */
90414   if( op==TK_INTERSECT ){
90415     addrEofB = addrEofA;
90416     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
90417   }else{  
90418     VdbeNoopComment((v, "eof-B subroutine"));
90419     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
90420     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
90421     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
90422     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
90423   }
90424
90425   /* Generate code to handle the case of A<B
90426   */
90427   VdbeNoopComment((v, "A-lt-B subroutine"));
90428   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
90429   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
90430   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
90431   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
90432
90433   /* Generate code to handle the case of A==B
90434   */
90435   if( op==TK_ALL ){
90436     addrAeqB = addrAltB;
90437   }else if( op==TK_INTERSECT ){
90438     addrAeqB = addrAltB;
90439     addrAltB++;
90440   }else{
90441     VdbeNoopComment((v, "A-eq-B subroutine"));
90442     addrAeqB =
90443     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
90444     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
90445     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
90446   }
90447
90448   /* Generate code to handle the case of A>B
90449   */
90450   VdbeNoopComment((v, "A-gt-B subroutine"));
90451   addrAgtB = sqlite3VdbeCurrentAddr(v);
90452   if( op==TK_ALL || op==TK_UNION ){
90453     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
90454   }
90455   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
90456   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
90457   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
90458
90459   /* This code runs once to initialize everything.
90460   */
90461   sqlite3VdbeJumpHere(v, j1);
90462   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
90463   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
90464   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
90465   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
90466   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
90467   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
90468
90469   /* Implement the main merge loop
90470   */
90471   sqlite3VdbeResolveLabel(v, labelCmpr);
90472   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
90473   sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
90474                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
90475   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
90476
90477   /* Release temporary registers
90478   */
90479   if( regPrev ){
90480     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
90481   }
90482
90483   /* Jump to the this point in order to terminate the query.
90484   */
90485   sqlite3VdbeResolveLabel(v, labelEnd);
90486
90487   /* Set the number of output columns
90488   */
90489   if( pDest->eDest==SRT_Output ){
90490     Select *pFirst = pPrior;
90491     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
90492     generateColumnNames(pParse, 0, pFirst->pEList);
90493   }
90494
90495   /* Reassembly the compound query so that it will be freed correctly
90496   ** by the calling function */
90497   if( p->pPrior ){
90498     sqlite3SelectDelete(db, p->pPrior);
90499   }
90500   p->pPrior = pPrior;
90501
90502   /*** TBD:  Insert subroutine calls to close cursors on incomplete
90503   **** subqueries ****/
90504   explainComposite(pParse, p->op, iSub1, iSub2, 0);
90505   return SQLITE_OK;
90506 }
90507 #endif
90508
90509 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
90510 /* Forward Declarations */
90511 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
90512 static void substSelect(sqlite3*, Select *, int, ExprList *);
90513
90514 /*
90515 ** Scan through the expression pExpr.  Replace every reference to
90516 ** a column in table number iTable with a copy of the iColumn-th
90517 ** entry in pEList.  (But leave references to the ROWID column 
90518 ** unchanged.)
90519 **
90520 ** This routine is part of the flattening procedure.  A subquery
90521 ** whose result set is defined by pEList appears as entry in the
90522 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
90523 ** FORM clause entry is iTable.  This routine make the necessary 
90524 ** changes to pExpr so that it refers directly to the source table
90525 ** of the subquery rather the result set of the subquery.
90526 */
90527 static Expr *substExpr(
90528   sqlite3 *db,        /* Report malloc errors to this connection */
90529   Expr *pExpr,        /* Expr in which substitution occurs */
90530   int iTable,         /* Table to be substituted */
90531   ExprList *pEList    /* Substitute expressions */
90532 ){
90533   if( pExpr==0 ) return 0;
90534   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
90535     if( pExpr->iColumn<0 ){
90536       pExpr->op = TK_NULL;
90537     }else{
90538       Expr *pNew;
90539       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
90540       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
90541       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
90542       if( pNew && pExpr->pColl ){
90543         pNew->pColl = pExpr->pColl;
90544       }
90545       sqlite3ExprDelete(db, pExpr);
90546       pExpr = pNew;
90547     }
90548   }else{
90549     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
90550     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
90551     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
90552       substSelect(db, pExpr->x.pSelect, iTable, pEList);
90553     }else{
90554       substExprList(db, pExpr->x.pList, iTable, pEList);
90555     }
90556   }
90557   return pExpr;
90558 }
90559 static void substExprList(
90560   sqlite3 *db,         /* Report malloc errors here */
90561   ExprList *pList,     /* List to scan and in which to make substitutes */
90562   int iTable,          /* Table to be substituted */
90563   ExprList *pEList     /* Substitute values */
90564 ){
90565   int i;
90566   if( pList==0 ) return;
90567   for(i=0; i<pList->nExpr; i++){
90568     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
90569   }
90570 }
90571 static void substSelect(
90572   sqlite3 *db,         /* Report malloc errors here */
90573   Select *p,           /* SELECT statement in which to make substitutions */
90574   int iTable,          /* Table to be replaced */
90575   ExprList *pEList     /* Substitute values */
90576 ){
90577   SrcList *pSrc;
90578   struct SrcList_item *pItem;
90579   int i;
90580   if( !p ) return;
90581   substExprList(db, p->pEList, iTable, pEList);
90582   substExprList(db, p->pGroupBy, iTable, pEList);
90583   substExprList(db, p->pOrderBy, iTable, pEList);
90584   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
90585   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
90586   substSelect(db, p->pPrior, iTable, pEList);
90587   pSrc = p->pSrc;
90588   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
90589   if( ALWAYS(pSrc) ){
90590     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
90591       substSelect(db, pItem->pSelect, iTable, pEList);
90592     }
90593   }
90594 }
90595 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
90596
90597 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
90598 /*
90599 ** This routine attempts to flatten subqueries in order to speed
90600 ** execution.  It returns 1 if it makes changes and 0 if no flattening
90601 ** occurs.
90602 **
90603 ** To understand the concept of flattening, consider the following
90604 ** query:
90605 **
90606 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
90607 **
90608 ** The default way of implementing this query is to execute the
90609 ** subquery first and store the results in a temporary table, then
90610 ** run the outer query on that temporary table.  This requires two
90611 ** passes over the data.  Furthermore, because the temporary table
90612 ** has no indices, the WHERE clause on the outer query cannot be
90613 ** optimized.
90614 **
90615 ** This routine attempts to rewrite queries such as the above into
90616 ** a single flat select, like this:
90617 **
90618 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
90619 **
90620 ** The code generated for this simpification gives the same result
90621 ** but only has to scan the data once.  And because indices might 
90622 ** exist on the table t1, a complete scan of the data might be
90623 ** avoided.
90624 **
90625 ** Flattening is only attempted if all of the following are true:
90626 **
90627 **   (1)  The subquery and the outer query do not both use aggregates.
90628 **
90629 **   (2)  The subquery is not an aggregate or the outer query is not a join.
90630 **
90631 **   (3)  The subquery is not the right operand of a left outer join
90632 **        (Originally ticket #306.  Strengthened by ticket #3300)
90633 **
90634 **   (4)  The subquery is not DISTINCT.
90635 **
90636 **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
90637 **        sub-queries that were excluded from this optimization. Restriction 
90638 **        (4) has since been expanded to exclude all DISTINCT subqueries.
90639 **
90640 **   (6)  The subquery does not use aggregates or the outer query is not
90641 **        DISTINCT.
90642 **
90643 **   (7)  The subquery has a FROM clause.
90644 **
90645 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
90646 **
90647 **   (9)  The subquery does not use LIMIT or the outer query does not use
90648 **        aggregates.
90649 **
90650 **  (10)  The subquery does not use aggregates or the outer query does not
90651 **        use LIMIT.
90652 **
90653 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
90654 **
90655 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
90656 **        a separate restriction deriving from ticket #350.
90657 **
90658 **  (13)  The subquery and outer query do not both use LIMIT.
90659 **
90660 **  (14)  The subquery does not use OFFSET.
90661 **
90662 **  (15)  The outer query is not part of a compound select or the
90663 **        subquery does not have a LIMIT clause.
90664 **        (See ticket #2339 and ticket [02a8e81d44]).
90665 **
90666 **  (16)  The outer query is not an aggregate or the subquery does
90667 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
90668 **        until we introduced the group_concat() function.  
90669 **
90670 **  (17)  The sub-query is not a compound select, or it is a UNION ALL 
90671 **        compound clause made up entirely of non-aggregate queries, and 
90672 **        the parent query:
90673 **
90674 **          * is not itself part of a compound select,
90675 **          * is not an aggregate or DISTINCT query, and
90676 **          * has no other tables or sub-selects in the FROM clause.
90677 **
90678 **        The parent and sub-query may contain WHERE clauses. Subject to
90679 **        rules (11), (13) and (14), they may also contain ORDER BY,
90680 **        LIMIT and OFFSET clauses.
90681 **
90682 **  (18)  If the sub-query is a compound select, then all terms of the
90683 **        ORDER by clause of the parent must be simple references to 
90684 **        columns of the sub-query.
90685 **
90686 **  (19)  The subquery does not use LIMIT or the outer query does not
90687 **        have a WHERE clause.
90688 **
90689 **  (20)  If the sub-query is a compound select, then it must not use
90690 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
90691 **        somewhat by saying that the terms of the ORDER BY clause must
90692 **        appear as unmodified result columns in the outer query.  But
90693 **        have other optimizations in mind to deal with that case.
90694 **
90695 ** In this routine, the "p" parameter is a pointer to the outer query.
90696 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
90697 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
90698 **
90699 ** If flattening is not attempted, this routine is a no-op and returns 0.
90700 ** If flattening is attempted this routine returns 1.
90701 **
90702 ** All of the expression analysis must occur on both the outer query and
90703 ** the subquery before this routine runs.
90704 */
90705 static int flattenSubquery(
90706   Parse *pParse,       /* Parsing context */
90707   Select *p,           /* The parent or outer SELECT statement */
90708   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
90709   int isAgg,           /* True if outer SELECT uses aggregate functions */
90710   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
90711 ){
90712   const char *zSavedAuthContext = pParse->zAuthContext;
90713   Select *pParent;
90714   Select *pSub;       /* The inner query or "subquery" */
90715   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
90716   SrcList *pSrc;      /* The FROM clause of the outer query */
90717   SrcList *pSubSrc;   /* The FROM clause of the subquery */
90718   ExprList *pList;    /* The result set of the outer query */
90719   int iParent;        /* VDBE cursor number of the pSub result set temp table */
90720   int i;              /* Loop counter */
90721   Expr *pWhere;                    /* The WHERE clause */
90722   struct SrcList_item *pSubitem;   /* The subquery */
90723   sqlite3 *db = pParse->db;
90724
90725   /* Check to see if flattening is permitted.  Return 0 if not.
90726   */
90727   assert( p!=0 );
90728   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
90729   if( db->flags & SQLITE_QueryFlattener ) return 0;
90730   pSrc = p->pSrc;
90731   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
90732   pSubitem = &pSrc->a[iFrom];
90733   iParent = pSubitem->iCursor;
90734   pSub = pSubitem->pSelect;
90735   assert( pSub!=0 );
90736   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
90737   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
90738   pSubSrc = pSub->pSrc;
90739   assert( pSubSrc );
90740   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
90741   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
90742   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
90743   ** became arbitrary expressions, we were forced to add restrictions (13)
90744   ** and (14). */
90745   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
90746   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
90747   if( p->pRightmost && pSub->pLimit ){
90748     return 0;                                            /* Restriction (15) */
90749   }
90750   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
90751   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
90752   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
90753      return 0;         /* Restrictions (8)(9) */
90754   }
90755   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
90756      return 0;         /* Restriction (6)  */
90757   }
90758   if( p->pOrderBy && pSub->pOrderBy ){
90759      return 0;                                           /* Restriction (11) */
90760   }
90761   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
90762   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
90763
90764   /* OBSOLETE COMMENT 1:
90765   ** Restriction 3:  If the subquery is a join, make sure the subquery is 
90766   ** not used as the right operand of an outer join.  Examples of why this
90767   ** is not allowed:
90768   **
90769   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
90770   **
90771   ** If we flatten the above, we would get
90772   **
90773   **         (t1 LEFT OUTER JOIN t2) JOIN t3
90774   **
90775   ** which is not at all the same thing.
90776   **
90777   ** OBSOLETE COMMENT 2:
90778   ** Restriction 12:  If the subquery is the right operand of a left outer
90779   ** join, make sure the subquery has no WHERE clause.
90780   ** An examples of why this is not allowed:
90781   **
90782   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
90783   **
90784   ** If we flatten the above, we would get
90785   **
90786   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
90787   **
90788   ** But the t2.x>0 test will always fail on a NULL row of t2, which
90789   ** effectively converts the OUTER JOIN into an INNER JOIN.
90790   **
90791   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
90792   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
90793   ** is fraught with danger.  Best to avoid the whole thing.  If the
90794   ** subquery is the right term of a LEFT JOIN, then do not flatten.
90795   */
90796   if( (pSubitem->jointype & JT_OUTER)!=0 ){
90797     return 0;
90798   }
90799
90800   /* Restriction 17: If the sub-query is a compound SELECT, then it must
90801   ** use only the UNION ALL operator. And none of the simple select queries
90802   ** that make up the compound SELECT are allowed to be aggregate or distinct
90803   ** queries.
90804   */
90805   if( pSub->pPrior ){
90806     if( pSub->pOrderBy ){
90807       return 0;  /* Restriction 20 */
90808     }
90809     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
90810       return 0;
90811     }
90812     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
90813       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
90814       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
90815       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
90816        || (pSub1->pPrior && pSub1->op!=TK_ALL) 
90817        || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
90818       ){
90819         return 0;
90820       }
90821     }
90822
90823     /* Restriction 18. */
90824     if( p->pOrderBy ){
90825       int ii;
90826       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
90827         if( p->pOrderBy->a[ii].iCol==0 ) return 0;
90828       }
90829     }
90830   }
90831
90832   /***** If we reach this point, flattening is permitted. *****/
90833
90834   /* Authorize the subquery */
90835   pParse->zAuthContext = pSubitem->zName;
90836   sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
90837   pParse->zAuthContext = zSavedAuthContext;
90838
90839   /* If the sub-query is a compound SELECT statement, then (by restrictions
90840   ** 17 and 18 above) it must be a UNION ALL and the parent query must 
90841   ** be of the form:
90842   **
90843   **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
90844   **
90845   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
90846   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 
90847   ** OFFSET clauses and joins them to the left-hand-side of the original
90848   ** using UNION ALL operators. In this case N is the number of simple
90849   ** select statements in the compound sub-query.
90850   **
90851   ** Example:
90852   **
90853   **     SELECT a+1 FROM (
90854   **        SELECT x FROM tab
90855   **        UNION ALL
90856   **        SELECT y FROM tab
90857   **        UNION ALL
90858   **        SELECT abs(z*2) FROM tab2
90859   **     ) WHERE a!=5 ORDER BY 1
90860   **
90861   ** Transformed into:
90862   **
90863   **     SELECT x+1 FROM tab WHERE x+1!=5
90864   **     UNION ALL
90865   **     SELECT y+1 FROM tab WHERE y+1!=5
90866   **     UNION ALL
90867   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
90868   **     ORDER BY 1
90869   **
90870   ** We call this the "compound-subquery flattening".
90871   */
90872   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
90873     Select *pNew;
90874     ExprList *pOrderBy = p->pOrderBy;
90875     Expr *pLimit = p->pLimit;
90876     Select *pPrior = p->pPrior;
90877     p->pOrderBy = 0;
90878     p->pSrc = 0;
90879     p->pPrior = 0;
90880     p->pLimit = 0;
90881     pNew = sqlite3SelectDup(db, p, 0);
90882     p->pLimit = pLimit;
90883     p->pOrderBy = pOrderBy;
90884     p->pSrc = pSrc;
90885     p->op = TK_ALL;
90886     p->pRightmost = 0;
90887     if( pNew==0 ){
90888       pNew = pPrior;
90889     }else{
90890       pNew->pPrior = pPrior;
90891       pNew->pRightmost = 0;
90892     }
90893     p->pPrior = pNew;
90894     if( db->mallocFailed ) return 1;
90895   }
90896
90897   /* Begin flattening the iFrom-th entry of the FROM clause 
90898   ** in the outer query.
90899   */
90900   pSub = pSub1 = pSubitem->pSelect;
90901
90902   /* Delete the transient table structure associated with the
90903   ** subquery
90904   */
90905   sqlite3DbFree(db, pSubitem->zDatabase);
90906   sqlite3DbFree(db, pSubitem->zName);
90907   sqlite3DbFree(db, pSubitem->zAlias);
90908   pSubitem->zDatabase = 0;
90909   pSubitem->zName = 0;
90910   pSubitem->zAlias = 0;
90911   pSubitem->pSelect = 0;
90912
90913   /* Defer deleting the Table object associated with the
90914   ** subquery until code generation is
90915   ** complete, since there may still exist Expr.pTab entries that
90916   ** refer to the subquery even after flattening.  Ticket #3346.
90917   **
90918   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
90919   */
90920   if( ALWAYS(pSubitem->pTab!=0) ){
90921     Table *pTabToDel = pSubitem->pTab;
90922     if( pTabToDel->nRef==1 ){
90923       Parse *pToplevel = sqlite3ParseToplevel(pParse);
90924       pTabToDel->pNextZombie = pToplevel->pZombieTab;
90925       pToplevel->pZombieTab = pTabToDel;
90926     }else{
90927       pTabToDel->nRef--;
90928     }
90929     pSubitem->pTab = 0;
90930   }
90931
90932   /* The following loop runs once for each term in a compound-subquery
90933   ** flattening (as described above).  If we are doing a different kind
90934   ** of flattening - a flattening other than a compound-subquery flattening -
90935   ** then this loop only runs once.
90936   **
90937   ** This loop moves all of the FROM elements of the subquery into the
90938   ** the FROM clause of the outer query.  Before doing this, remember
90939   ** the cursor number for the original outer query FROM element in
90940   ** iParent.  The iParent cursor will never be used.  Subsequent code
90941   ** will scan expressions looking for iParent references and replace
90942   ** those references with expressions that resolve to the subquery FROM
90943   ** elements we are now copying in.
90944   */
90945   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
90946     int nSubSrc;
90947     u8 jointype = 0;
90948     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
90949     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
90950     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
90951
90952     if( pSrc ){
90953       assert( pParent==p );  /* First time through the loop */
90954       jointype = pSubitem->jointype;
90955     }else{
90956       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
90957       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
90958       if( pSrc==0 ){
90959         assert( db->mallocFailed );
90960         break;
90961       }
90962     }
90963
90964     /* The subquery uses a single slot of the FROM clause of the outer
90965     ** query.  If the subquery has more than one element in its FROM clause,
90966     ** then expand the outer query to make space for it to hold all elements
90967     ** of the subquery.
90968     **
90969     ** Example:
90970     **
90971     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
90972     **
90973     ** The outer query has 3 slots in its FROM clause.  One slot of the
90974     ** outer query (the middle slot) is used by the subquery.  The next
90975     ** block of code will expand the out query to 4 slots.  The middle
90976     ** slot is expanded to two slots in order to make space for the
90977     ** two elements in the FROM clause of the subquery.
90978     */
90979     if( nSubSrc>1 ){
90980       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
90981       if( db->mallocFailed ){
90982         break;
90983       }
90984     }
90985
90986     /* Transfer the FROM clause terms from the subquery into the
90987     ** outer query.
90988     */
90989     for(i=0; i<nSubSrc; i++){
90990       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
90991       pSrc->a[i+iFrom] = pSubSrc->a[i];
90992       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
90993     }
90994     pSrc->a[iFrom].jointype = jointype;
90995   
90996     /* Now begin substituting subquery result set expressions for 
90997     ** references to the iParent in the outer query.
90998     ** 
90999     ** Example:
91000     **
91001     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
91002     **   \                     \_____________ subquery __________/          /
91003     **    \_____________________ outer query ______________________________/
91004     **
91005     ** We look at every expression in the outer query and every place we see
91006     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
91007     */
91008     pList = pParent->pEList;
91009     for(i=0; i<pList->nExpr; i++){
91010       if( pList->a[i].zName==0 ){
91011         const char *zSpan = pList->a[i].zSpan;
91012         if( ALWAYS(zSpan) ){
91013           pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
91014         }
91015       }
91016     }
91017     substExprList(db, pParent->pEList, iParent, pSub->pEList);
91018     if( isAgg ){
91019       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
91020       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
91021     }
91022     if( pSub->pOrderBy ){
91023       assert( pParent->pOrderBy==0 );
91024       pParent->pOrderBy = pSub->pOrderBy;
91025       pSub->pOrderBy = 0;
91026     }else if( pParent->pOrderBy ){
91027       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
91028     }
91029     if( pSub->pWhere ){
91030       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
91031     }else{
91032       pWhere = 0;
91033     }
91034     if( subqueryIsAgg ){
91035       assert( pParent->pHaving==0 );
91036       pParent->pHaving = pParent->pWhere;
91037       pParent->pWhere = pWhere;
91038       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
91039       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 
91040                                   sqlite3ExprDup(db, pSub->pHaving, 0));
91041       assert( pParent->pGroupBy==0 );
91042       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
91043     }else{
91044       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
91045       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
91046     }
91047   
91048     /* The flattened query is distinct if either the inner or the
91049     ** outer query is distinct. 
91050     */
91051     pParent->selFlags |= pSub->selFlags & SF_Distinct;
91052   
91053     /*
91054     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
91055     **
91056     ** One is tempted to try to add a and b to combine the limits.  But this
91057     ** does not work if either limit is negative.
91058     */
91059     if( pSub->pLimit ){
91060       pParent->pLimit = pSub->pLimit;
91061       pSub->pLimit = 0;
91062     }
91063   }
91064
91065   /* Finially, delete what is left of the subquery and return
91066   ** success.
91067   */
91068   sqlite3SelectDelete(db, pSub1);
91069
91070   return 1;
91071 }
91072 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
91073
91074 /*
91075 ** Analyze the SELECT statement passed as an argument to see if it
91076 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 
91077 ** it is, or 0 otherwise. At present, a query is considered to be
91078 ** a min()/max() query if:
91079 **
91080 **   1. There is a single object in the FROM clause.
91081 **
91082 **   2. There is a single expression in the result set, and it is
91083 **      either min(x) or max(x), where x is a column reference.
91084 */
91085 static u8 minMaxQuery(Select *p){
91086   Expr *pExpr;
91087   ExprList *pEList = p->pEList;
91088
91089   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
91090   pExpr = pEList->a[0].pExpr;
91091   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
91092   if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
91093   pEList = pExpr->x.pList;
91094   if( pEList==0 || pEList->nExpr!=1 ) return 0;
91095   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
91096   assert( !ExprHasProperty(pExpr, EP_IntValue) );
91097   if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
91098     return WHERE_ORDERBY_MIN;
91099   }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
91100     return WHERE_ORDERBY_MAX;
91101   }
91102   return WHERE_ORDERBY_NORMAL;
91103 }
91104
91105 /*
91106 ** The select statement passed as the first argument is an aggregate query.
91107 ** The second argment is the associated aggregate-info object. This 
91108 ** function tests if the SELECT is of the form:
91109 **
91110 **   SELECT count(*) FROM <tbl>
91111 **
91112 ** where table is a database table, not a sub-select or view. If the query
91113 ** does match this pattern, then a pointer to the Table object representing
91114 ** <tbl> is returned. Otherwise, 0 is returned.
91115 */
91116 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
91117   Table *pTab;
91118   Expr *pExpr;
91119
91120   assert( !p->pGroupBy );
91121
91122   if( p->pWhere || p->pEList->nExpr!=1 
91123    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
91124   ){
91125     return 0;
91126   }
91127   pTab = p->pSrc->a[0].pTab;
91128   pExpr = p->pEList->a[0].pExpr;
91129   assert( pTab && !pTab->pSelect && pExpr );
91130
91131   if( IsVirtual(pTab) ) return 0;
91132   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
91133   if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
91134   if( pExpr->flags&EP_Distinct ) return 0;
91135
91136   return pTab;
91137 }
91138
91139 /*
91140 ** If the source-list item passed as an argument was augmented with an
91141 ** INDEXED BY clause, then try to locate the specified index. If there
91142 ** was such a clause and the named index cannot be found, return 
91143 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 
91144 ** pFrom->pIndex and return SQLITE_OK.
91145 */
91146 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
91147   if( pFrom->pTab && pFrom->zIndex ){
91148     Table *pTab = pFrom->pTab;
91149     char *zIndex = pFrom->zIndex;
91150     Index *pIdx;
91151     for(pIdx=pTab->pIndex; 
91152         pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 
91153         pIdx=pIdx->pNext
91154     );
91155     if( !pIdx ){
91156       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
91157       pParse->checkSchema = 1;
91158       return SQLITE_ERROR;
91159     }
91160     pFrom->pIndex = pIdx;
91161   }
91162   return SQLITE_OK;
91163 }
91164
91165 /*
91166 ** This routine is a Walker callback for "expanding" a SELECT statement.
91167 ** "Expanding" means to do the following:
91168 **
91169 **    (1)  Make sure VDBE cursor numbers have been assigned to every
91170 **         element of the FROM clause.
91171 **
91172 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
91173 **         defines FROM clause.  When views appear in the FROM clause,
91174 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
91175 **         that implements the view.  A copy is made of the view's SELECT
91176 **         statement so that we can freely modify or delete that statement
91177 **         without worrying about messing up the presistent representation
91178 **         of the view.
91179 **
91180 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
91181 **         on joins and the ON and USING clause of joins.
91182 **
91183 **    (4)  Scan the list of columns in the result set (pEList) looking
91184 **         for instances of the "*" operator or the TABLE.* operator.
91185 **         If found, expand each "*" to be every column in every table
91186 **         and TABLE.* to be every column in TABLE.
91187 **
91188 */
91189 static int selectExpander(Walker *pWalker, Select *p){
91190   Parse *pParse = pWalker->pParse;
91191   int i, j, k;
91192   SrcList *pTabList;
91193   ExprList *pEList;
91194   struct SrcList_item *pFrom;
91195   sqlite3 *db = pParse->db;
91196
91197   if( db->mallocFailed  ){
91198     return WRC_Abort;
91199   }
91200   if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
91201     return WRC_Prune;
91202   }
91203   p->selFlags |= SF_Expanded;
91204   pTabList = p->pSrc;
91205   pEList = p->pEList;
91206
91207   /* Make sure cursor numbers have been assigned to all entries in
91208   ** the FROM clause of the SELECT statement.
91209   */
91210   sqlite3SrcListAssignCursors(pParse, pTabList);
91211
91212   /* Look up every table named in the FROM clause of the select.  If
91213   ** an entry of the FROM clause is a subquery instead of a table or view,
91214   ** then create a transient table structure to describe the subquery.
91215   */
91216   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
91217     Table *pTab;
91218     if( pFrom->pTab!=0 ){
91219       /* This statement has already been prepared.  There is no need
91220       ** to go further. */
91221       assert( i==0 );
91222       return WRC_Prune;
91223     }
91224     if( pFrom->zName==0 ){
91225 #ifndef SQLITE_OMIT_SUBQUERY
91226       Select *pSel = pFrom->pSelect;
91227       /* A sub-query in the FROM clause of a SELECT */
91228       assert( pSel!=0 );
91229       assert( pFrom->pTab==0 );
91230       sqlite3WalkSelect(pWalker, pSel);
91231       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
91232       if( pTab==0 ) return WRC_Abort;
91233       pTab->nRef = 1;
91234       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
91235       while( pSel->pPrior ){ pSel = pSel->pPrior; }
91236       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
91237       pTab->iPKey = -1;
91238       pTab->nRowEst = 1000000;
91239       pTab->tabFlags |= TF_Ephemeral;
91240 #endif
91241     }else{
91242       /* An ordinary table or view name in the FROM clause */
91243       assert( pFrom->pTab==0 );
91244       pFrom->pTab = pTab = 
91245         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
91246       if( pTab==0 ) return WRC_Abort;
91247       pTab->nRef++;
91248 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
91249       if( pTab->pSelect || IsVirtual(pTab) ){
91250         /* We reach here if the named table is a really a view */
91251         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
91252         assert( pFrom->pSelect==0 );
91253         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
91254         sqlite3WalkSelect(pWalker, pFrom->pSelect);
91255       }
91256 #endif
91257     }
91258
91259     /* Locate the index named by the INDEXED BY clause, if any. */
91260     if( sqlite3IndexedByLookup(pParse, pFrom) ){
91261       return WRC_Abort;
91262     }
91263   }
91264
91265   /* Process NATURAL keywords, and ON and USING clauses of joins.
91266   */
91267   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
91268     return WRC_Abort;
91269   }
91270
91271   /* For every "*" that occurs in the column list, insert the names of
91272   ** all columns in all tables.  And for every TABLE.* insert the names
91273   ** of all columns in TABLE.  The parser inserted a special expression
91274   ** with the TK_ALL operator for each "*" that it found in the column list.
91275   ** The following code just has to locate the TK_ALL expressions and expand
91276   ** each one to the list of all columns in all tables.
91277   **
91278   ** The first loop just checks to see if there are any "*" operators
91279   ** that need expanding.
91280   */
91281   for(k=0; k<pEList->nExpr; k++){
91282     Expr *pE = pEList->a[k].pExpr;
91283     if( pE->op==TK_ALL ) break;
91284     assert( pE->op!=TK_DOT || pE->pRight!=0 );
91285     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
91286     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
91287   }
91288   if( k<pEList->nExpr ){
91289     /*
91290     ** If we get here it means the result set contains one or more "*"
91291     ** operators that need to be expanded.  Loop through each expression
91292     ** in the result set and expand them one by one.
91293     */
91294     struct ExprList_item *a = pEList->a;
91295     ExprList *pNew = 0;
91296     int flags = pParse->db->flags;
91297     int longNames = (flags & SQLITE_FullColNames)!=0
91298                       && (flags & SQLITE_ShortColNames)==0;
91299
91300     for(k=0; k<pEList->nExpr; k++){
91301       Expr *pE = a[k].pExpr;
91302       assert( pE->op!=TK_DOT || pE->pRight!=0 );
91303       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
91304         /* This particular expression does not need to be expanded.
91305         */
91306         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
91307         if( pNew ){
91308           pNew->a[pNew->nExpr-1].zName = a[k].zName;
91309           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
91310           a[k].zName = 0;
91311           a[k].zSpan = 0;
91312         }
91313         a[k].pExpr = 0;
91314       }else{
91315         /* This expression is a "*" or a "TABLE.*" and needs to be
91316         ** expanded. */
91317         int tableSeen = 0;      /* Set to 1 when TABLE matches */
91318         char *zTName;            /* text of name of TABLE */
91319         if( pE->op==TK_DOT ){
91320           assert( pE->pLeft!=0 );
91321           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
91322           zTName = pE->pLeft->u.zToken;
91323         }else{
91324           zTName = 0;
91325         }
91326         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
91327           Table *pTab = pFrom->pTab;
91328           char *zTabName = pFrom->zAlias;
91329           if( zTabName==0 ){
91330             zTabName = pTab->zName;
91331           }
91332           if( db->mallocFailed ) break;
91333           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
91334             continue;
91335           }
91336           tableSeen = 1;
91337           for(j=0; j<pTab->nCol; j++){
91338             Expr *pExpr, *pRight;
91339             char *zName = pTab->aCol[j].zName;
91340             char *zColname;  /* The computed column name */
91341             char *zToFree;   /* Malloced string that needs to be freed */
91342             Token sColname;  /* Computed column name as a token */
91343
91344             /* If a column is marked as 'hidden' (currently only possible
91345             ** for virtual tables), do not include it in the expanded
91346             ** result-set list.
91347             */
91348             if( IsHiddenColumn(&pTab->aCol[j]) ){
91349               assert(IsVirtual(pTab));
91350               continue;
91351             }
91352
91353             if( i>0 && zTName==0 ){
91354               if( (pFrom->jointype & JT_NATURAL)!=0
91355                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
91356               ){
91357                 /* In a NATURAL join, omit the join columns from the 
91358                 ** table to the right of the join */
91359                 continue;
91360               }
91361               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
91362                 /* In a join with a USING clause, omit columns in the
91363                 ** using clause from the table on the right. */
91364                 continue;
91365               }
91366             }
91367             pRight = sqlite3Expr(db, TK_ID, zName);
91368             zColname = zName;
91369             zToFree = 0;
91370             if( longNames || pTabList->nSrc>1 ){
91371               Expr *pLeft;
91372               pLeft = sqlite3Expr(db, TK_ID, zTabName);
91373               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
91374               if( longNames ){
91375                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
91376                 zToFree = zColname;
91377               }
91378             }else{
91379               pExpr = pRight;
91380             }
91381             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
91382             sColname.z = zColname;
91383             sColname.n = sqlite3Strlen30(zColname);
91384             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
91385             sqlite3DbFree(db, zToFree);
91386           }
91387         }
91388         if( !tableSeen ){
91389           if( zTName ){
91390             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
91391           }else{
91392             sqlite3ErrorMsg(pParse, "no tables specified");
91393           }
91394         }
91395       }
91396     }
91397     sqlite3ExprListDelete(db, pEList);
91398     p->pEList = pNew;
91399   }
91400 #if SQLITE_MAX_COLUMN
91401   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
91402     sqlite3ErrorMsg(pParse, "too many columns in result set");
91403   }
91404 #endif
91405   return WRC_Continue;
91406 }
91407
91408 /*
91409 ** No-op routine for the parse-tree walker.
91410 **
91411 ** When this routine is the Walker.xExprCallback then expression trees
91412 ** are walked without any actions being taken at each node.  Presumably,
91413 ** when this routine is used for Walker.xExprCallback then 
91414 ** Walker.xSelectCallback is set to do something useful for every 
91415 ** subquery in the parser tree.
91416 */
91417 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
91418   UNUSED_PARAMETER2(NotUsed, NotUsed2);
91419   return WRC_Continue;
91420 }
91421
91422 /*
91423 ** This routine "expands" a SELECT statement and all of its subqueries.
91424 ** For additional information on what it means to "expand" a SELECT
91425 ** statement, see the comment on the selectExpand worker callback above.
91426 **
91427 ** Expanding a SELECT statement is the first step in processing a
91428 ** SELECT statement.  The SELECT statement must be expanded before
91429 ** name resolution is performed.
91430 **
91431 ** If anything goes wrong, an error message is written into pParse.
91432 ** The calling function can detect the problem by looking at pParse->nErr
91433 ** and/or pParse->db->mallocFailed.
91434 */
91435 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
91436   Walker w;
91437   w.xSelectCallback = selectExpander;
91438   w.xExprCallback = exprWalkNoop;
91439   w.pParse = pParse;
91440   sqlite3WalkSelect(&w, pSelect);
91441 }
91442
91443
91444 #ifndef SQLITE_OMIT_SUBQUERY
91445 /*
91446 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
91447 ** interface.
91448 **
91449 ** For each FROM-clause subquery, add Column.zType and Column.zColl
91450 ** information to the Table structure that represents the result set
91451 ** of that subquery.
91452 **
91453 ** The Table structure that represents the result set was constructed
91454 ** by selectExpander() but the type and collation information was omitted
91455 ** at that point because identifiers had not yet been resolved.  This
91456 ** routine is called after identifier resolution.
91457 */
91458 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
91459   Parse *pParse;
91460   int i;
91461   SrcList *pTabList;
91462   struct SrcList_item *pFrom;
91463
91464   assert( p->selFlags & SF_Resolved );
91465   if( (p->selFlags & SF_HasTypeInfo)==0 ){
91466     p->selFlags |= SF_HasTypeInfo;
91467     pParse = pWalker->pParse;
91468     pTabList = p->pSrc;
91469     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
91470       Table *pTab = pFrom->pTab;
91471       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
91472         /* A sub-query in the FROM clause of a SELECT */
91473         Select *pSel = pFrom->pSelect;
91474         assert( pSel );
91475         while( pSel->pPrior ) pSel = pSel->pPrior;
91476         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
91477       }
91478     }
91479   }
91480   return WRC_Continue;
91481 }
91482 #endif
91483
91484
91485 /*
91486 ** This routine adds datatype and collating sequence information to
91487 ** the Table structures of all FROM-clause subqueries in a
91488 ** SELECT statement.
91489 **
91490 ** Use this routine after name resolution.
91491 */
91492 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
91493 #ifndef SQLITE_OMIT_SUBQUERY
91494   Walker w;
91495   w.xSelectCallback = selectAddSubqueryTypeInfo;
91496   w.xExprCallback = exprWalkNoop;
91497   w.pParse = pParse;
91498   sqlite3WalkSelect(&w, pSelect);
91499 #endif
91500 }
91501
91502
91503 /*
91504 ** This routine sets of a SELECT statement for processing.  The
91505 ** following is accomplished:
91506 **
91507 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
91508 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
91509 **     *  ON and USING clauses are shifted into WHERE statements
91510 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
91511 **     *  Identifiers in expression are matched to tables.
91512 **
91513 ** This routine acts recursively on all subqueries within the SELECT.
91514 */
91515 SQLITE_PRIVATE void sqlite3SelectPrep(
91516   Parse *pParse,         /* The parser context */
91517   Select *p,             /* The SELECT statement being coded. */
91518   NameContext *pOuterNC  /* Name context for container */
91519 ){
91520   sqlite3 *db;
91521   if( NEVER(p==0) ) return;
91522   db = pParse->db;
91523   if( p->selFlags & SF_HasTypeInfo ) return;
91524   sqlite3SelectExpand(pParse, p);
91525   if( pParse->nErr || db->mallocFailed ) return;
91526   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
91527   if( pParse->nErr || db->mallocFailed ) return;
91528   sqlite3SelectAddTypeInfo(pParse, p);
91529 }
91530
91531 /*
91532 ** Reset the aggregate accumulator.
91533 **
91534 ** The aggregate accumulator is a set of memory cells that hold
91535 ** intermediate results while calculating an aggregate.  This
91536 ** routine simply stores NULLs in all of those memory cells.
91537 */
91538 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
91539   Vdbe *v = pParse->pVdbe;
91540   int i;
91541   struct AggInfo_func *pFunc;
91542   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
91543     return;
91544   }
91545   for(i=0; i<pAggInfo->nColumn; i++){
91546     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
91547   }
91548   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
91549     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
91550     if( pFunc->iDistinct>=0 ){
91551       Expr *pE = pFunc->pExpr;
91552       assert( !ExprHasProperty(pE, EP_xIsSelect) );
91553       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
91554         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
91555            "argument");
91556         pFunc->iDistinct = -1;
91557       }else{
91558         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
91559         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
91560                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
91561       }
91562     }
91563   }
91564 }
91565
91566 /*
91567 ** Invoke the OP_AggFinalize opcode for every aggregate function
91568 ** in the AggInfo structure.
91569 */
91570 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
91571   Vdbe *v = pParse->pVdbe;
91572   int i;
91573   struct AggInfo_func *pF;
91574   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
91575     ExprList *pList = pF->pExpr->x.pList;
91576     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
91577     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
91578                       (void*)pF->pFunc, P4_FUNCDEF);
91579   }
91580 }
91581
91582 /*
91583 ** Update the accumulator memory cells for an aggregate based on
91584 ** the current cursor position.
91585 */
91586 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
91587   Vdbe *v = pParse->pVdbe;
91588   int i;
91589   struct AggInfo_func *pF;
91590   struct AggInfo_col *pC;
91591
91592   pAggInfo->directMode = 1;
91593   sqlite3ExprCacheClear(pParse);
91594   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
91595     int nArg;
91596     int addrNext = 0;
91597     int regAgg;
91598     ExprList *pList = pF->pExpr->x.pList;
91599     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
91600     if( pList ){
91601       nArg = pList->nExpr;
91602       regAgg = sqlite3GetTempRange(pParse, nArg);
91603       sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
91604     }else{
91605       nArg = 0;
91606       regAgg = 0;
91607     }
91608     if( pF->iDistinct>=0 ){
91609       addrNext = sqlite3VdbeMakeLabel(v);
91610       assert( nArg==1 );
91611       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
91612     }
91613     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
91614       CollSeq *pColl = 0;
91615       struct ExprList_item *pItem;
91616       int j;
91617       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
91618       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
91619         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
91620       }
91621       if( !pColl ){
91622         pColl = pParse->db->pDfltColl;
91623       }
91624       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
91625     }
91626     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
91627                       (void*)pF->pFunc, P4_FUNCDEF);
91628     sqlite3VdbeChangeP5(v, (u8)nArg);
91629     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
91630     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
91631     if( addrNext ){
91632       sqlite3VdbeResolveLabel(v, addrNext);
91633       sqlite3ExprCacheClear(pParse);
91634     }
91635   }
91636
91637   /* Before populating the accumulator registers, clear the column cache.
91638   ** Otherwise, if any of the required column values are already present 
91639   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
91640   ** to pC->iMem. But by the time the value is used, the original register
91641   ** may have been used, invalidating the underlying buffer holding the
91642   ** text or blob value. See ticket [883034dcb5].
91643   **
91644   ** Another solution would be to change the OP_SCopy used to copy cached
91645   ** values to an OP_Copy.
91646   */
91647   sqlite3ExprCacheClear(pParse);
91648   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
91649     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
91650   }
91651   pAggInfo->directMode = 0;
91652   sqlite3ExprCacheClear(pParse);
91653 }
91654
91655 /*
91656 ** Generate code for the SELECT statement given in the p argument.  
91657 **
91658 ** The results are distributed in various ways depending on the
91659 ** contents of the SelectDest structure pointed to by argument pDest
91660 ** as follows:
91661 **
91662 **     pDest->eDest    Result
91663 **     ------------    -------------------------------------------
91664 **     SRT_Output      Generate a row of output (using the OP_ResultRow
91665 **                     opcode) for each row in the result set.
91666 **
91667 **     SRT_Mem         Only valid if the result is a single column.
91668 **                     Store the first column of the first result row
91669 **                     in register pDest->iParm then abandon the rest
91670 **                     of the query.  This destination implies "LIMIT 1".
91671 **
91672 **     SRT_Set         The result must be a single column.  Store each
91673 **                     row of result as the key in table pDest->iParm. 
91674 **                     Apply the affinity pDest->affinity before storing
91675 **                     results.  Used to implement "IN (SELECT ...)".
91676 **
91677 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
91678 **
91679 **     SRT_Except      Remove results from the temporary table pDest->iParm.
91680 **
91681 **     SRT_Table       Store results in temporary table pDest->iParm.
91682 **                     This is like SRT_EphemTab except that the table
91683 **                     is assumed to already be open.
91684 **
91685 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
91686 **                     the result there. The cursor is left open after
91687 **                     returning.  This is like SRT_Table except that
91688 **                     this destination uses OP_OpenEphemeral to create
91689 **                     the table first.
91690 **
91691 **     SRT_Coroutine   Generate a co-routine that returns a new row of
91692 **                     results each time it is invoked.  The entry point
91693 **                     of the co-routine is stored in register pDest->iParm.
91694 **
91695 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
91696 **                     set is not empty.
91697 **
91698 **     SRT_Discard     Throw the results away.  This is used by SELECT
91699 **                     statements within triggers whose only purpose is
91700 **                     the side-effects of functions.
91701 **
91702 ** This routine returns the number of errors.  If any errors are
91703 ** encountered, then an appropriate error message is left in
91704 ** pParse->zErrMsg.
91705 **
91706 ** This routine does NOT free the Select structure passed in.  The
91707 ** calling function needs to do that.
91708 */
91709 SQLITE_PRIVATE int sqlite3Select(
91710   Parse *pParse,         /* The parser context */
91711   Select *p,             /* The SELECT statement being coded. */
91712   SelectDest *pDest      /* What to do with the query results */
91713 ){
91714   int i, j;              /* Loop counters */
91715   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
91716   Vdbe *v;               /* The virtual machine under construction */
91717   int isAgg;             /* True for select lists like "count(*)" */
91718   ExprList *pEList;      /* List of columns to extract. */
91719   SrcList *pTabList;     /* List of tables to select from */
91720   Expr *pWhere;          /* The WHERE clause.  May be NULL */
91721   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
91722   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
91723   Expr *pHaving;         /* The HAVING clause.  May be NULL */
91724   int isDistinct;        /* True if the DISTINCT keyword is present */
91725   int distinct;          /* Table to use for the distinct set */
91726   int rc = 1;            /* Value to return from this function */
91727   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
91728   AggInfo sAggInfo;      /* Information used by aggregate queries */
91729   int iEnd;              /* Address of the end of the query */
91730   sqlite3 *db;           /* The database connection */
91731
91732 #ifndef SQLITE_OMIT_EXPLAIN
91733   int iRestoreSelectId = pParse->iSelectId;
91734   pParse->iSelectId = pParse->iNextSelectId++;
91735 #endif
91736
91737   db = pParse->db;
91738   if( p==0 || db->mallocFailed || pParse->nErr ){
91739     return 1;
91740   }
91741   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
91742   memset(&sAggInfo, 0, sizeof(sAggInfo));
91743
91744   if( IgnorableOrderby(pDest) ){
91745     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
91746            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
91747     /* If ORDER BY makes no difference in the output then neither does
91748     ** DISTINCT so it can be removed too. */
91749     sqlite3ExprListDelete(db, p->pOrderBy);
91750     p->pOrderBy = 0;
91751     p->selFlags &= ~SF_Distinct;
91752   }
91753   sqlite3SelectPrep(pParse, p, 0);
91754   pOrderBy = p->pOrderBy;
91755   pTabList = p->pSrc;
91756   pEList = p->pEList;
91757   if( pParse->nErr || db->mallocFailed ){
91758     goto select_end;
91759   }
91760   isAgg = (p->selFlags & SF_Aggregate)!=0;
91761   assert( pEList!=0 );
91762
91763   /* Begin generating code.
91764   */
91765   v = sqlite3GetVdbe(pParse);
91766   if( v==0 ) goto select_end;
91767
91768   /* If writing to memory or generating a set
91769   ** only a single column may be output.
91770   */
91771 #ifndef SQLITE_OMIT_SUBQUERY
91772   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
91773     goto select_end;
91774   }
91775 #endif
91776
91777   /* Generate code for all sub-queries in the FROM clause
91778   */
91779 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
91780   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
91781     struct SrcList_item *pItem = &pTabList->a[i];
91782     SelectDest dest;
91783     Select *pSub = pItem->pSelect;
91784     int isAggSub;
91785
91786     if( pSub==0 || pItem->isPopulated ) continue;
91787
91788     /* Increment Parse.nHeight by the height of the largest expression
91789     ** tree refered to by this, the parent select. The child select
91790     ** may contain expression trees of at most
91791     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
91792     ** more conservative than necessary, but much easier than enforcing
91793     ** an exact limit.
91794     */
91795     pParse->nHeight += sqlite3SelectExprHeight(p);
91796
91797     /* Check to see if the subquery can be absorbed into the parent. */
91798     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
91799     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
91800       if( isAggSub ){
91801         isAgg = 1;
91802         p->selFlags |= SF_Aggregate;
91803       }
91804       i = -1;
91805     }else{
91806       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
91807       assert( pItem->isPopulated==0 );
91808       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
91809       sqlite3Select(pParse, pSub, &dest);
91810       pItem->isPopulated = 1;
91811       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
91812     }
91813     if( /*pParse->nErr ||*/ db->mallocFailed ){
91814       goto select_end;
91815     }
91816     pParse->nHeight -= sqlite3SelectExprHeight(p);
91817     pTabList = p->pSrc;
91818     if( !IgnorableOrderby(pDest) ){
91819       pOrderBy = p->pOrderBy;
91820     }
91821   }
91822   pEList = p->pEList;
91823 #endif
91824   pWhere = p->pWhere;
91825   pGroupBy = p->pGroupBy;
91826   pHaving = p->pHaving;
91827   isDistinct = (p->selFlags & SF_Distinct)!=0;
91828
91829 #ifndef SQLITE_OMIT_COMPOUND_SELECT
91830   /* If there is are a sequence of queries, do the earlier ones first.
91831   */
91832   if( p->pPrior ){
91833     if( p->pRightmost==0 ){
91834       Select *pLoop, *pRight = 0;
91835       int cnt = 0;
91836       int mxSelect;
91837       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
91838         pLoop->pRightmost = p;
91839         pLoop->pNext = pRight;
91840         pRight = pLoop;
91841       }
91842       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
91843       if( mxSelect && cnt>mxSelect ){
91844         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
91845         goto select_end;
91846       }
91847     }
91848     rc = multiSelect(pParse, p, pDest);
91849     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
91850     return rc;
91851   }
91852 #endif
91853
91854   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
91855   ** GROUP BY might use an index, DISTINCT never does.
91856   */
91857   assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
91858   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
91859     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
91860     pGroupBy = p->pGroupBy;
91861     p->selFlags &= ~SF_Distinct;
91862   }
91863
91864   /* If there is both a GROUP BY and an ORDER BY clause and they are
91865   ** identical, then disable the ORDER BY clause since the GROUP BY
91866   ** will cause elements to come out in the correct order.  This is
91867   ** an optimization - the correct answer should result regardless.
91868   ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
91869   ** to disable this optimization for testing purposes.
91870   */
91871   if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
91872          && (db->flags & SQLITE_GroupByOrder)==0 ){
91873     pOrderBy = 0;
91874   }
91875
91876   /* If there is an ORDER BY clause, then this sorting
91877   ** index might end up being unused if the data can be 
91878   ** extracted in pre-sorted order.  If that is the case, then the
91879   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
91880   ** we figure out that the sorting index is not needed.  The addrSortIndex
91881   ** variable is used to facilitate that change.
91882   */
91883   if( pOrderBy ){
91884     KeyInfo *pKeyInfo;
91885     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
91886     pOrderBy->iECursor = pParse->nTab++;
91887     p->addrOpenEphm[2] = addrSortIndex =
91888       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
91889                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
91890                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
91891   }else{
91892     addrSortIndex = -1;
91893   }
91894
91895   /* If the output is destined for a temporary table, open that table.
91896   */
91897   if( pDest->eDest==SRT_EphemTab ){
91898     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
91899   }
91900
91901   /* Set the limiter.
91902   */
91903   iEnd = sqlite3VdbeMakeLabel(v);
91904   p->nSelectRow = (double)LARGEST_INT64;
91905   computeLimitRegisters(pParse, p, iEnd);
91906
91907   /* Open a virtual index to use for the distinct set.
91908   */
91909   if( p->selFlags & SF_Distinct ){
91910     KeyInfo *pKeyInfo;
91911     assert( isAgg || pGroupBy );
91912     distinct = pParse->nTab++;
91913     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
91914     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
91915                         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
91916     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
91917   }else{
91918     distinct = -1;
91919   }
91920
91921   /* Aggregate and non-aggregate queries are handled differently */
91922   if( !isAgg && pGroupBy==0 ){
91923     /* This case is for non-aggregate queries
91924     ** Begin the database scan
91925     */
91926     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
91927     if( pWInfo==0 ) goto select_end;
91928     if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
91929
91930     /* If sorting index that was created by a prior OP_OpenEphemeral 
91931     ** instruction ended up not being needed, then change the OP_OpenEphemeral
91932     ** into an OP_Noop.
91933     */
91934     if( addrSortIndex>=0 && pOrderBy==0 ){
91935       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
91936       p->addrOpenEphm[2] = -1;
91937     }
91938
91939     /* Use the standard inner loop
91940     */
91941     assert(!isDistinct);
91942     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
91943                     pWInfo->iContinue, pWInfo->iBreak);
91944
91945     /* End the database scan loop.
91946     */
91947     sqlite3WhereEnd(pWInfo);
91948   }else{
91949     /* This is the processing for aggregate queries */
91950     NameContext sNC;    /* Name context for processing aggregate information */
91951     int iAMem;          /* First Mem address for storing current GROUP BY */
91952     int iBMem;          /* First Mem address for previous GROUP BY */
91953     int iUseFlag;       /* Mem address holding flag indicating that at least
91954                         ** one row of the input to the aggregator has been
91955                         ** processed */
91956     int iAbortFlag;     /* Mem address which causes query abort if positive */
91957     int groupBySort;    /* Rows come from source in GROUP BY order */
91958     int addrEnd;        /* End of processing for this SELECT */
91959
91960     /* Remove any and all aliases between the result set and the
91961     ** GROUP BY clause.
91962     */
91963     if( pGroupBy ){
91964       int k;                        /* Loop counter */
91965       struct ExprList_item *pItem;  /* For looping over expression in a list */
91966
91967       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
91968         pItem->iAlias = 0;
91969       }
91970       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
91971         pItem->iAlias = 0;
91972       }
91973       if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
91974     }else{
91975       p->nSelectRow = (double)1;
91976     }
91977
91978  
91979     /* Create a label to jump to when we want to abort the query */
91980     addrEnd = sqlite3VdbeMakeLabel(v);
91981
91982     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
91983     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
91984     ** SELECT statement.
91985     */
91986     memset(&sNC, 0, sizeof(sNC));
91987     sNC.pParse = pParse;
91988     sNC.pSrcList = pTabList;
91989     sNC.pAggInfo = &sAggInfo;
91990     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
91991     sAggInfo.pGroupBy = pGroupBy;
91992     sqlite3ExprAnalyzeAggList(&sNC, pEList);
91993     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
91994     if( pHaving ){
91995       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
91996     }
91997     sAggInfo.nAccumulator = sAggInfo.nColumn;
91998     for(i=0; i<sAggInfo.nFunc; i++){
91999       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
92000       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
92001     }
92002     if( db->mallocFailed ) goto select_end;
92003
92004     /* Processing for aggregates with GROUP BY is very different and
92005     ** much more complex than aggregates without a GROUP BY.
92006     */
92007     if( pGroupBy ){
92008       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
92009       int j1;             /* A-vs-B comparision jump */
92010       int addrOutputRow;  /* Start of subroutine that outputs a result row */
92011       int regOutputRow;   /* Return address register for output subroutine */
92012       int addrSetAbort;   /* Set the abort flag and return */
92013       int addrTopOfLoop;  /* Top of the input loop */
92014       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
92015       int addrReset;      /* Subroutine for resetting the accumulator */
92016       int regReset;       /* Return address register for reset subroutine */
92017
92018       /* If there is a GROUP BY clause we might need a sorting index to
92019       ** implement it.  Allocate that sorting index now.  If it turns out
92020       ** that we do not need it after all, the OpenEphemeral instruction
92021       ** will be converted into a Noop.  
92022       */
92023       sAggInfo.sortingIdx = pParse->nTab++;
92024       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
92025       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 
92026           sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
92027           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
92028
92029       /* Initialize memory locations used by GROUP BY aggregate processing
92030       */
92031       iUseFlag = ++pParse->nMem;
92032       iAbortFlag = ++pParse->nMem;
92033       regOutputRow = ++pParse->nMem;
92034       addrOutputRow = sqlite3VdbeMakeLabel(v);
92035       regReset = ++pParse->nMem;
92036       addrReset = sqlite3VdbeMakeLabel(v);
92037       iAMem = pParse->nMem + 1;
92038       pParse->nMem += pGroupBy->nExpr;
92039       iBMem = pParse->nMem + 1;
92040       pParse->nMem += pGroupBy->nExpr;
92041       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
92042       VdbeComment((v, "clear abort flag"));
92043       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
92044       VdbeComment((v, "indicate accumulator empty"));
92045
92046       /* Begin a loop that will extract all source rows in GROUP BY order.
92047       ** This might involve two separate loops with an OP_Sort in between, or
92048       ** it might be a single loop that uses an index to extract information
92049       ** in the right order to begin with.
92050       */
92051       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
92052       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
92053       if( pWInfo==0 ) goto select_end;
92054       if( pGroupBy==0 ){
92055         /* The optimizer is able to deliver rows in group by order so
92056         ** we do not have to sort.  The OP_OpenEphemeral table will be
92057         ** cancelled later because we still need to use the pKeyInfo
92058         */
92059         pGroupBy = p->pGroupBy;
92060         groupBySort = 0;
92061       }else{
92062         /* Rows are coming out in undetermined order.  We have to push
92063         ** each row into a sorting index, terminate the first loop,
92064         ** then loop over the sorting index in order to get the output
92065         ** in sorted order
92066         */
92067         int regBase;
92068         int regRecord;
92069         int nCol;
92070         int nGroupBy;
92071
92072         explainTempTable(pParse, 
92073             isDistinct && !(p->selFlags&SF_Distinct)?"DISTINCT":"GROUP BY");
92074
92075         groupBySort = 1;
92076         nGroupBy = pGroupBy->nExpr;
92077         nCol = nGroupBy + 1;
92078         j = nGroupBy+1;
92079         for(i=0; i<sAggInfo.nColumn; i++){
92080           if( sAggInfo.aCol[i].iSorterColumn>=j ){
92081             nCol++;
92082             j++;
92083           }
92084         }
92085         regBase = sqlite3GetTempRange(pParse, nCol);
92086         sqlite3ExprCacheClear(pParse);
92087         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
92088         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
92089         j = nGroupBy+1;
92090         for(i=0; i<sAggInfo.nColumn; i++){
92091           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
92092           if( pCol->iSorterColumn>=j ){
92093             int r1 = j + regBase;
92094             int r2;
92095
92096             r2 = sqlite3ExprCodeGetColumn(pParse, 
92097                                pCol->pTab, pCol->iColumn, pCol->iTable, r1);
92098             if( r1!=r2 ){
92099               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
92100             }
92101             j++;
92102           }
92103         }
92104         regRecord = sqlite3GetTempReg(pParse);
92105         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
92106         sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
92107         sqlite3ReleaseTempReg(pParse, regRecord);
92108         sqlite3ReleaseTempRange(pParse, regBase, nCol);
92109         sqlite3WhereEnd(pWInfo);
92110         sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
92111         VdbeComment((v, "GROUP BY sort"));
92112         sAggInfo.useSortingIdx = 1;
92113         sqlite3ExprCacheClear(pParse);
92114       }
92115
92116       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
92117       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
92118       ** Then compare the current GROUP BY terms against the GROUP BY terms
92119       ** from the previous row currently stored in a0, a1, a2...
92120       */
92121       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
92122       sqlite3ExprCacheClear(pParse);
92123       for(j=0; j<pGroupBy->nExpr; j++){
92124         if( groupBySort ){
92125           sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
92126         }else{
92127           sAggInfo.directMode = 1;
92128           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
92129         }
92130       }
92131       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
92132                           (char*)pKeyInfo, P4_KEYINFO);
92133       j1 = sqlite3VdbeCurrentAddr(v);
92134       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
92135
92136       /* Generate code that runs whenever the GROUP BY changes.
92137       ** Changes in the GROUP BY are detected by the previous code
92138       ** block.  If there were no changes, this block is skipped.
92139       **
92140       ** This code copies current group by terms in b0,b1,b2,...
92141       ** over to a0,a1,a2.  It then calls the output subroutine
92142       ** and resets the aggregate accumulator registers in preparation
92143       ** for the next GROUP BY batch.
92144       */
92145       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
92146       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
92147       VdbeComment((v, "output one row"));
92148       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
92149       VdbeComment((v, "check abort flag"));
92150       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
92151       VdbeComment((v, "reset accumulator"));
92152
92153       /* Update the aggregate accumulators based on the content of
92154       ** the current row
92155       */
92156       sqlite3VdbeJumpHere(v, j1);
92157       updateAccumulator(pParse, &sAggInfo);
92158       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
92159       VdbeComment((v, "indicate data in accumulator"));
92160
92161       /* End of the loop
92162       */
92163       if( groupBySort ){
92164         sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
92165       }else{
92166         sqlite3WhereEnd(pWInfo);
92167         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
92168       }
92169
92170       /* Output the final row of result
92171       */
92172       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
92173       VdbeComment((v, "output final row"));
92174
92175       /* Jump over the subroutines
92176       */
92177       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
92178
92179       /* Generate a subroutine that outputs a single row of the result
92180       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
92181       ** is less than or equal to zero, the subroutine is a no-op.  If
92182       ** the processing calls for the query to abort, this subroutine
92183       ** increments the iAbortFlag memory location before returning in
92184       ** order to signal the caller to abort.
92185       */
92186       addrSetAbort = sqlite3VdbeCurrentAddr(v);
92187       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
92188       VdbeComment((v, "set abort flag"));
92189       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
92190       sqlite3VdbeResolveLabel(v, addrOutputRow);
92191       addrOutputRow = sqlite3VdbeCurrentAddr(v);
92192       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
92193       VdbeComment((v, "Groupby result generator entry point"));
92194       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
92195       finalizeAggFunctions(pParse, &sAggInfo);
92196       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
92197       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
92198                       distinct, pDest,
92199                       addrOutputRow+1, addrSetAbort);
92200       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
92201       VdbeComment((v, "end groupby result generator"));
92202
92203       /* Generate a subroutine that will reset the group-by accumulator
92204       */
92205       sqlite3VdbeResolveLabel(v, addrReset);
92206       resetAccumulator(pParse, &sAggInfo);
92207       sqlite3VdbeAddOp1(v, OP_Return, regReset);
92208      
92209     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
92210     else {
92211       ExprList *pDel = 0;
92212 #ifndef SQLITE_OMIT_BTREECOUNT
92213       Table *pTab;
92214       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
92215         /* If isSimpleCount() returns a pointer to a Table structure, then
92216         ** the SQL statement is of the form:
92217         **
92218         **   SELECT count(*) FROM <tbl>
92219         **
92220         ** where the Table structure returned represents table <tbl>.
92221         **
92222         ** This statement is so common that it is optimized specially. The
92223         ** OP_Count instruction is executed either on the intkey table that
92224         ** contains the data for table <tbl> or on one of its indexes. It
92225         ** is better to execute the op on an index, as indexes are almost
92226         ** always spread across less pages than their corresponding tables.
92227         */
92228         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
92229         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
92230         Index *pIdx;                         /* Iterator variable */
92231         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
92232         Index *pBest = 0;                    /* Best index found so far */
92233         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
92234
92235         sqlite3CodeVerifySchema(pParse, iDb);
92236         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
92237
92238         /* Search for the index that has the least amount of columns. If
92239         ** there is such an index, and it has less columns than the table
92240         ** does, then we can assume that it consumes less space on disk and
92241         ** will therefore be cheaper to scan to determine the query result.
92242         ** In this case set iRoot to the root page number of the index b-tree
92243         ** and pKeyInfo to the KeyInfo structure required to navigate the
92244         ** index.
92245         **
92246         ** In practice the KeyInfo structure will not be used. It is only 
92247         ** passed to keep OP_OpenRead happy.
92248         */
92249         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
92250           if( !pBest || pIdx->nColumn<pBest->nColumn ){
92251             pBest = pIdx;
92252           }
92253         }
92254         if( pBest && pBest->nColumn<pTab->nCol ){
92255           iRoot = pBest->tnum;
92256           pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
92257         }
92258
92259         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
92260         sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
92261         if( pKeyInfo ){
92262           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
92263         }
92264         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
92265         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
92266       }else
92267 #endif /* SQLITE_OMIT_BTREECOUNT */
92268       {
92269         /* Check if the query is of one of the following forms:
92270         **
92271         **   SELECT min(x) FROM ...
92272         **   SELECT max(x) FROM ...
92273         **
92274         ** If it is, then ask the code in where.c to attempt to sort results
92275         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
92276         ** If where.c is able to produce results sorted in this order, then
92277         ** add vdbe code to break out of the processing loop after the 
92278         ** first iteration (since the first iteration of the loop is 
92279         ** guaranteed to operate on the row with the minimum or maximum 
92280         ** value of x, the only row required).
92281         **
92282         ** A special flag must be passed to sqlite3WhereBegin() to slightly
92283         ** modify behaviour as follows:
92284         **
92285         **   + If the query is a "SELECT min(x)", then the loop coded by
92286         **     where.c should not iterate over any values with a NULL value
92287         **     for x.
92288         **
92289         **   + The optimizer code in where.c (the thing that decides which
92290         **     index or indices to use) should place a different priority on 
92291         **     satisfying the 'ORDER BY' clause than it does in other cases.
92292         **     Refer to code and comments in where.c for details.
92293         */
92294         ExprList *pMinMax = 0;
92295         u8 flag = minMaxQuery(p);
92296         if( flag ){
92297           assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
92298           pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
92299           pDel = pMinMax;
92300           if( pMinMax && !db->mallocFailed ){
92301             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
92302             pMinMax->a[0].pExpr->op = TK_COLUMN;
92303           }
92304         }
92305   
92306         /* This case runs if the aggregate has no GROUP BY clause.  The
92307         ** processing is much simpler since there is only a single row
92308         ** of output.
92309         */
92310         resetAccumulator(pParse, &sAggInfo);
92311         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
92312         if( pWInfo==0 ){
92313           sqlite3ExprListDelete(db, pDel);
92314           goto select_end;
92315         }
92316         updateAccumulator(pParse, &sAggInfo);
92317         if( !pMinMax && flag ){
92318           sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
92319           VdbeComment((v, "%s() by index",
92320                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
92321         }
92322         sqlite3WhereEnd(pWInfo);
92323         finalizeAggFunctions(pParse, &sAggInfo);
92324       }
92325
92326       pOrderBy = 0;
92327       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
92328       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 
92329                       pDest, addrEnd, addrEnd);
92330       sqlite3ExprListDelete(db, pDel);
92331     }
92332     sqlite3VdbeResolveLabel(v, addrEnd);
92333     
92334   } /* endif aggregate query */
92335
92336   if( distinct>=0 ){
92337     explainTempTable(pParse, "DISTINCT");
92338   }
92339
92340   /* If there is an ORDER BY clause, then we need to sort the results
92341   ** and send them to the callback one by one.
92342   */
92343   if( pOrderBy ){
92344     explainTempTable(pParse, "ORDER BY");
92345     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
92346   }
92347
92348   /* Jump here to skip this query
92349   */
92350   sqlite3VdbeResolveLabel(v, iEnd);
92351
92352   /* The SELECT was successfully coded.   Set the return code to 0
92353   ** to indicate no errors.
92354   */
92355   rc = 0;
92356
92357   /* Control jumps to here if an error is encountered above, or upon
92358   ** successful coding of the SELECT.
92359   */
92360 select_end:
92361   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
92362
92363   /* Identify column names if results of the SELECT are to be output.
92364   */
92365   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
92366     generateColumnNames(pParse, pTabList, pEList);
92367   }
92368
92369   sqlite3DbFree(db, sAggInfo.aCol);
92370   sqlite3DbFree(db, sAggInfo.aFunc);
92371   return rc;
92372 }
92373
92374 #if defined(SQLITE_DEBUG)
92375 /*
92376 *******************************************************************************
92377 ** The following code is used for testing and debugging only.  The code
92378 ** that follows does not appear in normal builds.
92379 **
92380 ** These routines are used to print out the content of all or part of a 
92381 ** parse structures such as Select or Expr.  Such printouts are useful
92382 ** for helping to understand what is happening inside the code generator
92383 ** during the execution of complex SELECT statements.
92384 **
92385 ** These routine are not called anywhere from within the normal
92386 ** code base.  Then are intended to be called from within the debugger
92387 ** or from temporary "printf" statements inserted for debugging.
92388 */
92389 SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
92390   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
92391     sqlite3DebugPrintf("(%s", p->u.zToken);
92392   }else{
92393     sqlite3DebugPrintf("(%d", p->op);
92394   }
92395   if( p->pLeft ){
92396     sqlite3DebugPrintf(" ");
92397     sqlite3PrintExpr(p->pLeft);
92398   }
92399   if( p->pRight ){
92400     sqlite3DebugPrintf(" ");
92401     sqlite3PrintExpr(p->pRight);
92402   }
92403   sqlite3DebugPrintf(")");
92404 }
92405 SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
92406   int i;
92407   for(i=0; i<pList->nExpr; i++){
92408     sqlite3PrintExpr(pList->a[i].pExpr);
92409     if( i<pList->nExpr-1 ){
92410       sqlite3DebugPrintf(", ");
92411     }
92412   }
92413 }
92414 SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
92415   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
92416   sqlite3PrintExprList(p->pEList);
92417   sqlite3DebugPrintf("\n");
92418   if( p->pSrc ){
92419     char *zPrefix;
92420     int i;
92421     zPrefix = "FROM";
92422     for(i=0; i<p->pSrc->nSrc; i++){
92423       struct SrcList_item *pItem = &p->pSrc->a[i];
92424       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
92425       zPrefix = "";
92426       if( pItem->pSelect ){
92427         sqlite3DebugPrintf("(\n");
92428         sqlite3PrintSelect(pItem->pSelect, indent+10);
92429         sqlite3DebugPrintf("%*s)", indent+8, "");
92430       }else if( pItem->zName ){
92431         sqlite3DebugPrintf("%s", pItem->zName);
92432       }
92433       if( pItem->pTab ){
92434         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
92435       }
92436       if( pItem->zAlias ){
92437         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
92438       }
92439       if( i<p->pSrc->nSrc-1 ){
92440         sqlite3DebugPrintf(",");
92441       }
92442       sqlite3DebugPrintf("\n");
92443     }
92444   }
92445   if( p->pWhere ){
92446     sqlite3DebugPrintf("%*s WHERE ", indent, "");
92447     sqlite3PrintExpr(p->pWhere);
92448     sqlite3DebugPrintf("\n");
92449   }
92450   if( p->pGroupBy ){
92451     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
92452     sqlite3PrintExprList(p->pGroupBy);
92453     sqlite3DebugPrintf("\n");
92454   }
92455   if( p->pHaving ){
92456     sqlite3DebugPrintf("%*s HAVING ", indent, "");
92457     sqlite3PrintExpr(p->pHaving);
92458     sqlite3DebugPrintf("\n");
92459   }
92460   if( p->pOrderBy ){
92461     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
92462     sqlite3PrintExprList(p->pOrderBy);
92463     sqlite3DebugPrintf("\n");
92464   }
92465 }
92466 /* End of the structure debug printing code
92467 *****************************************************************************/
92468 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
92469
92470 /************** End of select.c **********************************************/
92471 /************** Begin file table.c *******************************************/
92472 /*
92473 ** 2001 September 15
92474 **
92475 ** The author disclaims copyright to this source code.  In place of
92476 ** a legal notice, here is a blessing:
92477 **
92478 **    May you do good and not evil.
92479 **    May you find forgiveness for yourself and forgive others.
92480 **    May you share freely, never taking more than you give.
92481 **
92482 *************************************************************************
92483 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
92484 ** interface routines.  These are just wrappers around the main
92485 ** interface routine of sqlite3_exec().
92486 **
92487 ** These routines are in a separate files so that they will not be linked
92488 ** if they are not used.
92489 */
92490
92491 #ifndef SQLITE_OMIT_GET_TABLE
92492
92493 /*
92494 ** This structure is used to pass data from sqlite3_get_table() through
92495 ** to the callback function is uses to build the result.
92496 */
92497 typedef struct TabResult {
92498   char **azResult;   /* Accumulated output */
92499   char *zErrMsg;     /* Error message text, if an error occurs */
92500   int nAlloc;        /* Slots allocated for azResult[] */
92501   int nRow;          /* Number of rows in the result */
92502   int nColumn;       /* Number of columns in the result */
92503   int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
92504   int rc;            /* Return code from sqlite3_exec() */
92505 } TabResult;
92506
92507 /*
92508 ** This routine is called once for each row in the result table.  Its job
92509 ** is to fill in the TabResult structure appropriately, allocating new
92510 ** memory as necessary.
92511 */
92512 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
92513   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
92514   int need;                         /* Slots needed in p->azResult[] */
92515   int i;                            /* Loop counter */
92516   char *z;                          /* A single column of result */
92517
92518   /* Make sure there is enough space in p->azResult to hold everything
92519   ** we need to remember from this invocation of the callback.
92520   */
92521   if( p->nRow==0 && argv!=0 ){
92522     need = nCol*2;
92523   }else{
92524     need = nCol;
92525   }
92526   if( p->nData + need > p->nAlloc ){
92527     char **azNew;
92528     p->nAlloc = p->nAlloc*2 + need;
92529     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
92530     if( azNew==0 ) goto malloc_failed;
92531     p->azResult = azNew;
92532   }
92533
92534   /* If this is the first row, then generate an extra row containing
92535   ** the names of all columns.
92536   */
92537   if( p->nRow==0 ){
92538     p->nColumn = nCol;
92539     for(i=0; i<nCol; i++){
92540       z = sqlite3_mprintf("%s", colv[i]);
92541       if( z==0 ) goto malloc_failed;
92542       p->azResult[p->nData++] = z;
92543     }
92544   }else if( p->nColumn!=nCol ){
92545     sqlite3_free(p->zErrMsg);
92546     p->zErrMsg = sqlite3_mprintf(
92547        "sqlite3_get_table() called with two or more incompatible queries"
92548     );
92549     p->rc = SQLITE_ERROR;
92550     return 1;
92551   }
92552
92553   /* Copy over the row data
92554   */
92555   if( argv!=0 ){
92556     for(i=0; i<nCol; i++){
92557       if( argv[i]==0 ){
92558         z = 0;
92559       }else{
92560         int n = sqlite3Strlen30(argv[i])+1;
92561         z = sqlite3_malloc( n );
92562         if( z==0 ) goto malloc_failed;
92563         memcpy(z, argv[i], n);
92564       }
92565       p->azResult[p->nData++] = z;
92566     }
92567     p->nRow++;
92568   }
92569   return 0;
92570
92571 malloc_failed:
92572   p->rc = SQLITE_NOMEM;
92573   return 1;
92574 }
92575
92576 /*
92577 ** Query the database.  But instead of invoking a callback for each row,
92578 ** malloc() for space to hold the result and return the entire results
92579 ** at the conclusion of the call.
92580 **
92581 ** The result that is written to ***pazResult is held in memory obtained
92582 ** from malloc().  But the caller cannot free this memory directly.  
92583 ** Instead, the entire table should be passed to sqlite3_free_table() when
92584 ** the calling procedure is finished using it.
92585 */
92586 SQLITE_API int sqlite3_get_table(
92587   sqlite3 *db,                /* The database on which the SQL executes */
92588   const char *zSql,           /* The SQL to be executed */
92589   char ***pazResult,          /* Write the result table here */
92590   int *pnRow,                 /* Write the number of rows in the result here */
92591   int *pnColumn,              /* Write the number of columns of result here */
92592   char **pzErrMsg             /* Write error messages here */
92593 ){
92594   int rc;
92595   TabResult res;
92596
92597   *pazResult = 0;
92598   if( pnColumn ) *pnColumn = 0;
92599   if( pnRow ) *pnRow = 0;
92600   if( pzErrMsg ) *pzErrMsg = 0;
92601   res.zErrMsg = 0;
92602   res.nRow = 0;
92603   res.nColumn = 0;
92604   res.nData = 1;
92605   res.nAlloc = 20;
92606   res.rc = SQLITE_OK;
92607   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
92608   if( res.azResult==0 ){
92609      db->errCode = SQLITE_NOMEM;
92610      return SQLITE_NOMEM;
92611   }
92612   res.azResult[0] = 0;
92613   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
92614   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
92615   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
92616   if( (rc&0xff)==SQLITE_ABORT ){
92617     sqlite3_free_table(&res.azResult[1]);
92618     if( res.zErrMsg ){
92619       if( pzErrMsg ){
92620         sqlite3_free(*pzErrMsg);
92621         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
92622       }
92623       sqlite3_free(res.zErrMsg);
92624     }
92625     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
92626     return res.rc;
92627   }
92628   sqlite3_free(res.zErrMsg);
92629   if( rc!=SQLITE_OK ){
92630     sqlite3_free_table(&res.azResult[1]);
92631     return rc;
92632   }
92633   if( res.nAlloc>res.nData ){
92634     char **azNew;
92635     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
92636     if( azNew==0 ){
92637       sqlite3_free_table(&res.azResult[1]);
92638       db->errCode = SQLITE_NOMEM;
92639       return SQLITE_NOMEM;
92640     }
92641     res.azResult = azNew;
92642   }
92643   *pazResult = &res.azResult[1];
92644   if( pnColumn ) *pnColumn = res.nColumn;
92645   if( pnRow ) *pnRow = res.nRow;
92646   return rc;
92647 }
92648
92649 /*
92650 ** This routine frees the space the sqlite3_get_table() malloced.
92651 */
92652 SQLITE_API void sqlite3_free_table(
92653   char **azResult            /* Result returned from from sqlite3_get_table() */
92654 ){
92655   if( azResult ){
92656     int i, n;
92657     azResult--;
92658     assert( azResult!=0 );
92659     n = SQLITE_PTR_TO_INT(azResult[0]);
92660     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
92661     sqlite3_free(azResult);
92662   }
92663 }
92664
92665 #endif /* SQLITE_OMIT_GET_TABLE */
92666
92667 /************** End of table.c ***********************************************/
92668 /************** Begin file trigger.c *****************************************/
92669 /*
92670 **
92671 ** The author disclaims copyright to this source code.  In place of
92672 ** a legal notice, here is a blessing:
92673 **
92674 **    May you do good and not evil.
92675 **    May you find forgiveness for yourself and forgive others.
92676 **    May you share freely, never taking more than you give.
92677 **
92678 *************************************************************************
92679 ** This file contains the implementation for TRIGGERs
92680 */
92681
92682 #ifndef SQLITE_OMIT_TRIGGER
92683 /*
92684 ** Delete a linked list of TriggerStep structures.
92685 */
92686 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
92687   while( pTriggerStep ){
92688     TriggerStep * pTmp = pTriggerStep;
92689     pTriggerStep = pTriggerStep->pNext;
92690
92691     sqlite3ExprDelete(db, pTmp->pWhere);
92692     sqlite3ExprListDelete(db, pTmp->pExprList);
92693     sqlite3SelectDelete(db, pTmp->pSelect);
92694     sqlite3IdListDelete(db, pTmp->pIdList);
92695
92696     sqlite3DbFree(db, pTmp);
92697   }
92698 }
92699
92700 /*
92701 ** Given table pTab, return a list of all the triggers attached to 
92702 ** the table. The list is connected by Trigger.pNext pointers.
92703 **
92704 ** All of the triggers on pTab that are in the same database as pTab
92705 ** are already attached to pTab->pTrigger.  But there might be additional
92706 ** triggers on pTab in the TEMP schema.  This routine prepends all
92707 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
92708 ** and returns the combined list.
92709 **
92710 ** To state it another way:  This routine returns a list of all triggers
92711 ** that fire off of pTab.  The list will include any TEMP triggers on
92712 ** pTab as well as the triggers lised in pTab->pTrigger.
92713 */
92714 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
92715   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
92716   Trigger *pList = 0;                  /* List of triggers to return */
92717
92718   if( pParse->disableTriggers ){
92719     return 0;
92720   }
92721
92722   if( pTmpSchema!=pTab->pSchema ){
92723     HashElem *p;
92724     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
92725       Trigger *pTrig = (Trigger *)sqliteHashData(p);
92726       if( pTrig->pTabSchema==pTab->pSchema
92727        && 0==sqlite3StrICmp(pTrig->table, pTab->zName) 
92728       ){
92729         pTrig->pNext = (pList ? pList : pTab->pTrigger);
92730         pList = pTrig;
92731       }
92732     }
92733   }
92734
92735   return (pList ? pList : pTab->pTrigger);
92736 }
92737
92738 /*
92739 ** This is called by the parser when it sees a CREATE TRIGGER statement
92740 ** up to the point of the BEGIN before the trigger actions.  A Trigger
92741 ** structure is generated based on the information available and stored
92742 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
92743 ** sqlite3FinishTrigger() function is called to complete the trigger
92744 ** construction process.
92745 */
92746 SQLITE_PRIVATE void sqlite3BeginTrigger(
92747   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
92748   Token *pName1,      /* The name of the trigger */
92749   Token *pName2,      /* The name of the trigger */
92750   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
92751   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
92752   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
92753   SrcList *pTableName,/* The name of the table/view the trigger applies to */
92754   Expr *pWhen,        /* WHEN clause */
92755   int isTemp,         /* True if the TEMPORARY keyword is present */
92756   int noErr           /* Suppress errors if the trigger already exists */
92757 ){
92758   Trigger *pTrigger = 0;  /* The new trigger */
92759   Table *pTab;            /* Table that the trigger fires off of */
92760   char *zName = 0;        /* Name of the trigger */
92761   sqlite3 *db = pParse->db;  /* The database connection */
92762   int iDb;                /* The database to store the trigger in */
92763   Token *pName;           /* The unqualified db name */
92764   DbFixer sFix;           /* State vector for the DB fixer */
92765   int iTabDb;             /* Index of the database holding pTab */
92766
92767   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
92768   assert( pName2!=0 );
92769   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
92770   assert( op>0 && op<0xff );
92771   if( isTemp ){
92772     /* If TEMP was specified, then the trigger name may not be qualified. */
92773     if( pName2->n>0 ){
92774       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
92775       goto trigger_cleanup;
92776     }
92777     iDb = 1;
92778     pName = pName1;
92779   }else{
92780     /* Figure out the db that the the trigger will be created in */
92781     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
92782     if( iDb<0 ){
92783       goto trigger_cleanup;
92784     }
92785   }
92786
92787   /* If the trigger name was unqualified, and the table is a temp table,
92788   ** then set iDb to 1 to create the trigger in the temporary database.
92789   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
92790   ** exist, the error is caught by the block below.
92791   */
92792   if( !pTableName || db->mallocFailed ){
92793     goto trigger_cleanup;
92794   }
92795   pTab = sqlite3SrcListLookup(pParse, pTableName);
92796   if( db->init.busy==0 && pName2->n==0 && pTab
92797         && pTab->pSchema==db->aDb[1].pSchema ){
92798     iDb = 1;
92799   }
92800
92801   /* Ensure the table name matches database name and that the table exists */
92802   if( db->mallocFailed ) goto trigger_cleanup;
92803   assert( pTableName->nSrc==1 );
92804   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
92805       sqlite3FixSrcList(&sFix, pTableName) ){
92806     goto trigger_cleanup;
92807   }
92808   pTab = sqlite3SrcListLookup(pParse, pTableName);
92809   if( !pTab ){
92810     /* The table does not exist. */
92811     if( db->init.iDb==1 ){
92812       /* Ticket #3810.
92813       ** Normally, whenever a table is dropped, all associated triggers are
92814       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
92815       ** and the table is dropped by a different database connection, the
92816       ** trigger is not visible to the database connection that does the
92817       ** drop so the trigger cannot be dropped.  This results in an
92818       ** "orphaned trigger" - a trigger whose associated table is missing.
92819       */
92820       db->init.orphanTrigger = 1;
92821     }
92822     goto trigger_cleanup;
92823   }
92824   if( IsVirtual(pTab) ){
92825     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
92826     goto trigger_cleanup;
92827   }
92828
92829   /* Check that the trigger name is not reserved and that no trigger of the
92830   ** specified name exists */
92831   zName = sqlite3NameFromToken(db, pName);
92832   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
92833     goto trigger_cleanup;
92834   }
92835   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
92836                       zName, sqlite3Strlen30(zName)) ){
92837     if( !noErr ){
92838       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
92839     }
92840     goto trigger_cleanup;
92841   }
92842
92843   /* Do not create a trigger on a system table */
92844   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
92845     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
92846     pParse->nErr++;
92847     goto trigger_cleanup;
92848   }
92849
92850   /* INSTEAD of triggers are only for views and views only support INSTEAD
92851   ** of triggers.
92852   */
92853   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
92854     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
92855         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
92856     goto trigger_cleanup;
92857   }
92858   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
92859     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
92860         " trigger on table: %S", pTableName, 0);
92861     goto trigger_cleanup;
92862   }
92863   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
92864
92865 #ifndef SQLITE_OMIT_AUTHORIZATION
92866   {
92867     int code = SQLITE_CREATE_TRIGGER;
92868     const char *zDb = db->aDb[iTabDb].zName;
92869     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
92870     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
92871     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
92872       goto trigger_cleanup;
92873     }
92874     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
92875       goto trigger_cleanup;
92876     }
92877   }
92878 #endif
92879
92880   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
92881   ** cannot appear on views.  So we might as well translate every
92882   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
92883   ** elsewhere.
92884   */
92885   if (tr_tm == TK_INSTEAD){
92886     tr_tm = TK_BEFORE;
92887   }
92888
92889   /* Build the Trigger object */
92890   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
92891   if( pTrigger==0 ) goto trigger_cleanup;
92892   pTrigger->zName = zName;
92893   zName = 0;
92894   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
92895   pTrigger->pSchema = db->aDb[iDb].pSchema;
92896   pTrigger->pTabSchema = pTab->pSchema;
92897   pTrigger->op = (u8)op;
92898   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
92899   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
92900   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
92901   assert( pParse->pNewTrigger==0 );
92902   pParse->pNewTrigger = pTrigger;
92903
92904 trigger_cleanup:
92905   sqlite3DbFree(db, zName);
92906   sqlite3SrcListDelete(db, pTableName);
92907   sqlite3IdListDelete(db, pColumns);
92908   sqlite3ExprDelete(db, pWhen);
92909   if( !pParse->pNewTrigger ){
92910     sqlite3DeleteTrigger(db, pTrigger);
92911   }else{
92912     assert( pParse->pNewTrigger==pTrigger );
92913   }
92914 }
92915
92916 /*
92917 ** This routine is called after all of the trigger actions have been parsed
92918 ** in order to complete the process of building the trigger.
92919 */
92920 SQLITE_PRIVATE void sqlite3FinishTrigger(
92921   Parse *pParse,          /* Parser context */
92922   TriggerStep *pStepList, /* The triggered program */
92923   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
92924 ){
92925   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
92926   char *zName;                            /* Name of trigger */
92927   sqlite3 *db = pParse->db;               /* The database */
92928   DbFixer sFix;                           /* Fixer object */
92929   int iDb;                                /* Database containing the trigger */
92930   Token nameToken;                        /* Trigger name for error reporting */
92931
92932   pTrig = pParse->pNewTrigger;
92933   pParse->pNewTrigger = 0;
92934   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
92935   zName = pTrig->zName;
92936   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
92937   pTrig->step_list = pStepList;
92938   while( pStepList ){
92939     pStepList->pTrig = pTrig;
92940     pStepList = pStepList->pNext;
92941   }
92942   nameToken.z = pTrig->zName;
92943   nameToken.n = sqlite3Strlen30(nameToken.z);
92944   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken) 
92945           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
92946     goto triggerfinish_cleanup;
92947   }
92948
92949   /* if we are not initializing,
92950   ** build the sqlite_master entry
92951   */
92952   if( !db->init.busy ){
92953     Vdbe *v;
92954     char *z;
92955
92956     /* Make an entry in the sqlite_master table */
92957     v = sqlite3GetVdbe(pParse);
92958     if( v==0 ) goto triggerfinish_cleanup;
92959     sqlite3BeginWriteOperation(pParse, 0, iDb);
92960     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
92961     sqlite3NestedParse(pParse,
92962        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
92963        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
92964        pTrig->table, z);
92965     sqlite3DbFree(db, z);
92966     sqlite3ChangeCookie(pParse, iDb);
92967     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
92968         db, "type='trigger' AND name='%q'", zName), P4_DYNAMIC
92969     );
92970   }
92971
92972   if( db->init.busy ){
92973     Trigger *pLink = pTrig;
92974     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
92975     pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
92976     if( pTrig ){
92977       db->mallocFailed = 1;
92978     }else if( pLink->pSchema==pLink->pTabSchema ){
92979       Table *pTab;
92980       int n = sqlite3Strlen30(pLink->table);
92981       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
92982       assert( pTab!=0 );
92983       pLink->pNext = pTab->pTrigger;
92984       pTab->pTrigger = pLink;
92985     }
92986   }
92987
92988 triggerfinish_cleanup:
92989   sqlite3DeleteTrigger(db, pTrig);
92990   assert( !pParse->pNewTrigger );
92991   sqlite3DeleteTriggerStep(db, pStepList);
92992 }
92993
92994 /*
92995 ** Turn a SELECT statement (that the pSelect parameter points to) into
92996 ** a trigger step.  Return a pointer to a TriggerStep structure.
92997 **
92998 ** The parser calls this routine when it finds a SELECT statement in
92999 ** body of a TRIGGER.  
93000 */
93001 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
93002   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
93003   if( pTriggerStep==0 ) {
93004     sqlite3SelectDelete(db, pSelect);
93005     return 0;
93006   }
93007   pTriggerStep->op = TK_SELECT;
93008   pTriggerStep->pSelect = pSelect;
93009   pTriggerStep->orconf = OE_Default;
93010   return pTriggerStep;
93011 }
93012
93013 /*
93014 ** Allocate space to hold a new trigger step.  The allocated space
93015 ** holds both the TriggerStep object and the TriggerStep.target.z string.
93016 **
93017 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
93018 */
93019 static TriggerStep *triggerStepAllocate(
93020   sqlite3 *db,                /* Database connection */
93021   u8 op,                      /* Trigger opcode */
93022   Token *pName                /* The target name */
93023 ){
93024   TriggerStep *pTriggerStep;
93025
93026   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
93027   if( pTriggerStep ){
93028     char *z = (char*)&pTriggerStep[1];
93029     memcpy(z, pName->z, pName->n);
93030     pTriggerStep->target.z = z;
93031     pTriggerStep->target.n = pName->n;
93032     pTriggerStep->op = op;
93033   }
93034   return pTriggerStep;
93035 }
93036
93037 /*
93038 ** Build a trigger step out of an INSERT statement.  Return a pointer
93039 ** to the new trigger step.
93040 **
93041 ** The parser calls this routine when it sees an INSERT inside the
93042 ** body of a trigger.
93043 */
93044 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
93045   sqlite3 *db,        /* The database connection */
93046   Token *pTableName,  /* Name of the table into which we insert */
93047   IdList *pColumn,    /* List of columns in pTableName to insert into */
93048   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
93049   Select *pSelect,    /* A SELECT statement that supplies values */
93050   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
93051 ){
93052   TriggerStep *pTriggerStep;
93053
93054   assert(pEList == 0 || pSelect == 0);
93055   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
93056
93057   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
93058   if( pTriggerStep ){
93059     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
93060     pTriggerStep->pIdList = pColumn;
93061     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
93062     pTriggerStep->orconf = orconf;
93063   }else{
93064     sqlite3IdListDelete(db, pColumn);
93065   }
93066   sqlite3ExprListDelete(db, pEList);
93067   sqlite3SelectDelete(db, pSelect);
93068
93069   return pTriggerStep;
93070 }
93071
93072 /*
93073 ** Construct a trigger step that implements an UPDATE statement and return
93074 ** a pointer to that trigger step.  The parser calls this routine when it
93075 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
93076 */
93077 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
93078   sqlite3 *db,         /* The database connection */
93079   Token *pTableName,   /* Name of the table to be updated */
93080   ExprList *pEList,    /* The SET clause: list of column and new values */
93081   Expr *pWhere,        /* The WHERE clause */
93082   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
93083 ){
93084   TriggerStep *pTriggerStep;
93085
93086   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
93087   if( pTriggerStep ){
93088     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
93089     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
93090     pTriggerStep->orconf = orconf;
93091   }
93092   sqlite3ExprListDelete(db, pEList);
93093   sqlite3ExprDelete(db, pWhere);
93094   return pTriggerStep;
93095 }
93096
93097 /*
93098 ** Construct a trigger step that implements a DELETE statement and return
93099 ** a pointer to that trigger step.  The parser calls this routine when it
93100 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
93101 */
93102 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
93103   sqlite3 *db,            /* Database connection */
93104   Token *pTableName,      /* The table from which rows are deleted */
93105   Expr *pWhere            /* The WHERE clause */
93106 ){
93107   TriggerStep *pTriggerStep;
93108
93109   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
93110   if( pTriggerStep ){
93111     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
93112     pTriggerStep->orconf = OE_Default;
93113   }
93114   sqlite3ExprDelete(db, pWhere);
93115   return pTriggerStep;
93116 }
93117
93118 /* 
93119 ** Recursively delete a Trigger structure
93120 */
93121 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
93122   if( pTrigger==0 ) return;
93123   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
93124   sqlite3DbFree(db, pTrigger->zName);
93125   sqlite3DbFree(db, pTrigger->table);
93126   sqlite3ExprDelete(db, pTrigger->pWhen);
93127   sqlite3IdListDelete(db, pTrigger->pColumns);
93128   sqlite3DbFree(db, pTrigger);
93129 }
93130
93131 /*
93132 ** This function is called to drop a trigger from the database schema. 
93133 **
93134 ** This may be called directly from the parser and therefore identifies
93135 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
93136 ** same job as this routine except it takes a pointer to the trigger
93137 ** instead of the trigger name.
93138 **/
93139 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
93140   Trigger *pTrigger = 0;
93141   int i;
93142   const char *zDb;
93143   const char *zName;
93144   int nName;
93145   sqlite3 *db = pParse->db;
93146
93147   if( db->mallocFailed ) goto drop_trigger_cleanup;
93148   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
93149     goto drop_trigger_cleanup;
93150   }
93151
93152   assert( pName->nSrc==1 );
93153   zDb = pName->a[0].zDatabase;
93154   zName = pName->a[0].zName;
93155   nName = sqlite3Strlen30(zName);
93156   for(i=OMIT_TEMPDB; i<db->nDb; i++){
93157     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
93158     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
93159     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
93160     if( pTrigger ) break;
93161   }
93162   if( !pTrigger ){
93163     if( !noErr ){
93164       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
93165     }
93166     pParse->checkSchema = 1;
93167     goto drop_trigger_cleanup;
93168   }
93169   sqlite3DropTriggerPtr(pParse, pTrigger);
93170
93171 drop_trigger_cleanup:
93172   sqlite3SrcListDelete(db, pName);
93173 }
93174
93175 /*
93176 ** Return a pointer to the Table structure for the table that a trigger
93177 ** is set on.
93178 */
93179 static Table *tableOfTrigger(Trigger *pTrigger){
93180   int n = sqlite3Strlen30(pTrigger->table);
93181   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
93182 }
93183
93184
93185 /*
93186 ** Drop a trigger given a pointer to that trigger. 
93187 */
93188 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
93189   Table   *pTable;
93190   Vdbe *v;
93191   sqlite3 *db = pParse->db;
93192   int iDb;
93193
93194   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
93195   assert( iDb>=0 && iDb<db->nDb );
93196   pTable = tableOfTrigger(pTrigger);
93197   assert( pTable );
93198   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
93199 #ifndef SQLITE_OMIT_AUTHORIZATION
93200   {
93201     int code = SQLITE_DROP_TRIGGER;
93202     const char *zDb = db->aDb[iDb].zName;
93203     const char *zTab = SCHEMA_TABLE(iDb);
93204     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
93205     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
93206       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
93207       return;
93208     }
93209   }
93210 #endif
93211
93212   /* Generate code to destroy the database record of the trigger.
93213   */
93214   assert( pTable!=0 );
93215   if( (v = sqlite3GetVdbe(pParse))!=0 ){
93216     int base;
93217     static const VdbeOpList dropTrigger[] = {
93218       { OP_Rewind,     0, ADDR(9),  0},
93219       { OP_String8,    0, 1,        0}, /* 1 */
93220       { OP_Column,     0, 1,        2},
93221       { OP_Ne,         2, ADDR(8),  1},
93222       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
93223       { OP_Column,     0, 0,        2},
93224       { OP_Ne,         2, ADDR(8),  1},
93225       { OP_Delete,     0, 0,        0},
93226       { OP_Next,       0, ADDR(1),  0}, /* 8 */
93227     };
93228
93229     sqlite3BeginWriteOperation(pParse, 0, iDb);
93230     sqlite3OpenMasterTable(pParse, iDb);
93231     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
93232     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, 0);
93233     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
93234     sqlite3ChangeCookie(pParse, iDb);
93235     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
93236     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
93237     if( pParse->nMem<3 ){
93238       pParse->nMem = 3;
93239     }
93240   }
93241 }
93242
93243 /*
93244 ** Remove a trigger from the hash tables of the sqlite* pointer.
93245 */
93246 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
93247   Hash *pHash = &(db->aDb[iDb].pSchema->trigHash);
93248   Trigger *pTrigger;
93249   pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
93250   if( ALWAYS(pTrigger) ){
93251     if( pTrigger->pSchema==pTrigger->pTabSchema ){
93252       Table *pTab = tableOfTrigger(pTrigger);
93253       Trigger **pp;
93254       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
93255       *pp = (*pp)->pNext;
93256     }
93257     sqlite3DeleteTrigger(db, pTrigger);
93258     db->flags |= SQLITE_InternChanges;
93259   }
93260 }
93261
93262 /*
93263 ** pEList is the SET clause of an UPDATE statement.  Each entry
93264 ** in pEList is of the format <id>=<expr>.  If any of the entries
93265 ** in pEList have an <id> which matches an identifier in pIdList,
93266 ** then return TRUE.  If pIdList==NULL, then it is considered a
93267 ** wildcard that matches anything.  Likewise if pEList==NULL then
93268 ** it matches anything so always return true.  Return false only
93269 ** if there is no match.
93270 */
93271 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
93272   int e;
93273   if( pIdList==0 || NEVER(pEList==0) ) return 1;
93274   for(e=0; e<pEList->nExpr; e++){
93275     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
93276   }
93277   return 0; 
93278 }
93279
93280 /*
93281 ** Return a list of all triggers on table pTab if there exists at least
93282 ** one trigger that must be fired when an operation of type 'op' is 
93283 ** performed on the table, and, if that operation is an UPDATE, if at
93284 ** least one of the columns in pChanges is being modified.
93285 */
93286 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
93287   Parse *pParse,          /* Parse context */
93288   Table *pTab,            /* The table the contains the triggers */
93289   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
93290   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
93291   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
93292 ){
93293   int mask = 0;
93294   Trigger *pList = sqlite3TriggerList(pParse, pTab);
93295   Trigger *p;
93296   assert( pList==0 || IsVirtual(pTab)==0 );
93297   for(p=pList; p; p=p->pNext){
93298     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
93299       mask |= p->tr_tm;
93300     }
93301   }
93302   if( pMask ){
93303     *pMask = mask;
93304   }
93305   return (mask ? pList : 0);
93306 }
93307
93308 /*
93309 ** Convert the pStep->target token into a SrcList and return a pointer
93310 ** to that SrcList.
93311 **
93312 ** This routine adds a specific database name, if needed, to the target when
93313 ** forming the SrcList.  This prevents a trigger in one database from
93314 ** referring to a target in another database.  An exception is when the
93315 ** trigger is in TEMP in which case it can refer to any other database it
93316 ** wants.
93317 */
93318 static SrcList *targetSrcList(
93319   Parse *pParse,       /* The parsing context */
93320   TriggerStep *pStep   /* The trigger containing the target token */
93321 ){
93322   int iDb;             /* Index of the database to use */
93323   SrcList *pSrc;       /* SrcList to be returned */
93324
93325   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
93326   if( pSrc ){
93327     assert( pSrc->nSrc>0 );
93328     assert( pSrc->a!=0 );
93329     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
93330     if( iDb==0 || iDb>=2 ){
93331       sqlite3 *db = pParse->db;
93332       assert( iDb<pParse->db->nDb );
93333       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
93334     }
93335   }
93336   return pSrc;
93337 }
93338
93339 /*
93340 ** Generate VDBE code for the statements inside the body of a single 
93341 ** trigger.
93342 */
93343 static int codeTriggerProgram(
93344   Parse *pParse,            /* The parser context */
93345   TriggerStep *pStepList,   /* List of statements inside the trigger body */
93346   int orconf                /* Conflict algorithm. (OE_Abort, etc) */  
93347 ){
93348   TriggerStep *pStep;
93349   Vdbe *v = pParse->pVdbe;
93350   sqlite3 *db = pParse->db;
93351
93352   assert( pParse->pTriggerTab && pParse->pToplevel );
93353   assert( pStepList );
93354   assert( v!=0 );
93355   for(pStep=pStepList; pStep; pStep=pStep->pNext){
93356     /* Figure out the ON CONFLICT policy that will be used for this step
93357     ** of the trigger program. If the statement that caused this trigger
93358     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
93359     ** the ON CONFLICT policy that was specified as part of the trigger
93360     ** step statement. Example:
93361     **
93362     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
93363     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
93364     **   END;
93365     **
93366     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
93367     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
93368     */
93369     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
93370
93371     switch( pStep->op ){
93372       case TK_UPDATE: {
93373         sqlite3Update(pParse, 
93374           targetSrcList(pParse, pStep),
93375           sqlite3ExprListDup(db, pStep->pExprList, 0), 
93376           sqlite3ExprDup(db, pStep->pWhere, 0), 
93377           pParse->eOrconf
93378         );
93379         break;
93380       }
93381       case TK_INSERT: {
93382         sqlite3Insert(pParse, 
93383           targetSrcList(pParse, pStep),
93384           sqlite3ExprListDup(db, pStep->pExprList, 0), 
93385           sqlite3SelectDup(db, pStep->pSelect, 0), 
93386           sqlite3IdListDup(db, pStep->pIdList), 
93387           pParse->eOrconf
93388         );
93389         break;
93390       }
93391       case TK_DELETE: {
93392         sqlite3DeleteFrom(pParse, 
93393           targetSrcList(pParse, pStep),
93394           sqlite3ExprDup(db, pStep->pWhere, 0)
93395         );
93396         break;
93397       }
93398       default: assert( pStep->op==TK_SELECT ); {
93399         SelectDest sDest;
93400         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
93401         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
93402         sqlite3Select(pParse, pSelect, &sDest);
93403         sqlite3SelectDelete(db, pSelect);
93404         break;
93405       }
93406     } 
93407     if( pStep->op!=TK_SELECT ){
93408       sqlite3VdbeAddOp0(v, OP_ResetCount);
93409     }
93410   }
93411
93412   return 0;
93413 }
93414
93415 #ifdef SQLITE_DEBUG
93416 /*
93417 ** This function is used to add VdbeComment() annotations to a VDBE
93418 ** program. It is not used in production code, only for debugging.
93419 */
93420 static const char *onErrorText(int onError){
93421   switch( onError ){
93422     case OE_Abort:    return "abort";
93423     case OE_Rollback: return "rollback";
93424     case OE_Fail:     return "fail";
93425     case OE_Replace:  return "replace";
93426     case OE_Ignore:   return "ignore";
93427     case OE_Default:  return "default";
93428   }
93429   return "n/a";
93430 }
93431 #endif
93432
93433 /*
93434 ** Parse context structure pFrom has just been used to create a sub-vdbe
93435 ** (trigger program). If an error has occurred, transfer error information
93436 ** from pFrom to pTo.
93437 */
93438 static void transferParseError(Parse *pTo, Parse *pFrom){
93439   assert( pFrom->zErrMsg==0 || pFrom->nErr );
93440   assert( pTo->zErrMsg==0 || pTo->nErr );
93441   if( pTo->nErr==0 ){
93442     pTo->zErrMsg = pFrom->zErrMsg;
93443     pTo->nErr = pFrom->nErr;
93444   }else{
93445     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
93446   }
93447 }
93448
93449 /*
93450 ** Create and populate a new TriggerPrg object with a sub-program 
93451 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
93452 */
93453 static TriggerPrg *codeRowTrigger(
93454   Parse *pParse,       /* Current parse context */
93455   Trigger *pTrigger,   /* Trigger to code */
93456   Table *pTab,         /* The table pTrigger is attached to */
93457   int orconf           /* ON CONFLICT policy to code trigger program with */
93458 ){
93459   Parse *pTop = sqlite3ParseToplevel(pParse);
93460   sqlite3 *db = pParse->db;   /* Database handle */
93461   TriggerPrg *pPrg;           /* Value to return */
93462   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
93463   Vdbe *v;                    /* Temporary VM */
93464   NameContext sNC;            /* Name context for sub-vdbe */
93465   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
93466   Parse *pSubParse;           /* Parse context for sub-vdbe */
93467   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
93468
93469   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
93470   assert( pTop->pVdbe );
93471
93472   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
93473   ** are freed if an error occurs, link them into the Parse.pTriggerPrg 
93474   ** list of the top-level Parse object sooner rather than later.  */
93475   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
93476   if( !pPrg ) return 0;
93477   pPrg->pNext = pTop->pTriggerPrg;
93478   pTop->pTriggerPrg = pPrg;
93479   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
93480   if( !pProgram ) return 0;
93481   sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
93482   pPrg->pTrigger = pTrigger;
93483   pPrg->orconf = orconf;
93484   pPrg->aColmask[0] = 0xffffffff;
93485   pPrg->aColmask[1] = 0xffffffff;
93486
93487   /* Allocate and populate a new Parse context to use for coding the 
93488   ** trigger sub-program.  */
93489   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
93490   if( !pSubParse ) return 0;
93491   memset(&sNC, 0, sizeof(sNC));
93492   sNC.pParse = pSubParse;
93493   pSubParse->db = db;
93494   pSubParse->pTriggerTab = pTab;
93495   pSubParse->pToplevel = pTop;
93496   pSubParse->zAuthContext = pTrigger->zName;
93497   pSubParse->eTriggerOp = pTrigger->op;
93498   pSubParse->nQueryLoop = pParse->nQueryLoop;
93499
93500   v = sqlite3GetVdbe(pSubParse);
93501   if( v ){
93502     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", 
93503       pTrigger->zName, onErrorText(orconf),
93504       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
93505         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
93506         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
93507         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
93508       pTab->zName
93509     ));
93510 #ifndef SQLITE_OMIT_TRACE
93511     sqlite3VdbeChangeP4(v, -1, 
93512       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
93513     );
93514 #endif
93515
93516     /* If one was specified, code the WHEN clause. If it evaluates to false
93517     ** (or NULL) the sub-vdbe is immediately halted by jumping to the 
93518     ** OP_Halt inserted at the end of the program.  */
93519     if( pTrigger->pWhen ){
93520       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
93521       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) 
93522        && db->mallocFailed==0 
93523       ){
93524         iEndTrigger = sqlite3VdbeMakeLabel(v);
93525         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
93526       }
93527       sqlite3ExprDelete(db, pWhen);
93528     }
93529
93530     /* Code the trigger program into the sub-vdbe. */
93531     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
93532
93533     /* Insert an OP_Halt at the end of the sub-program. */
93534     if( iEndTrigger ){
93535       sqlite3VdbeResolveLabel(v, iEndTrigger);
93536     }
93537     sqlite3VdbeAddOp0(v, OP_Halt);
93538     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
93539
93540     transferParseError(pParse, pSubParse);
93541     if( db->mallocFailed==0 ){
93542       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
93543     }
93544     pProgram->nMem = pSubParse->nMem;
93545     pProgram->nCsr = pSubParse->nTab;
93546     pProgram->token = (void *)pTrigger;
93547     pPrg->aColmask[0] = pSubParse->oldmask;
93548     pPrg->aColmask[1] = pSubParse->newmask;
93549     sqlite3VdbeDelete(v);
93550   }
93551
93552   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
93553   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
93554   sqlite3StackFree(db, pSubParse);
93555
93556   return pPrg;
93557 }
93558     
93559 /*
93560 ** Return a pointer to a TriggerPrg object containing the sub-program for
93561 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
93562 ** TriggerPrg object exists, a new object is allocated and populated before
93563 ** being returned.
93564 */
93565 static TriggerPrg *getRowTrigger(
93566   Parse *pParse,       /* Current parse context */
93567   Trigger *pTrigger,   /* Trigger to code */
93568   Table *pTab,         /* The table trigger pTrigger is attached to */
93569   int orconf           /* ON CONFLICT algorithm. */
93570 ){
93571   Parse *pRoot = sqlite3ParseToplevel(pParse);
93572   TriggerPrg *pPrg;
93573
93574   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
93575
93576   /* It may be that this trigger has already been coded (or is in the
93577   ** process of being coded). If this is the case, then an entry with
93578   ** a matching TriggerPrg.pTrigger field will be present somewhere
93579   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
93580   for(pPrg=pRoot->pTriggerPrg; 
93581       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); 
93582       pPrg=pPrg->pNext
93583   );
93584
93585   /* If an existing TriggerPrg could not be located, create a new one. */
93586   if( !pPrg ){
93587     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
93588   }
93589
93590   return pPrg;
93591 }
93592
93593 /*
93594 ** Generate code for the trigger program associated with trigger p on 
93595 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
93596 ** function are the same as those described in the header function for
93597 ** sqlite3CodeRowTrigger()
93598 */
93599 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
93600   Parse *pParse,       /* Parse context */
93601   Trigger *p,          /* Trigger to code */
93602   Table *pTab,         /* The table to code triggers from */
93603   int reg,             /* Reg array containing OLD.* and NEW.* values */
93604   int orconf,          /* ON CONFLICT policy */
93605   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
93606 ){
93607   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
93608   TriggerPrg *pPrg;
93609   pPrg = getRowTrigger(pParse, p, pTab, orconf);
93610   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
93611
93612   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
93613   ** is a pointer to the sub-vdbe containing the trigger program.  */
93614   if( pPrg ){
93615     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
93616
93617     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
93618     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
93619     VdbeComment(
93620         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
93621
93622     /* Set the P5 operand of the OP_Program instruction to non-zero if
93623     ** recursive invocation of this trigger program is disallowed. Recursive
93624     ** invocation is disallowed if (a) the sub-program is really a trigger,
93625     ** not a foreign key action, and (b) the flag to enable recursive triggers
93626     ** is clear.  */
93627     sqlite3VdbeChangeP5(v, (u8)bRecursive);
93628   }
93629 }
93630
93631 /*
93632 ** This is called to code the required FOR EACH ROW triggers for an operation
93633 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
93634 ** is given by the op paramater. The tr_tm parameter determines whether the
93635 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
93636 ** parameter pChanges is passed the list of columns being modified.
93637 **
93638 ** If there are no triggers that fire at the specified time for the specified
93639 ** operation on pTab, this function is a no-op.
93640 **
93641 ** The reg argument is the address of the first in an array of registers 
93642 ** that contain the values substituted for the new.* and old.* references
93643 ** in the trigger program. If N is the number of columns in table pTab
93644 ** (a copy of pTab->nCol), then registers are populated as follows:
93645 **
93646 **   Register       Contains
93647 **   ------------------------------------------------------
93648 **   reg+0          OLD.rowid
93649 **   reg+1          OLD.* value of left-most column of pTab
93650 **   ...            ...
93651 **   reg+N          OLD.* value of right-most column of pTab
93652 **   reg+N+1        NEW.rowid
93653 **   reg+N+2        OLD.* value of left-most column of pTab
93654 **   ...            ...
93655 **   reg+N+N+1      NEW.* value of right-most column of pTab
93656 **
93657 ** For ON DELETE triggers, the registers containing the NEW.* values will
93658 ** never be accessed by the trigger program, so they are not allocated or 
93659 ** populated by the caller (there is no data to populate them with anyway). 
93660 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
93661 ** are never accessed, and so are not allocated by the caller. So, for an
93662 ** ON INSERT trigger, the value passed to this function as parameter reg
93663 ** is not a readable register, although registers (reg+N) through 
93664 ** (reg+N+N+1) are.
93665 **
93666 ** Parameter orconf is the default conflict resolution algorithm for the
93667 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
93668 ** is the instruction that control should jump to if a trigger program
93669 ** raises an IGNORE exception.
93670 */
93671 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
93672   Parse *pParse,       /* Parse context */
93673   Trigger *pTrigger,   /* List of triggers on table pTab */
93674   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
93675   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
93676   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
93677   Table *pTab,         /* The table to code triggers from */
93678   int reg,             /* The first in an array of registers (see above) */
93679   int orconf,          /* ON CONFLICT policy */
93680   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
93681 ){
93682   Trigger *p;          /* Used to iterate through pTrigger list */
93683
93684   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
93685   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
93686   assert( (op==TK_UPDATE)==(pChanges!=0) );
93687
93688   for(p=pTrigger; p; p=p->pNext){
93689
93690     /* Sanity checking:  The schema for the trigger and for the table are
93691     ** always defined.  The trigger must be in the same schema as the table
93692     ** or else it must be a TEMP trigger. */
93693     assert( p->pSchema!=0 );
93694     assert( p->pTabSchema!=0 );
93695     assert( p->pSchema==p->pTabSchema 
93696          || p->pSchema==pParse->db->aDb[1].pSchema );
93697
93698     /* Determine whether we should code this trigger */
93699     if( p->op==op 
93700      && p->tr_tm==tr_tm 
93701      && checkColumnOverlap(p->pColumns, pChanges)
93702     ){
93703       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
93704     }
93705   }
93706 }
93707
93708 /*
93709 ** Triggers may access values stored in the old.* or new.* pseudo-table. 
93710 ** This function returns a 32-bit bitmask indicating which columns of the 
93711 ** old.* or new.* tables actually are used by triggers. This information 
93712 ** may be used by the caller, for example, to avoid having to load the entire
93713 ** old.* record into memory when executing an UPDATE or DELETE command.
93714 **
93715 ** Bit 0 of the returned mask is set if the left-most column of the
93716 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
93717 ** the second leftmost column value is required, and so on. If there
93718 ** are more than 32 columns in the table, and at least one of the columns
93719 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
93720 **
93721 ** It is not possible to determine if the old.rowid or new.rowid column is 
93722 ** accessed by triggers. The caller must always assume that it is.
93723 **
93724 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
93725 ** applies to the old.* table. If 1, the new.* table.
93726 **
93727 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
93728 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
93729 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
93730 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
93731 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
93732 */
93733 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
93734   Parse *pParse,       /* Parse context */
93735   Trigger *pTrigger,   /* List of triggers on table pTab */
93736   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
93737   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
93738   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
93739   Table *pTab,         /* The table to code triggers from */
93740   int orconf           /* Default ON CONFLICT policy for trigger steps */
93741 ){
93742   const int op = pChanges ? TK_UPDATE : TK_DELETE;
93743   u32 mask = 0;
93744   Trigger *p;
93745
93746   assert( isNew==1 || isNew==0 );
93747   for(p=pTrigger; p; p=p->pNext){
93748     if( p->op==op && (tr_tm&p->tr_tm)
93749      && checkColumnOverlap(p->pColumns,pChanges)
93750     ){
93751       TriggerPrg *pPrg;
93752       pPrg = getRowTrigger(pParse, p, pTab, orconf);
93753       if( pPrg ){
93754         mask |= pPrg->aColmask[isNew];
93755       }
93756     }
93757   }
93758
93759   return mask;
93760 }
93761
93762 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
93763
93764 /************** End of trigger.c *********************************************/
93765 /************** Begin file update.c ******************************************/
93766 /*
93767 ** 2001 September 15
93768 **
93769 ** The author disclaims copyright to this source code.  In place of
93770 ** a legal notice, here is a blessing:
93771 **
93772 **    May you do good and not evil.
93773 **    May you find forgiveness for yourself and forgive others.
93774 **    May you share freely, never taking more than you give.
93775 **
93776 *************************************************************************
93777 ** This file contains C code routines that are called by the parser
93778 ** to handle UPDATE statements.
93779 */
93780
93781 #ifndef SQLITE_OMIT_VIRTUALTABLE
93782 /* Forward declaration */
93783 static void updateVirtualTable(
93784   Parse *pParse,       /* The parsing context */
93785   SrcList *pSrc,       /* The virtual table to be modified */
93786   Table *pTab,         /* The virtual table */
93787   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
93788   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
93789   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
93790   Expr *pWhere         /* WHERE clause of the UPDATE statement */
93791 );
93792 #endif /* SQLITE_OMIT_VIRTUALTABLE */
93793
93794 /*
93795 ** The most recently coded instruction was an OP_Column to retrieve the
93796 ** i-th column of table pTab. This routine sets the P4 parameter of the 
93797 ** OP_Column to the default value, if any.
93798 **
93799 ** The default value of a column is specified by a DEFAULT clause in the 
93800 ** column definition. This was either supplied by the user when the table
93801 ** was created, or added later to the table definition by an ALTER TABLE
93802 ** command. If the latter, then the row-records in the table btree on disk
93803 ** may not contain a value for the column and the default value, taken
93804 ** from the P4 parameter of the OP_Column instruction, is returned instead.
93805 ** If the former, then all row-records are guaranteed to include a value
93806 ** for the column and the P4 value is not required.
93807 **
93808 ** Column definitions created by an ALTER TABLE command may only have 
93809 ** literal default values specified: a number, null or a string. (If a more
93810 ** complicated default expression value was provided, it is evaluated 
93811 ** when the ALTER TABLE is executed and one of the literal values written
93812 ** into the sqlite_master table.)
93813 **
93814 ** Therefore, the P4 parameter is only required if the default value for
93815 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
93816 ** function is capable of transforming these types of expressions into
93817 ** sqlite3_value objects.
93818 **
93819 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
93820 ** on register iReg. This is used when an equivalent integer value is 
93821 ** stored in place of an 8-byte floating point value in order to save 
93822 ** space.
93823 */
93824 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
93825   assert( pTab!=0 );
93826   if( !pTab->pSelect ){
93827     sqlite3_value *pValue;
93828     u8 enc = ENC(sqlite3VdbeDb(v));
93829     Column *pCol = &pTab->aCol[i];
93830     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
93831     assert( i<pTab->nCol );
93832     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
93833                          pCol->affinity, &pValue);
93834     if( pValue ){
93835       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
93836     }
93837 #ifndef SQLITE_OMIT_FLOATING_POINT
93838     if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
93839       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
93840     }
93841 #endif
93842   }
93843 }
93844
93845 /*
93846 ** Process an UPDATE statement.
93847 **
93848 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
93849 **          \_______/ \________/     \______/       \________________/
93850 *            onError   pTabList      pChanges             pWhere
93851 */
93852 SQLITE_PRIVATE void sqlite3Update(
93853   Parse *pParse,         /* The parser context */
93854   SrcList *pTabList,     /* The table in which we should change things */
93855   ExprList *pChanges,    /* Things to be changed */
93856   Expr *pWhere,          /* The WHERE clause.  May be null */
93857   int onError            /* How to handle constraint errors */
93858 ){
93859   int i, j;              /* Loop counters */
93860   Table *pTab;           /* The table to be updated */
93861   int addr = 0;          /* VDBE instruction address of the start of the loop */
93862   WhereInfo *pWInfo;     /* Information about the WHERE clause */
93863   Vdbe *v;               /* The virtual database engine */
93864   Index *pIdx;           /* For looping over indices */
93865   int nIdx;              /* Number of indices that need updating */
93866   int iCur;              /* VDBE Cursor number of pTab */
93867   sqlite3 *db;           /* The database structure */
93868   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
93869   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
93870                          ** an expression for the i-th column of the table.
93871                          ** aXRef[i]==-1 if the i-th column is not changed. */
93872   int chngRowid;         /* True if the record number is being changed */
93873   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
93874   int openAll = 0;       /* True if all indices need to be opened */
93875   AuthContext sContext;  /* The authorization context */
93876   NameContext sNC;       /* The name-context to resolve expressions in */
93877   int iDb;               /* Database containing the table being updated */
93878   int okOnePass;         /* True for one-pass algorithm without the FIFO */
93879   int hasFK;             /* True if foreign key processing is required */
93880
93881 #ifndef SQLITE_OMIT_TRIGGER
93882   int isView;            /* True when updating a view (INSTEAD OF trigger) */
93883   Trigger *pTrigger;     /* List of triggers on pTab, if required */
93884   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
93885 #endif
93886   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
93887
93888   /* Register Allocations */
93889   int regRowCount = 0;   /* A count of rows changed */
93890   int regOldRowid;       /* The old rowid */
93891   int regNewRowid;       /* The new rowid */
93892   int regNew;
93893   int regOld = 0;
93894   int regRowSet = 0;     /* Rowset of rows to be updated */
93895   int regRec;            /* Register used for new table record to insert */
93896
93897   memset(&sContext, 0, sizeof(sContext));
93898   db = pParse->db;
93899   if( pParse->nErr || db->mallocFailed ){
93900     goto update_cleanup;
93901   }
93902   assert( pTabList->nSrc==1 );
93903
93904   /* Locate the table which we want to update. 
93905   */
93906   pTab = sqlite3SrcListLookup(pParse, pTabList);
93907   if( pTab==0 ) goto update_cleanup;
93908   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
93909
93910   /* Figure out if we have any triggers and if the table being
93911   ** updated is a view.
93912   */
93913 #ifndef SQLITE_OMIT_TRIGGER
93914   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
93915   isView = pTab->pSelect!=0;
93916   assert( pTrigger || tmask==0 );
93917 #else
93918 # define pTrigger 0
93919 # define isView 0
93920 # define tmask 0
93921 #endif
93922 #ifdef SQLITE_OMIT_VIEW
93923 # undef isView
93924 # define isView 0
93925 #endif
93926
93927   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
93928     goto update_cleanup;
93929   }
93930   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
93931     goto update_cleanup;
93932   }
93933   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
93934   if( aXRef==0 ) goto update_cleanup;
93935   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
93936
93937   /* Allocate a cursors for the main database table and for all indices.
93938   ** The index cursors might not be used, but if they are used they
93939   ** need to occur right after the database cursor.  So go ahead and
93940   ** allocate enough space, just in case.
93941   */
93942   pTabList->a[0].iCursor = iCur = pParse->nTab++;
93943   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
93944     pParse->nTab++;
93945   }
93946
93947   /* Initialize the name-context */
93948   memset(&sNC, 0, sizeof(sNC));
93949   sNC.pParse = pParse;
93950   sNC.pSrcList = pTabList;
93951
93952   /* Resolve the column names in all the expressions of the
93953   ** of the UPDATE statement.  Also find the column index
93954   ** for each column to be updated in the pChanges array.  For each
93955   ** column to be updated, make sure we have authorization to change
93956   ** that column.
93957   */
93958   chngRowid = 0;
93959   for(i=0; i<pChanges->nExpr; i++){
93960     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
93961       goto update_cleanup;
93962     }
93963     for(j=0; j<pTab->nCol; j++){
93964       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
93965         if( j==pTab->iPKey ){
93966           chngRowid = 1;
93967           pRowidExpr = pChanges->a[i].pExpr;
93968         }
93969         aXRef[j] = i;
93970         break;
93971       }
93972     }
93973     if( j>=pTab->nCol ){
93974       if( sqlite3IsRowid(pChanges->a[i].zName) ){
93975         chngRowid = 1;
93976         pRowidExpr = pChanges->a[i].pExpr;
93977       }else{
93978         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
93979         pParse->checkSchema = 1;
93980         goto update_cleanup;
93981       }
93982     }
93983 #ifndef SQLITE_OMIT_AUTHORIZATION
93984     {
93985       int rc;
93986       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
93987                            pTab->aCol[j].zName, db->aDb[iDb].zName);
93988       if( rc==SQLITE_DENY ){
93989         goto update_cleanup;
93990       }else if( rc==SQLITE_IGNORE ){
93991         aXRef[j] = -1;
93992       }
93993     }
93994 #endif
93995   }
93996
93997   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
93998
93999   /* Allocate memory for the array aRegIdx[].  There is one entry in the
94000   ** array for each index associated with table being updated.  Fill in
94001   ** the value with a register number for indices that are to be used
94002   ** and with zero for unused indices.
94003   */
94004   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
94005   if( nIdx>0 ){
94006     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
94007     if( aRegIdx==0 ) goto update_cleanup;
94008   }
94009   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
94010     int reg;
94011     if( chngRowid ){
94012       reg = ++pParse->nMem;
94013     }else{
94014       reg = 0;
94015       for(i=0; i<pIdx->nColumn; i++){
94016         if( aXRef[pIdx->aiColumn[i]]>=0 ){
94017           reg = ++pParse->nMem;
94018           break;
94019         }
94020       }
94021     }
94022     aRegIdx[j] = reg;
94023   }
94024
94025   /* Begin generating code. */
94026   v = sqlite3GetVdbe(pParse);
94027   if( v==0 ) goto update_cleanup;
94028   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
94029   sqlite3BeginWriteOperation(pParse, 1, iDb);
94030
94031 #ifndef SQLITE_OMIT_VIRTUALTABLE
94032   /* Virtual tables must be handled separately */
94033   if( IsVirtual(pTab) ){
94034     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
94035                        pWhere);
94036     pWhere = 0;
94037     pTabList = 0;
94038     goto update_cleanup;
94039   }
94040 #endif
94041
94042   /* Allocate required registers. */
94043   regOldRowid = regNewRowid = ++pParse->nMem;
94044   if( pTrigger || hasFK ){
94045     regOld = pParse->nMem + 1;
94046     pParse->nMem += pTab->nCol;
94047   }
94048   if( chngRowid || pTrigger || hasFK ){
94049     regNewRowid = ++pParse->nMem;
94050   }
94051   regNew = pParse->nMem + 1;
94052   pParse->nMem += pTab->nCol;
94053   regRec = ++pParse->nMem;
94054
94055   /* Start the view context. */
94056   if( isView ){
94057     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
94058   }
94059
94060   /* If we are trying to update a view, realize that view into
94061   ** a ephemeral table.
94062   */
94063 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
94064   if( isView ){
94065     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
94066   }
94067 #endif
94068
94069   /* Resolve the column names in all the expressions in the
94070   ** WHERE clause.
94071   */
94072   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
94073     goto update_cleanup;
94074   }
94075
94076   /* Begin the database scan
94077   */
94078   sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
94079   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0, WHERE_ONEPASS_DESIRED);
94080   if( pWInfo==0 ) goto update_cleanup;
94081   okOnePass = pWInfo->okOnePass;
94082
94083   /* Remember the rowid of every item to be updated.
94084   */
94085   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
94086   if( !okOnePass ){
94087     regRowSet = ++pParse->nMem;
94088     sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
94089   }
94090
94091   /* End the database scan loop.
94092   */
94093   sqlite3WhereEnd(pWInfo);
94094
94095   /* Initialize the count of updated rows
94096   */
94097   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
94098     regRowCount = ++pParse->nMem;
94099     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
94100   }
94101
94102   if( !isView ){
94103     /* 
94104     ** Open every index that needs updating.  Note that if any
94105     ** index could potentially invoke a REPLACE conflict resolution 
94106     ** action, then we need to open all indices because we might need
94107     ** to be deleting some records.
94108     */
94109     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
94110     if( onError==OE_Replace ){
94111       openAll = 1;
94112     }else{
94113       openAll = 0;
94114       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
94115         if( pIdx->onError==OE_Replace ){
94116           openAll = 1;
94117           break;
94118         }
94119       }
94120     }
94121     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
94122       if( openAll || aRegIdx[i]>0 ){
94123         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
94124         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
94125                        (char*)pKey, P4_KEYINFO_HANDOFF);
94126         assert( pParse->nTab>iCur+i+1 );
94127       }
94128     }
94129   }
94130
94131   /* Top of the update loop */
94132   if( okOnePass ){
94133     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
94134     addr = sqlite3VdbeAddOp0(v, OP_Goto);
94135     sqlite3VdbeJumpHere(v, a1);
94136   }else{
94137     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
94138   }
94139
94140   /* Make cursor iCur point to the record that is being updated. If
94141   ** this record does not exist for some reason (deleted by a trigger,
94142   ** for example, then jump to the next iteration of the RowSet loop.  */
94143   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
94144
94145   /* If the record number will change, set register regNewRowid to
94146   ** contain the new value. If the record number is not being modified,
94147   ** then regNewRowid is the same register as regOldRowid, which is
94148   ** already populated.  */
94149   assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
94150   if( chngRowid ){
94151     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
94152     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
94153   }
94154
94155   /* If there are triggers on this table, populate an array of registers 
94156   ** with the required old.* column data.  */
94157   if( hasFK || pTrigger ){
94158     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
94159     oldmask |= sqlite3TriggerColmask(pParse, 
94160         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
94161     );
94162     for(i=0; i<pTab->nCol; i++){
94163       if( aXRef[i]<0 || oldmask==0xffffffff || (oldmask & (1<<i)) ){
94164         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
94165       }else{
94166         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
94167       }
94168     }
94169     if( chngRowid==0 ){
94170       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
94171     }
94172   }
94173
94174   /* Populate the array of registers beginning at regNew with the new
94175   ** row data. This array is used to check constaints, create the new
94176   ** table and index records, and as the values for any new.* references
94177   ** made by triggers.
94178   **
94179   ** If there are one or more BEFORE triggers, then do not populate the
94180   ** registers associated with columns that are (a) not modified by
94181   ** this UPDATE statement and (b) not accessed by new.* references. The
94182   ** values for registers not modified by the UPDATE must be reloaded from 
94183   ** the database after the BEFORE triggers are fired anyway (as the trigger 
94184   ** may have modified them). So not loading those that are not going to
94185   ** be used eliminates some redundant opcodes.
94186   */
94187   newmask = sqlite3TriggerColmask(
94188       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
94189   );
94190   for(i=0; i<pTab->nCol; i++){
94191     if( i==pTab->iPKey ){
94192       sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
94193     }else{
94194       j = aXRef[i];
94195       if( j>=0 ){
94196         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
94197       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
94198         /* This branch loads the value of a column that will not be changed 
94199         ** into a register. This is done if there are no BEFORE triggers, or
94200         ** if there are one or more BEFORE triggers that use this value via
94201         ** a new.* reference in a trigger program.
94202         */
94203         testcase( i==31 );
94204         testcase( i==32 );
94205         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
94206         sqlite3ColumnDefault(v, pTab, i, regNew+i);
94207       }
94208     }
94209   }
94210
94211   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
94212   ** verified. One could argue that this is wrong.
94213   */
94214   if( tmask&TRIGGER_BEFORE ){
94215     sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
94216     sqlite3TableAffinityStr(v, pTab);
94217     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
94218         TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
94219
94220     /* The row-trigger may have deleted the row being updated. In this
94221     ** case, jump to the next row. No updates or AFTER triggers are 
94222     ** required. This behaviour - what happens when the row being updated
94223     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
94224     ** documentation.
94225     */
94226     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
94227
94228     /* If it did not delete it, the row-trigger may still have modified 
94229     ** some of the columns of the row being updated. Load the values for 
94230     ** all columns not modified by the update statement into their 
94231     ** registers in case this has happened.
94232     */
94233     for(i=0; i<pTab->nCol; i++){
94234       if( aXRef[i]<0 && i!=pTab->iPKey ){
94235         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
94236         sqlite3ColumnDefault(v, pTab, i, regNew+i);
94237       }
94238     }
94239   }
94240
94241   if( !isView ){
94242     int j1;                       /* Address of jump instruction */
94243
94244     /* Do constraint checks. */
94245     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
94246         aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
94247
94248     /* Do FK constraint checks. */
94249     if( hasFK ){
94250       sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
94251     }
94252
94253     /* Delete the index entries associated with the current record.  */
94254     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
94255     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
94256   
94257     /* If changing the record number, delete the old record.  */
94258     if( hasFK || chngRowid ){
94259       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
94260     }
94261     sqlite3VdbeJumpHere(v, j1);
94262
94263     if( hasFK ){
94264       sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
94265     }
94266   
94267     /* Insert the new index entries and the new record. */
94268     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
94269
94270     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
94271     ** handle rows (possibly in other tables) that refer via a foreign key
94272     ** to the row just updated. */ 
94273     if( hasFK ){
94274       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
94275     }
94276   }
94277
94278   /* Increment the row counter 
94279   */
94280   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
94281     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
94282   }
94283
94284   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
94285       TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
94286
94287   /* Repeat the above with the next record to be updated, until
94288   ** all record selected by the WHERE clause have been updated.
94289   */
94290   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
94291   sqlite3VdbeJumpHere(v, addr);
94292
94293   /* Close all tables */
94294   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
94295     if( openAll || aRegIdx[i]>0 ){
94296       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
94297     }
94298   }
94299   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
94300
94301   /* Update the sqlite_sequence table by storing the content of the
94302   ** maximum rowid counter values recorded while inserting into
94303   ** autoincrement tables.
94304   */
94305   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
94306     sqlite3AutoincrementEnd(pParse);
94307   }
94308
94309   /*
94310   ** Return the number of rows that were changed. If this routine is 
94311   ** generating code because of a call to sqlite3NestedParse(), do not
94312   ** invoke the callback function.
94313   */
94314   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
94315     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
94316     sqlite3VdbeSetNumCols(v, 1);
94317     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
94318   }
94319
94320 update_cleanup:
94321   sqlite3AuthContextPop(&sContext);
94322   sqlite3DbFree(db, aRegIdx);
94323   sqlite3DbFree(db, aXRef);
94324   sqlite3SrcListDelete(db, pTabList);
94325   sqlite3ExprListDelete(db, pChanges);
94326   sqlite3ExprDelete(db, pWhere);
94327   return;
94328 }
94329 /* Make sure "isView" and other macros defined above are undefined. Otherwise
94330 ** thely may interfere with compilation of other functions in this file
94331 ** (or in another file, if this file becomes part of the amalgamation).  */
94332 #ifdef isView
94333  #undef isView
94334 #endif
94335 #ifdef pTrigger
94336  #undef pTrigger
94337 #endif
94338
94339 #ifndef SQLITE_OMIT_VIRTUALTABLE
94340 /*
94341 ** Generate code for an UPDATE of a virtual table.
94342 **
94343 ** The strategy is that we create an ephemerial table that contains
94344 ** for each row to be changed:
94345 **
94346 **   (A)  The original rowid of that row.
94347 **   (B)  The revised rowid for the row. (note1)
94348 **   (C)  The content of every column in the row.
94349 **
94350 ** Then we loop over this ephemeral table and for each row in
94351 ** the ephermeral table call VUpdate.
94352 **
94353 ** When finished, drop the ephemeral table.
94354 **
94355 ** (note1) Actually, if we know in advance that (A) is always the same
94356 ** as (B) we only store (A), then duplicate (A) when pulling
94357 ** it out of the ephemeral table before calling VUpdate.
94358 */
94359 static void updateVirtualTable(
94360   Parse *pParse,       /* The parsing context */
94361   SrcList *pSrc,       /* The virtual table to be modified */
94362   Table *pTab,         /* The virtual table */
94363   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
94364   Expr *pRowid,        /* Expression used to recompute the rowid */
94365   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
94366   Expr *pWhere         /* WHERE clause of the UPDATE statement */
94367 ){
94368   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
94369   ExprList *pEList = 0;     /* The result set of the SELECT statement */
94370   Select *pSelect = 0;      /* The SELECT statement */
94371   Expr *pExpr;              /* Temporary expression */
94372   int ephemTab;             /* Table holding the result of the SELECT */
94373   int i;                    /* Loop counter */
94374   int addr;                 /* Address of top of loop */
94375   int iReg;                 /* First register in set passed to OP_VUpdate */
94376   sqlite3 *db = pParse->db; /* Database connection */
94377   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
94378   SelectDest dest;
94379
94380   /* Construct the SELECT statement that will find the new values for
94381   ** all updated rows. 
94382   */
94383   pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
94384   if( pRowid ){
94385     pEList = sqlite3ExprListAppend(pParse, pEList,
94386                                    sqlite3ExprDup(db, pRowid, 0));
94387   }
94388   assert( pTab->iPKey<0 );
94389   for(i=0; i<pTab->nCol; i++){
94390     if( aXRef[i]>=0 ){
94391       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
94392     }else{
94393       pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
94394     }
94395     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
94396   }
94397   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
94398   
94399   /* Create the ephemeral table into which the update results will
94400   ** be stored.
94401   */
94402   assert( v );
94403   ephemTab = pParse->nTab++;
94404   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
94405   sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
94406
94407   /* fill the ephemeral table 
94408   */
94409   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
94410   sqlite3Select(pParse, pSelect, &dest);
94411
94412   /* Generate code to scan the ephemeral table and call VUpdate. */
94413   iReg = ++pParse->nMem;
94414   pParse->nMem += pTab->nCol+1;
94415   addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
94416   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
94417   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
94418   for(i=0; i<pTab->nCol; i++){
94419     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
94420   }
94421   sqlite3VtabMakeWritable(pParse, pTab);
94422   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
94423   sqlite3MayAbort(pParse);
94424   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
94425   sqlite3VdbeJumpHere(v, addr);
94426   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
94427
94428   /* Cleanup */
94429   sqlite3SelectDelete(db, pSelect);  
94430 }
94431 #endif /* SQLITE_OMIT_VIRTUALTABLE */
94432
94433 /************** End of update.c **********************************************/
94434 /************** Begin file vacuum.c ******************************************/
94435 /*
94436 ** 2003 April 6
94437 **
94438 ** The author disclaims copyright to this source code.  In place of
94439 ** a legal notice, here is a blessing:
94440 **
94441 **    May you do good and not evil.
94442 **    May you find forgiveness for yourself and forgive others.
94443 **    May you share freely, never taking more than you give.
94444 **
94445 *************************************************************************
94446 ** This file contains code used to implement the VACUUM command.
94447 **
94448 ** Most of the code in this file may be omitted by defining the
94449 ** SQLITE_OMIT_VACUUM macro.
94450 */
94451
94452 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
94453 /*
94454 ** Finalize a prepared statement.  If there was an error, store the
94455 ** text of the error message in *pzErrMsg.  Return the result code.
94456 */
94457 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
94458   int rc;
94459   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
94460   if( rc ){
94461     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
94462   }
94463   return rc;
94464 }
94465
94466 /*
94467 ** Execute zSql on database db. Return an error code.
94468 */
94469 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
94470   sqlite3_stmt *pStmt;
94471   VVA_ONLY( int rc; )
94472   if( !zSql ){
94473     return SQLITE_NOMEM;
94474   }
94475   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
94476     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
94477     return sqlite3_errcode(db);
94478   }
94479   VVA_ONLY( rc = ) sqlite3_step(pStmt);
94480   assert( rc!=SQLITE_ROW );
94481   return vacuumFinalize(db, pStmt, pzErrMsg);
94482 }
94483
94484 /*
94485 ** Execute zSql on database db. The statement returns exactly
94486 ** one column. Execute this as SQL on the same database.
94487 */
94488 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
94489   sqlite3_stmt *pStmt;
94490   int rc;
94491
94492   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
94493   if( rc!=SQLITE_OK ) return rc;
94494
94495   while( SQLITE_ROW==sqlite3_step(pStmt) ){
94496     rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
94497     if( rc!=SQLITE_OK ){
94498       vacuumFinalize(db, pStmt, pzErrMsg);
94499       return rc;
94500     }
94501   }
94502
94503   return vacuumFinalize(db, pStmt, pzErrMsg);
94504 }
94505
94506 /*
94507 ** The non-standard VACUUM command is used to clean up the database,
94508 ** collapse free space, etc.  It is modelled after the VACUUM command
94509 ** in PostgreSQL.
94510 **
94511 ** In version 1.0.x of SQLite, the VACUUM command would call
94512 ** gdbm_reorganize() on all the database tables.  But beginning
94513 ** with 2.0.0, SQLite no longer uses GDBM so this command has
94514 ** become a no-op.
94515 */
94516 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
94517   Vdbe *v = sqlite3GetVdbe(pParse);
94518   if( v ){
94519     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
94520   }
94521   return;
94522 }
94523
94524 /*
94525 ** This routine implements the OP_Vacuum opcode of the VDBE.
94526 */
94527 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
94528   int rc = SQLITE_OK;     /* Return code from service routines */
94529   Btree *pMain;           /* The database being vacuumed */
94530   Btree *pTemp;           /* The temporary database we vacuum into */
94531   char *zSql = 0;         /* SQL statements */
94532   int saved_flags;        /* Saved value of the db->flags */
94533   int saved_nChange;      /* Saved value of db->nChange */
94534   int saved_nTotalChange; /* Saved value of db->nTotalChange */
94535   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
94536   Db *pDb = 0;            /* Database to detach at end of vacuum */
94537   int isMemDb;            /* True if vacuuming a :memory: database */
94538   int nRes;               /* Bytes of reserved space at the end of each page */
94539   int nDb;                /* Number of attached databases */
94540
94541   if( !db->autoCommit ){
94542     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
94543     return SQLITE_ERROR;
94544   }
94545   if( db->activeVdbeCnt>1 ){
94546     sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
94547     return SQLITE_ERROR;
94548   }
94549
94550   /* Save the current value of the database flags so that it can be 
94551   ** restored before returning. Then set the writable-schema flag, and
94552   ** disable CHECK and foreign key constraints.  */
94553   saved_flags = db->flags;
94554   saved_nChange = db->nChange;
94555   saved_nTotalChange = db->nTotalChange;
94556   saved_xTrace = db->xTrace;
94557   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
94558   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
94559   db->xTrace = 0;
94560
94561   pMain = db->aDb[0].pBt;
94562   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
94563
94564   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
94565   ** can be set to 'off' for this file, as it is not recovered if a crash
94566   ** occurs anyway. The integrity of the database is maintained by a
94567   ** (possibly synchronous) transaction opened on the main database before
94568   ** sqlite3BtreeCopyFile() is called.
94569   **
94570   ** An optimisation would be to use a non-journaled pager.
94571   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
94572   ** that actually made the VACUUM run slower.  Very little journalling
94573   ** actually occurs when doing a vacuum since the vacuum_db is initially
94574   ** empty.  Only the journal header is written.  Apparently it takes more
94575   ** time to parse and run the PRAGMA to turn journalling off than it does
94576   ** to write the journal header file.
94577   */
94578   nDb = db->nDb;
94579   if( sqlite3TempInMemory(db) ){
94580     zSql = "ATTACH ':memory:' AS vacuum_db;";
94581   }else{
94582     zSql = "ATTACH '' AS vacuum_db;";
94583   }
94584   rc = execSql(db, pzErrMsg, zSql);
94585   if( db->nDb>nDb ){
94586     pDb = &db->aDb[db->nDb-1];
94587     assert( strcmp(pDb->zName,"vacuum_db")==0 );
94588   }
94589   if( rc!=SQLITE_OK ) goto end_of_vacuum;
94590   pTemp = db->aDb[db->nDb-1].pBt;
94591
94592   /* The call to execSql() to attach the temp database has left the file
94593   ** locked (as there was more than one active statement when the transaction
94594   ** to read the schema was concluded. Unlock it here so that this doesn't
94595   ** cause problems for the call to BtreeSetPageSize() below.  */
94596   sqlite3BtreeCommit(pTemp);
94597
94598   nRes = sqlite3BtreeGetReserve(pMain);
94599
94600   /* A VACUUM cannot change the pagesize of an encrypted database. */
94601 #ifdef SQLITE_HAS_CODEC
94602   if( db->nextPagesize ){
94603     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
94604     int nKey;
94605     char *zKey;
94606     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
94607     if( nKey ) db->nextPagesize = 0;
94608   }
94609 #endif
94610
94611   /* Do not attempt to change the page size for a WAL database */
94612   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
94613                                                ==PAGER_JOURNALMODE_WAL ){
94614     db->nextPagesize = 0;
94615   }
94616
94617   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
94618    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
94619    || NEVER(db->mallocFailed)
94620   ){
94621     rc = SQLITE_NOMEM;
94622     goto end_of_vacuum;
94623   }
94624   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
94625   if( rc!=SQLITE_OK ){
94626     goto end_of_vacuum;
94627   }
94628
94629 #ifndef SQLITE_OMIT_AUTOVACUUM
94630   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
94631                                            sqlite3BtreeGetAutoVacuum(pMain));
94632 #endif
94633
94634   /* Begin a transaction */
94635   rc = execSql(db, pzErrMsg, "BEGIN EXCLUSIVE;");
94636   if( rc!=SQLITE_OK ) goto end_of_vacuum;
94637
94638   /* Query the schema of the main database. Create a mirror schema
94639   ** in the temporary database.
94640   */
94641   rc = execExecSql(db, pzErrMsg,
94642       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
94643       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
94644       "   AND rootpage>0"
94645   );
94646   if( rc!=SQLITE_OK ) goto end_of_vacuum;
94647   rc = execExecSql(db, pzErrMsg,
94648       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
94649       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
94650   if( rc!=SQLITE_OK ) goto end_of_vacuum;
94651   rc = execExecSql(db, pzErrMsg,
94652       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
94653       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
94654   if( rc!=SQLITE_OK ) goto end_of_vacuum;
94655
94656   /* Loop through the tables in the main database. For each, do
94657   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
94658   ** the contents to the temporary database.
94659   */
94660   rc = execExecSql(db, pzErrMsg,
94661       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
94662       "|| ' SELECT * FROM main.' || quote(name) || ';'"
94663       "FROM main.sqlite_master "
94664       "WHERE type = 'table' AND name!='sqlite_sequence' "
94665       "  AND rootpage>0"
94666   );
94667   if( rc!=SQLITE_OK ) goto end_of_vacuum;
94668
94669   /* Copy over the sequence table
94670   */
94671   rc = execExecSql(db, pzErrMsg,
94672       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
94673       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
94674   );
94675   if( rc!=SQLITE_OK ) goto end_of_vacuum;
94676   rc = execExecSql(db, pzErrMsg,
94677       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
94678       "|| ' SELECT * FROM main.' || quote(name) || ';' "
94679       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
94680   );
94681   if( rc!=SQLITE_OK ) goto end_of_vacuum;
94682
94683
94684   /* Copy the triggers, views, and virtual tables from the main database
94685   ** over to the temporary database.  None of these objects has any
94686   ** associated storage, so all we have to do is copy their entries
94687   ** from the SQLITE_MASTER table.
94688   */
94689   rc = execSql(db, pzErrMsg,
94690       "INSERT INTO vacuum_db.sqlite_master "
94691       "  SELECT type, name, tbl_name, rootpage, sql"
94692       "    FROM main.sqlite_master"
94693       "   WHERE type='view' OR type='trigger'"
94694       "      OR (type='table' AND rootpage=0)"
94695   );
94696   if( rc ) goto end_of_vacuum;
94697
94698   /* At this point, unless the main db was completely empty, there is now a
94699   ** transaction open on the vacuum database, but not on the main database.
94700   ** Open a btree level transaction on the main database. This allows a
94701   ** call to sqlite3BtreeCopyFile(). The main database btree level
94702   ** transaction is then committed, so the SQL level never knows it was
94703   ** opened for writing. This way, the SQL transaction used to create the
94704   ** temporary database never needs to be committed.
94705   */
94706   {
94707     u32 meta;
94708     int i;
94709
94710     /* This array determines which meta meta values are preserved in the
94711     ** vacuum.  Even entries are the meta value number and odd entries
94712     ** are an increment to apply to the meta value after the vacuum.
94713     ** The increment is used to increase the schema cookie so that other
94714     ** connections to the same database will know to reread the schema.
94715     */
94716     static const unsigned char aCopy[] = {
94717        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
94718        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
94719        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
94720        BTREE_USER_VERSION,       0,  /* Preserve the user version */
94721     };
94722
94723     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
94724     assert( 1==sqlite3BtreeIsInTrans(pMain) );
94725
94726     /* Copy Btree meta values */
94727     for(i=0; i<ArraySize(aCopy); i+=2){
94728       /* GetMeta() and UpdateMeta() cannot fail in this context because
94729       ** we already have page 1 loaded into cache and marked dirty. */
94730       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
94731       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
94732       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
94733     }
94734
94735     rc = sqlite3BtreeCopyFile(pMain, pTemp);
94736     if( rc!=SQLITE_OK ) goto end_of_vacuum;
94737     rc = sqlite3BtreeCommit(pTemp);
94738     if( rc!=SQLITE_OK ) goto end_of_vacuum;
94739 #ifndef SQLITE_OMIT_AUTOVACUUM
94740     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
94741 #endif
94742   }
94743
94744   assert( rc==SQLITE_OK );
94745   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
94746
94747 end_of_vacuum:
94748   /* Restore the original value of db->flags */
94749   db->flags = saved_flags;
94750   db->nChange = saved_nChange;
94751   db->nTotalChange = saved_nTotalChange;
94752   db->xTrace = saved_xTrace;
94753   sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
94754
94755   /* Currently there is an SQL level transaction open on the vacuum
94756   ** database. No locks are held on any other files (since the main file
94757   ** was committed at the btree level). So it safe to end the transaction
94758   ** by manually setting the autoCommit flag to true and detaching the
94759   ** vacuum database. The vacuum_db journal file is deleted when the pager
94760   ** is closed by the DETACH.
94761   */
94762   db->autoCommit = 1;
94763
94764   if( pDb ){
94765     sqlite3BtreeClose(pDb->pBt);
94766     pDb->pBt = 0;
94767     pDb->pSchema = 0;
94768   }
94769
94770   sqlite3ResetInternalSchema(db, 0);
94771
94772   return rc;
94773 }
94774 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
94775
94776 /************** End of vacuum.c **********************************************/
94777 /************** Begin file vtab.c ********************************************/
94778 /*
94779 ** 2006 June 10
94780 **
94781 ** The author disclaims copyright to this source code.  In place of
94782 ** a legal notice, here is a blessing:
94783 **
94784 **    May you do good and not evil.
94785 **    May you find forgiveness for yourself and forgive others.
94786 **    May you share freely, never taking more than you give.
94787 **
94788 *************************************************************************
94789 ** This file contains code used to help implement virtual tables.
94790 */
94791 #ifndef SQLITE_OMIT_VIRTUALTABLE
94792
94793 /*
94794 ** The actual function that does the work of creating a new module.
94795 ** This function implements the sqlite3_create_module() and
94796 ** sqlite3_create_module_v2() interfaces.
94797 */
94798 static int createModule(
94799   sqlite3 *db,                    /* Database in which module is registered */
94800   const char *zName,              /* Name assigned to this module */
94801   const sqlite3_module *pModule,  /* The definition of the module */
94802   void *pAux,                     /* Context pointer for xCreate/xConnect */
94803   void (*xDestroy)(void *)        /* Module destructor function */
94804 ){
94805   int rc, nName;
94806   Module *pMod;
94807
94808   sqlite3_mutex_enter(db->mutex);
94809   nName = sqlite3Strlen30(zName);
94810   pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
94811   if( pMod ){
94812     Module *pDel;
94813     char *zCopy = (char *)(&pMod[1]);
94814     memcpy(zCopy, zName, nName+1);
94815     pMod->zName = zCopy;
94816     pMod->pModule = pModule;
94817     pMod->pAux = pAux;
94818     pMod->xDestroy = xDestroy;
94819     pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
94820     if( pDel && pDel->xDestroy ){
94821       pDel->xDestroy(pDel->pAux);
94822     }
94823     sqlite3DbFree(db, pDel);
94824     if( pDel==pMod ){
94825       db->mallocFailed = 1;
94826     }
94827     sqlite3ResetInternalSchema(db, 0);
94828   }else if( xDestroy ){
94829     xDestroy(pAux);
94830   }
94831   rc = sqlite3ApiExit(db, SQLITE_OK);
94832   sqlite3_mutex_leave(db->mutex);
94833   return rc;
94834 }
94835
94836
94837 /*
94838 ** External API function used to create a new virtual-table module.
94839 */
94840 SQLITE_API int sqlite3_create_module(
94841   sqlite3 *db,                    /* Database in which module is registered */
94842   const char *zName,              /* Name assigned to this module */
94843   const sqlite3_module *pModule,  /* The definition of the module */
94844   void *pAux                      /* Context pointer for xCreate/xConnect */
94845 ){
94846   return createModule(db, zName, pModule, pAux, 0);
94847 }
94848
94849 /*
94850 ** External API function used to create a new virtual-table module.
94851 */
94852 SQLITE_API int sqlite3_create_module_v2(
94853   sqlite3 *db,                    /* Database in which module is registered */
94854   const char *zName,              /* Name assigned to this module */
94855   const sqlite3_module *pModule,  /* The definition of the module */
94856   void *pAux,                     /* Context pointer for xCreate/xConnect */
94857   void (*xDestroy)(void *)        /* Module destructor function */
94858 ){
94859   return createModule(db, zName, pModule, pAux, xDestroy);
94860 }
94861
94862 /*
94863 ** Lock the virtual table so that it cannot be disconnected.
94864 ** Locks nest.  Every lock should have a corresponding unlock.
94865 ** If an unlock is omitted, resources leaks will occur.  
94866 **
94867 ** If a disconnect is attempted while a virtual table is locked,
94868 ** the disconnect is deferred until all locks have been removed.
94869 */
94870 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
94871   pVTab->nRef++;
94872 }
94873
94874
94875 /*
94876 ** pTab is a pointer to a Table structure representing a virtual-table.
94877 ** Return a pointer to the VTable object used by connection db to access 
94878 ** this virtual-table, if one has been created, or NULL otherwise.
94879 */
94880 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
94881   VTable *pVtab;
94882   assert( IsVirtual(pTab) );
94883   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
94884   return pVtab;
94885 }
94886
94887 /*
94888 ** Decrement the ref-count on a virtual table object. When the ref-count
94889 ** reaches zero, call the xDisconnect() method to delete the object.
94890 */
94891 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
94892   sqlite3 *db = pVTab->db;
94893
94894   assert( db );
94895   assert( pVTab->nRef>0 );
94896   assert( sqlite3SafetyCheckOk(db) );
94897
94898   pVTab->nRef--;
94899   if( pVTab->nRef==0 ){
94900     sqlite3_vtab *p = pVTab->pVtab;
94901     if( p ){
94902       p->pModule->xDisconnect(p);
94903     }
94904     sqlite3DbFree(db, pVTab);
94905   }
94906 }
94907
94908 /*
94909 ** Table p is a virtual table. This function moves all elements in the
94910 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
94911 ** database connections to be disconnected at the next opportunity. 
94912 ** Except, if argument db is not NULL, then the entry associated with
94913 ** connection db is left in the p->pVTable list.
94914 */
94915 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
94916   VTable *pRet = 0;
94917   VTable *pVTable = p->pVTable;
94918   p->pVTable = 0;
94919
94920   /* Assert that the mutex (if any) associated with the BtShared database 
94921   ** that contains table p is held by the caller. See header comments 
94922   ** above function sqlite3VtabUnlockList() for an explanation of why
94923   ** this makes it safe to access the sqlite3.pDisconnect list of any
94924   ** database connection that may have an entry in the p->pVTable list.  */
94925   assert( db==0 ||
94926     sqlite3BtreeHoldsMutex(db->aDb[sqlite3SchemaToIndex(db, p->pSchema)].pBt) 
94927   );
94928
94929   while( pVTable ){
94930     sqlite3 *db2 = pVTable->db;
94931     VTable *pNext = pVTable->pNext;
94932     assert( db2 );
94933     if( db2==db ){
94934       pRet = pVTable;
94935       p->pVTable = pRet;
94936       pRet->pNext = 0;
94937     }else{
94938       pVTable->pNext = db2->pDisconnect;
94939       db2->pDisconnect = pVTable;
94940     }
94941     pVTable = pNext;
94942   }
94943
94944   assert( !db || pRet );
94945   return pRet;
94946 }
94947
94948
94949 /*
94950 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
94951 **
94952 ** This function may only be called when the mutexes associated with all
94953 ** shared b-tree databases opened using connection db are held by the 
94954 ** caller. This is done to protect the sqlite3.pDisconnect list. The
94955 ** sqlite3.pDisconnect list is accessed only as follows:
94956 **
94957 **   1) By this function. In this case, all BtShared mutexes and the mutex
94958 **      associated with the database handle itself must be held.
94959 **
94960 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
94961 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
94962 **      associated with the database the virtual table is stored in is held
94963 **      or, if the virtual table is stored in a non-sharable database, then
94964 **      the database handle mutex is held.
94965 **
94966 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously 
94967 ** by multiple threads. It is thread-safe.
94968 */
94969 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
94970   VTable *p = db->pDisconnect;
94971   db->pDisconnect = 0;
94972
94973   assert( sqlite3BtreeHoldsAllMutexes(db) );
94974   assert( sqlite3_mutex_held(db->mutex) );
94975
94976   if( p ){
94977     sqlite3ExpirePreparedStatements(db);
94978     do {
94979       VTable *pNext = p->pNext;
94980       sqlite3VtabUnlock(p);
94981       p = pNext;
94982     }while( p );
94983   }
94984 }
94985
94986 /*
94987 ** Clear any and all virtual-table information from the Table record.
94988 ** This routine is called, for example, just before deleting the Table
94989 ** record.
94990 **
94991 ** Since it is a virtual-table, the Table structure contains a pointer
94992 ** to the head of a linked list of VTable structures. Each VTable 
94993 ** structure is associated with a single sqlite3* user of the schema.
94994 ** The reference count of the VTable structure associated with database 
94995 ** connection db is decremented immediately (which may lead to the 
94996 ** structure being xDisconnected and free). Any other VTable structures
94997 ** in the list are moved to the sqlite3.pDisconnect list of the associated 
94998 ** database connection.
94999 */
95000 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
95001   if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
95002   if( p->azModuleArg ){
95003     int i;
95004     for(i=0; i<p->nModuleArg; i++){
95005       sqlite3DbFree(db, p->azModuleArg[i]);
95006     }
95007     sqlite3DbFree(db, p->azModuleArg);
95008   }
95009 }
95010
95011 /*
95012 ** Add a new module argument to pTable->azModuleArg[].
95013 ** The string is not copied - the pointer is stored.  The
95014 ** string will be freed automatically when the table is
95015 ** deleted.
95016 */
95017 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
95018   int i = pTable->nModuleArg++;
95019   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
95020   char **azModuleArg;
95021   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
95022   if( azModuleArg==0 ){
95023     int j;
95024     for(j=0; j<i; j++){
95025       sqlite3DbFree(db, pTable->azModuleArg[j]);
95026     }
95027     sqlite3DbFree(db, zArg);
95028     sqlite3DbFree(db, pTable->azModuleArg);
95029     pTable->nModuleArg = 0;
95030   }else{
95031     azModuleArg[i] = zArg;
95032     azModuleArg[i+1] = 0;
95033   }
95034   pTable->azModuleArg = azModuleArg;
95035 }
95036
95037 /*
95038 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
95039 ** statement.  The module name has been parsed, but the optional list
95040 ** of parameters that follow the module name are still pending.
95041 */
95042 SQLITE_PRIVATE void sqlite3VtabBeginParse(
95043   Parse *pParse,        /* Parsing context */
95044   Token *pName1,        /* Name of new table, or database name */
95045   Token *pName2,        /* Name of new table or NULL */
95046   Token *pModuleName    /* Name of the module for the virtual table */
95047 ){
95048   int iDb;              /* The database the table is being created in */
95049   Table *pTable;        /* The new virtual table */
95050   sqlite3 *db;          /* Database connection */
95051
95052   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
95053   pTable = pParse->pNewTable;
95054   if( pTable==0 ) return;
95055   assert( 0==pTable->pIndex );
95056
95057   db = pParse->db;
95058   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
95059   assert( iDb>=0 );
95060
95061   pTable->tabFlags |= TF_Virtual;
95062   pTable->nModuleArg = 0;
95063   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
95064   addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
95065   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
95066   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
95067
95068 #ifndef SQLITE_OMIT_AUTHORIZATION
95069   /* Creating a virtual table invokes the authorization callback twice.
95070   ** The first invocation, to obtain permission to INSERT a row into the
95071   ** sqlite_master table, has already been made by sqlite3StartTable().
95072   ** The second call, to obtain permission to create the table, is made now.
95073   */
95074   if( pTable->azModuleArg ){
95075     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
95076             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
95077   }
95078 #endif
95079 }
95080
95081 /*
95082 ** This routine takes the module argument that has been accumulating
95083 ** in pParse->zArg[] and appends it to the list of arguments on the
95084 ** virtual table currently under construction in pParse->pTable.
95085 */
95086 static void addArgumentToVtab(Parse *pParse){
95087   if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
95088     const char *z = (const char*)pParse->sArg.z;
95089     int n = pParse->sArg.n;
95090     sqlite3 *db = pParse->db;
95091     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
95092   }
95093 }
95094
95095 /*
95096 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
95097 ** has been completely parsed.
95098 */
95099 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
95100   Table *pTab = pParse->pNewTable;  /* The table being constructed */
95101   sqlite3 *db = pParse->db;         /* The database connection */
95102
95103   if( pTab==0 ) return;
95104   addArgumentToVtab(pParse);
95105   pParse->sArg.z = 0;
95106   if( pTab->nModuleArg<1 ) return;
95107   
95108   /* If the CREATE VIRTUAL TABLE statement is being entered for the
95109   ** first time (in other words if the virtual table is actually being
95110   ** created now instead of just being read out of sqlite_master) then
95111   ** do additional initialization work and store the statement text
95112   ** in the sqlite_master table.
95113   */
95114   if( !db->init.busy ){
95115     char *zStmt;
95116     char *zWhere;
95117     int iDb;
95118     Vdbe *v;
95119
95120     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
95121     if( pEnd ){
95122       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
95123     }
95124     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
95125
95126     /* A slot for the record has already been allocated in the 
95127     ** SQLITE_MASTER table.  We just need to update that slot with all
95128     ** the information we've collected.  
95129     **
95130     ** The VM register number pParse->regRowid holds the rowid of an
95131     ** entry in the sqlite_master table tht was created for this vtab
95132     ** by sqlite3StartTable().
95133     */
95134     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
95135     sqlite3NestedParse(pParse,
95136       "UPDATE %Q.%s "
95137          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
95138        "WHERE rowid=#%d",
95139       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
95140       pTab->zName,
95141       pTab->zName,
95142       zStmt,
95143       pParse->regRowid
95144     );
95145     sqlite3DbFree(db, zStmt);
95146     v = sqlite3GetVdbe(pParse);
95147     sqlite3ChangeCookie(pParse, iDb);
95148
95149     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
95150     zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
95151     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
95152     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, 
95153                          pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
95154   }
95155
95156   /* If we are rereading the sqlite_master table create the in-memory
95157   ** record of the table. The xConnect() method is not called until
95158   ** the first time the virtual table is used in an SQL statement. This
95159   ** allows a schema that contains virtual tables to be loaded before
95160   ** the required virtual table implementations are registered.  */
95161   else {
95162     Table *pOld;
95163     Schema *pSchema = pTab->pSchema;
95164     const char *zName = pTab->zName;
95165     int nName = sqlite3Strlen30(zName);
95166     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
95167     if( pOld ){
95168       db->mallocFailed = 1;
95169       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
95170       return;
95171     }
95172     pParse->pNewTable = 0;
95173   }
95174 }
95175
95176 /*
95177 ** The parser calls this routine when it sees the first token
95178 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
95179 */
95180 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
95181   addArgumentToVtab(pParse);
95182   pParse->sArg.z = 0;
95183   pParse->sArg.n = 0;
95184 }
95185
95186 /*
95187 ** The parser calls this routine for each token after the first token
95188 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
95189 */
95190 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
95191   Token *pArg = &pParse->sArg;
95192   if( pArg->z==0 ){
95193     pArg->z = p->z;
95194     pArg->n = p->n;
95195   }else{
95196     assert(pArg->z < p->z);
95197     pArg->n = (int)(&p->z[p->n] - pArg->z);
95198   }
95199 }
95200
95201 /*
95202 ** Invoke a virtual table constructor (either xCreate or xConnect). The
95203 ** pointer to the function to invoke is passed as the fourth parameter
95204 ** to this procedure.
95205 */
95206 static int vtabCallConstructor(
95207   sqlite3 *db, 
95208   Table *pTab,
95209   Module *pMod,
95210   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
95211   char **pzErr
95212 ){
95213   VTable *pVTable;
95214   int rc;
95215   const char *const*azArg = (const char *const*)pTab->azModuleArg;
95216   int nArg = pTab->nModuleArg;
95217   char *zErr = 0;
95218   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
95219
95220   if( !zModuleName ){
95221     return SQLITE_NOMEM;
95222   }
95223
95224   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
95225   if( !pVTable ){
95226     sqlite3DbFree(db, zModuleName);
95227     return SQLITE_NOMEM;
95228   }
95229   pVTable->db = db;
95230   pVTable->pMod = pMod;
95231
95232   assert( !db->pVTab );
95233   assert( xConstruct );
95234   db->pVTab = pTab;
95235
95236   /* Invoke the virtual table constructor */
95237   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
95238   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
95239
95240   if( SQLITE_OK!=rc ){
95241     if( zErr==0 ){
95242       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
95243     }else {
95244       *pzErr = sqlite3MPrintf(db, "%s", zErr);
95245       sqlite3_free(zErr);
95246     }
95247     sqlite3DbFree(db, pVTable);
95248   }else if( ALWAYS(pVTable->pVtab) ){
95249     /* Justification of ALWAYS():  A correct vtab constructor must allocate
95250     ** the sqlite3_vtab object if successful.  */
95251     pVTable->pVtab->pModule = pMod->pModule;
95252     pVTable->nRef = 1;
95253     if( db->pVTab ){
95254       const char *zFormat = "vtable constructor did not declare schema: %s";
95255       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
95256       sqlite3VtabUnlock(pVTable);
95257       rc = SQLITE_ERROR;
95258     }else{
95259       int iCol;
95260       /* If everything went according to plan, link the new VTable structure
95261       ** into the linked list headed by pTab->pVTable. Then loop through the 
95262       ** columns of the table to see if any of them contain the token "hidden".
95263       ** If so, set the Column.isHidden flag and remove the token from
95264       ** the type string.  */
95265       pVTable->pNext = pTab->pVTable;
95266       pTab->pVTable = pVTable;
95267
95268       for(iCol=0; iCol<pTab->nCol; iCol++){
95269         char *zType = pTab->aCol[iCol].zType;
95270         int nType;
95271         int i = 0;
95272         if( !zType ) continue;
95273         nType = sqlite3Strlen30(zType);
95274         if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
95275           for(i=0; i<nType; i++){
95276             if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
95277              && (zType[i+7]=='\0' || zType[i+7]==' ')
95278             ){
95279               i++;
95280               break;
95281             }
95282           }
95283         }
95284         if( i<nType ){
95285           int j;
95286           int nDel = 6 + (zType[i+6] ? 1 : 0);
95287           for(j=i; (j+nDel)<=nType; j++){
95288             zType[j] = zType[j+nDel];
95289           }
95290           if( zType[i]=='\0' && i>0 ){
95291             assert(zType[i-1]==' ');
95292             zType[i-1] = '\0';
95293           }
95294           pTab->aCol[iCol].isHidden = 1;
95295         }
95296       }
95297     }
95298   }
95299
95300   sqlite3DbFree(db, zModuleName);
95301   db->pVTab = 0;
95302   return rc;
95303 }
95304
95305 /*
95306 ** This function is invoked by the parser to call the xConnect() method
95307 ** of the virtual table pTab. If an error occurs, an error code is returned 
95308 ** and an error left in pParse.
95309 **
95310 ** This call is a no-op if table pTab is not a virtual table.
95311 */
95312 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
95313   sqlite3 *db = pParse->db;
95314   const char *zMod;
95315   Module *pMod;
95316   int rc;
95317
95318   assert( pTab );
95319   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
95320     return SQLITE_OK;
95321   }
95322
95323   /* Locate the required virtual table module */
95324   zMod = pTab->azModuleArg[0];
95325   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
95326
95327   if( !pMod ){
95328     const char *zModule = pTab->azModuleArg[0];
95329     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
95330     rc = SQLITE_ERROR;
95331   }else{
95332     char *zErr = 0;
95333     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
95334     if( rc!=SQLITE_OK ){
95335       sqlite3ErrorMsg(pParse, "%s", zErr);
95336     }
95337     sqlite3DbFree(db, zErr);
95338   }
95339
95340   return rc;
95341 }
95342
95343 /*
95344 ** Add the virtual table pVTab to the array sqlite3.aVTrans[].
95345 */
95346 static int addToVTrans(sqlite3 *db, VTable *pVTab){
95347   const int ARRAY_INCR = 5;
95348
95349   /* Grow the sqlite3.aVTrans array if required */
95350   if( (db->nVTrans%ARRAY_INCR)==0 ){
95351     VTable **aVTrans;
95352     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
95353     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
95354     if( !aVTrans ){
95355       return SQLITE_NOMEM;
95356     }
95357     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
95358     db->aVTrans = aVTrans;
95359   }
95360
95361   /* Add pVtab to the end of sqlite3.aVTrans */
95362   db->aVTrans[db->nVTrans++] = pVTab;
95363   sqlite3VtabLock(pVTab);
95364   return SQLITE_OK;
95365 }
95366
95367 /*
95368 ** This function is invoked by the vdbe to call the xCreate method
95369 ** of the virtual table named zTab in database iDb. 
95370 **
95371 ** If an error occurs, *pzErr is set to point an an English language
95372 ** description of the error and an SQLITE_XXX error code is returned.
95373 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
95374 */
95375 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
95376   int rc = SQLITE_OK;
95377   Table *pTab;
95378   Module *pMod;
95379   const char *zMod;
95380
95381   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
95382   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
95383
95384   /* Locate the required virtual table module */
95385   zMod = pTab->azModuleArg[0];
95386   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
95387
95388   /* If the module has been registered and includes a Create method, 
95389   ** invoke it now. If the module has not been registered, return an 
95390   ** error. Otherwise, do nothing.
95391   */
95392   if( !pMod ){
95393     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
95394     rc = SQLITE_ERROR;
95395   }else{
95396     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
95397   }
95398
95399   /* Justification of ALWAYS():  The xConstructor method is required to
95400   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
95401   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
95402       rc = addToVTrans(db, sqlite3GetVTable(db, pTab));
95403   }
95404
95405   return rc;
95406 }
95407
95408 /*
95409 ** This function is used to set the schema of a virtual table.  It is only
95410 ** valid to call this function from within the xCreate() or xConnect() of a
95411 ** virtual table module.
95412 */
95413 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
95414   Parse *pParse;
95415
95416   int rc = SQLITE_OK;
95417   Table *pTab;
95418   char *zErr = 0;
95419
95420   sqlite3_mutex_enter(db->mutex);
95421   pTab = db->pVTab;
95422   if( !pTab ){
95423     sqlite3Error(db, SQLITE_MISUSE, 0);
95424     sqlite3_mutex_leave(db->mutex);
95425     return SQLITE_MISUSE_BKPT;
95426   }
95427   assert( (pTab->tabFlags & TF_Virtual)!=0 );
95428
95429   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
95430   if( pParse==0 ){
95431     rc = SQLITE_NOMEM;
95432   }else{
95433     pParse->declareVtab = 1;
95434     pParse->db = db;
95435     pParse->nQueryLoop = 1;
95436   
95437     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr) 
95438      && pParse->pNewTable
95439      && !db->mallocFailed
95440      && !pParse->pNewTable->pSelect
95441      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
95442     ){
95443       if( !pTab->aCol ){
95444         pTab->aCol = pParse->pNewTable->aCol;
95445         pTab->nCol = pParse->pNewTable->nCol;
95446         pParse->pNewTable->nCol = 0;
95447         pParse->pNewTable->aCol = 0;
95448       }
95449       db->pVTab = 0;
95450     }else{
95451       sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
95452       sqlite3DbFree(db, zErr);
95453       rc = SQLITE_ERROR;
95454     }
95455     pParse->declareVtab = 0;
95456   
95457     if( pParse->pVdbe ){
95458       sqlite3VdbeFinalize(pParse->pVdbe);
95459     }
95460     sqlite3DeleteTable(db, pParse->pNewTable);
95461     sqlite3StackFree(db, pParse);
95462   }
95463
95464   assert( (rc&0xff)==rc );
95465   rc = sqlite3ApiExit(db, rc);
95466   sqlite3_mutex_leave(db->mutex);
95467   return rc;
95468 }
95469
95470 /*
95471 ** This function is invoked by the vdbe to call the xDestroy method
95472 ** of the virtual table named zTab in database iDb. This occurs
95473 ** when a DROP TABLE is mentioned.
95474 **
95475 ** This call is a no-op if zTab is not a virtual table.
95476 */
95477 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
95478   int rc = SQLITE_OK;
95479   Table *pTab;
95480
95481   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
95482   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
95483     VTable *p = vtabDisconnectAll(db, pTab);
95484
95485     assert( rc==SQLITE_OK );
95486     rc = p->pMod->pModule->xDestroy(p->pVtab);
95487
95488     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
95489     if( rc==SQLITE_OK ){
95490       assert( pTab->pVTable==p && p->pNext==0 );
95491       p->pVtab = 0;
95492       pTab->pVTable = 0;
95493       sqlite3VtabUnlock(p);
95494     }
95495   }
95496
95497   return rc;
95498 }
95499
95500 /*
95501 ** This function invokes either the xRollback or xCommit method
95502 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
95503 ** called is identified by the second argument, "offset", which is
95504 ** the offset of the method to call in the sqlite3_module structure.
95505 **
95506 ** The array is cleared after invoking the callbacks. 
95507 */
95508 static void callFinaliser(sqlite3 *db, int offset){
95509   int i;
95510   if( db->aVTrans ){
95511     for(i=0; i<db->nVTrans; i++){
95512       VTable *pVTab = db->aVTrans[i];
95513       sqlite3_vtab *p = pVTab->pVtab;
95514       if( p ){
95515         int (*x)(sqlite3_vtab *);
95516         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
95517         if( x ) x(p);
95518       }
95519       sqlite3VtabUnlock(pVTab);
95520     }
95521     sqlite3DbFree(db, db->aVTrans);
95522     db->nVTrans = 0;
95523     db->aVTrans = 0;
95524   }
95525 }
95526
95527 /*
95528 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
95529 ** array. Return the error code for the first error that occurs, or
95530 ** SQLITE_OK if all xSync operations are successful.
95531 **
95532 ** Set *pzErrmsg to point to a buffer that should be released using 
95533 ** sqlite3DbFree() containing an error message, if one is available.
95534 */
95535 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
95536   int i;
95537   int rc = SQLITE_OK;
95538   VTable **aVTrans = db->aVTrans;
95539
95540   db->aVTrans = 0;
95541   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
95542     int (*x)(sqlite3_vtab *);
95543     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
95544     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
95545       rc = x(pVtab);
95546       sqlite3DbFree(db, *pzErrmsg);
95547       *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
95548       sqlite3_free(pVtab->zErrMsg);
95549     }
95550   }
95551   db->aVTrans = aVTrans;
95552   return rc;
95553 }
95554
95555 /*
95556 ** Invoke the xRollback method of all virtual tables in the 
95557 ** sqlite3.aVTrans array. Then clear the array itself.
95558 */
95559 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
95560   callFinaliser(db, offsetof(sqlite3_module,xRollback));
95561   return SQLITE_OK;
95562 }
95563
95564 /*
95565 ** Invoke the xCommit method of all virtual tables in the 
95566 ** sqlite3.aVTrans array. Then clear the array itself.
95567 */
95568 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
95569   callFinaliser(db, offsetof(sqlite3_module,xCommit));
95570   return SQLITE_OK;
95571 }
95572
95573 /*
95574 ** If the virtual table pVtab supports the transaction interface
95575 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
95576 ** not currently open, invoke the xBegin method now.
95577 **
95578 ** If the xBegin call is successful, place the sqlite3_vtab pointer
95579 ** in the sqlite3.aVTrans array.
95580 */
95581 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
95582   int rc = SQLITE_OK;
95583   const sqlite3_module *pModule;
95584
95585   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
95586   ** than zero, then this function is being called from within a
95587   ** virtual module xSync() callback. It is illegal to write to 
95588   ** virtual module tables in this case, so return SQLITE_LOCKED.
95589   */
95590   if( sqlite3VtabInSync(db) ){
95591     return SQLITE_LOCKED;
95592   }
95593   if( !pVTab ){
95594     return SQLITE_OK;
95595   } 
95596   pModule = pVTab->pVtab->pModule;
95597
95598   if( pModule->xBegin ){
95599     int i;
95600
95601
95602     /* If pVtab is already in the aVTrans array, return early */
95603     for(i=0; i<db->nVTrans; i++){
95604       if( db->aVTrans[i]==pVTab ){
95605         return SQLITE_OK;
95606       }
95607     }
95608
95609     /* Invoke the xBegin method */
95610     rc = pModule->xBegin(pVTab->pVtab);
95611     if( rc==SQLITE_OK ){
95612       rc = addToVTrans(db, pVTab);
95613     }
95614   }
95615   return rc;
95616 }
95617
95618 /*
95619 ** The first parameter (pDef) is a function implementation.  The
95620 ** second parameter (pExpr) is the first argument to this function.
95621 ** If pExpr is a column in a virtual table, then let the virtual
95622 ** table implementation have an opportunity to overload the function.
95623 **
95624 ** This routine is used to allow virtual table implementations to
95625 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
95626 **
95627 ** Return either the pDef argument (indicating no change) or a 
95628 ** new FuncDef structure that is marked as ephemeral using the
95629 ** SQLITE_FUNC_EPHEM flag.
95630 */
95631 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
95632   sqlite3 *db,    /* Database connection for reporting malloc problems */
95633   FuncDef *pDef,  /* Function to possibly overload */
95634   int nArg,       /* Number of arguments to the function */
95635   Expr *pExpr     /* First argument to the function */
95636 ){
95637   Table *pTab;
95638   sqlite3_vtab *pVtab;
95639   sqlite3_module *pMod;
95640   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
95641   void *pArg = 0;
95642   FuncDef *pNew;
95643   int rc = 0;
95644   char *zLowerName;
95645   unsigned char *z;
95646
95647
95648   /* Check to see the left operand is a column in a virtual table */
95649   if( NEVER(pExpr==0) ) return pDef;
95650   if( pExpr->op!=TK_COLUMN ) return pDef;
95651   pTab = pExpr->pTab;
95652   if( NEVER(pTab==0) ) return pDef;
95653   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
95654   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
95655   assert( pVtab!=0 );
95656   assert( pVtab->pModule!=0 );
95657   pMod = (sqlite3_module *)pVtab->pModule;
95658   if( pMod->xFindFunction==0 ) return pDef;
95659  
95660   /* Call the xFindFunction method on the virtual table implementation
95661   ** to see if the implementation wants to overload this function 
95662   */
95663   zLowerName = sqlite3DbStrDup(db, pDef->zName);
95664   if( zLowerName ){
95665     for(z=(unsigned char*)zLowerName; *z; z++){
95666       *z = sqlite3UpperToLower[*z];
95667     }
95668     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
95669     sqlite3DbFree(db, zLowerName);
95670   }
95671   if( rc==0 ){
95672     return pDef;
95673   }
95674
95675   /* Create a new ephemeral function definition for the overloaded
95676   ** function */
95677   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
95678                              + sqlite3Strlen30(pDef->zName) + 1);
95679   if( pNew==0 ){
95680     return pDef;
95681   }
95682   *pNew = *pDef;
95683   pNew->zName = (char *)&pNew[1];
95684   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
95685   pNew->xFunc = xFunc;
95686   pNew->pUserData = pArg;
95687   pNew->flags |= SQLITE_FUNC_EPHEM;
95688   return pNew;
95689 }
95690
95691 /*
95692 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
95693 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
95694 ** array if it is missing.  If pTab is already in the array, this routine
95695 ** is a no-op.
95696 */
95697 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
95698   Parse *pToplevel = sqlite3ParseToplevel(pParse);
95699   int i, n;
95700   Table **apVtabLock;
95701
95702   assert( IsVirtual(pTab) );
95703   for(i=0; i<pToplevel->nVtabLock; i++){
95704     if( pTab==pToplevel->apVtabLock[i] ) return;
95705   }
95706   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
95707   apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
95708   if( apVtabLock ){
95709     pToplevel->apVtabLock = apVtabLock;
95710     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
95711   }else{
95712     pToplevel->db->mallocFailed = 1;
95713   }
95714 }
95715
95716 #endif /* SQLITE_OMIT_VIRTUALTABLE */
95717
95718 /************** End of vtab.c ************************************************/
95719 /************** Begin file where.c *******************************************/
95720 /*
95721 ** 2001 September 15
95722 **
95723 ** The author disclaims copyright to this source code.  In place of
95724 ** a legal notice, here is a blessing:
95725 **
95726 **    May you do good and not evil.
95727 **    May you find forgiveness for yourself and forgive others.
95728 **    May you share freely, never taking more than you give.
95729 **
95730 *************************************************************************
95731 ** This module contains C code that generates VDBE code used to process
95732 ** the WHERE clause of SQL statements.  This module is responsible for
95733 ** generating the code that loops through a table looking for applicable
95734 ** rows.  Indices are selected and used to speed the search when doing
95735 ** so is applicable.  Because this module is responsible for selecting
95736 ** indices, you might also think of this module as the "query optimizer".
95737 */
95738
95739 /*
95740 ** Trace output macros
95741 */
95742 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
95743 SQLITE_PRIVATE int sqlite3WhereTrace = 0;
95744 #endif
95745 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
95746 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
95747 #else
95748 # define WHERETRACE(X)
95749 #endif
95750
95751 /* Forward reference
95752 */
95753 typedef struct WhereClause WhereClause;
95754 typedef struct WhereMaskSet WhereMaskSet;
95755 typedef struct WhereOrInfo WhereOrInfo;
95756 typedef struct WhereAndInfo WhereAndInfo;
95757 typedef struct WhereCost WhereCost;
95758
95759 /*
95760 ** The query generator uses an array of instances of this structure to
95761 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
95762 ** clause subexpression is separated from the others by AND operators,
95763 ** usually, or sometimes subexpressions separated by OR.
95764 **
95765 ** All WhereTerms are collected into a single WhereClause structure.  
95766 ** The following identity holds:
95767 **
95768 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
95769 **
95770 ** When a term is of the form:
95771 **
95772 **              X <op> <expr>
95773 **
95774 ** where X is a column name and <op> is one of certain operators,
95775 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
95776 ** cursor number and column number for X.  WhereTerm.eOperator records
95777 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
95778 ** use of a bitmask encoding for the operator allows us to search
95779 ** quickly for terms that match any of several different operators.
95780 **
95781 ** A WhereTerm might also be two or more subterms connected by OR:
95782 **
95783 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
95784 **
95785 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
95786 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
95787 ** is collected about the
95788 **
95789 ** If a term in the WHERE clause does not match either of the two previous
95790 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
95791 ** to the original subexpression content and wtFlags is set up appropriately
95792 ** but no other fields in the WhereTerm object are meaningful.
95793 **
95794 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
95795 ** but they do so indirectly.  A single WhereMaskSet structure translates
95796 ** cursor number into bits and the translated bit is stored in the prereq
95797 ** fields.  The translation is used in order to maximize the number of
95798 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
95799 ** spread out over the non-negative integers.  For example, the cursor
95800 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
95801 ** translates these sparse cursor numbers into consecutive integers
95802 ** beginning with 0 in order to make the best possible use of the available
95803 ** bits in the Bitmask.  So, in the example above, the cursor numbers
95804 ** would be mapped into integers 0 through 7.
95805 **
95806 ** The number of terms in a join is limited by the number of bits
95807 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
95808 ** is only able to process joins with 64 or fewer tables.
95809 */
95810 typedef struct WhereTerm WhereTerm;
95811 struct WhereTerm {
95812   Expr *pExpr;            /* Pointer to the subexpression that is this term */
95813   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
95814   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
95815   union {
95816     int leftColumn;         /* Column number of X in "X <op> <expr>" */
95817     WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
95818     WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
95819   } u;
95820   u16 eOperator;          /* A WO_xx value describing <op> */
95821   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
95822   u8 nChild;              /* Number of children that must disable us */
95823   WhereClause *pWC;       /* The clause this term is part of */
95824   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
95825   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
95826 };
95827
95828 /*
95829 ** Allowed values of WhereTerm.wtFlags
95830 */
95831 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
95832 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
95833 #define TERM_CODED      0x04   /* This term is already coded */
95834 #define TERM_COPIED     0x08   /* Has a child */
95835 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
95836 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
95837 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
95838
95839 /*
95840 ** An instance of the following structure holds all information about a
95841 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
95842 */
95843 struct WhereClause {
95844   Parse *pParse;           /* The parser context */
95845   WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
95846   Bitmask vmask;           /* Bitmask identifying virtual table cursors */
95847   u8 op;                   /* Split operator.  TK_AND or TK_OR */
95848   int nTerm;               /* Number of terms */
95849   int nSlot;               /* Number of entries in a[] */
95850   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
95851 #if defined(SQLITE_SMALL_STACK)
95852   WhereTerm aStatic[1];    /* Initial static space for a[] */
95853 #else
95854   WhereTerm aStatic[8];    /* Initial static space for a[] */
95855 #endif
95856 };
95857
95858 /*
95859 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
95860 ** a dynamically allocated instance of the following structure.
95861 */
95862 struct WhereOrInfo {
95863   WhereClause wc;          /* Decomposition into subterms */
95864   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
95865 };
95866
95867 /*
95868 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
95869 ** a dynamically allocated instance of the following structure.
95870 */
95871 struct WhereAndInfo {
95872   WhereClause wc;          /* The subexpression broken out */
95873 };
95874
95875 /*
95876 ** An instance of the following structure keeps track of a mapping
95877 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
95878 **
95879 ** The VDBE cursor numbers are small integers contained in 
95880 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
95881 ** clause, the cursor numbers might not begin with 0 and they might
95882 ** contain gaps in the numbering sequence.  But we want to make maximum
95883 ** use of the bits in our bitmasks.  This structure provides a mapping
95884 ** from the sparse cursor numbers into consecutive integers beginning
95885 ** with 0.
95886 **
95887 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
95888 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
95889 **
95890 ** For example, if the WHERE clause expression used these VDBE
95891 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
95892 ** would map those cursor numbers into bits 0 through 5.
95893 **
95894 ** Note that the mapping is not necessarily ordered.  In the example
95895 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
95896 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
95897 ** does not really matter.  What is important is that sparse cursor
95898 ** numbers all get mapped into bit numbers that begin with 0 and contain
95899 ** no gaps.
95900 */
95901 struct WhereMaskSet {
95902   int n;                        /* Number of assigned cursor values */
95903   int ix[BMS];                  /* Cursor assigned to each bit */
95904 };
95905
95906 /*
95907 ** A WhereCost object records a lookup strategy and the estimated
95908 ** cost of pursuing that strategy.
95909 */
95910 struct WhereCost {
95911   WherePlan plan;    /* The lookup strategy */
95912   double rCost;      /* Overall cost of pursuing this search strategy */
95913   Bitmask used;      /* Bitmask of cursors used by this plan */
95914 };
95915
95916 /*
95917 ** Bitmasks for the operators that indices are able to exploit.  An
95918 ** OR-ed combination of these values can be used when searching for
95919 ** terms in the where clause.
95920 */
95921 #define WO_IN     0x001
95922 #define WO_EQ     0x002
95923 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
95924 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
95925 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
95926 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
95927 #define WO_MATCH  0x040
95928 #define WO_ISNULL 0x080
95929 #define WO_OR     0x100       /* Two or more OR-connected terms */
95930 #define WO_AND    0x200       /* Two or more AND-connected terms */
95931
95932 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
95933 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
95934
95935 /*
95936 ** Value for wsFlags returned by bestIndex() and stored in
95937 ** WhereLevel.wsFlags.  These flags determine which search
95938 ** strategies are appropriate.
95939 **
95940 ** The least significant 12 bits is reserved as a mask for WO_ values above.
95941 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
95942 ** But if the table is the right table of a left join, WhereLevel.wsFlags
95943 ** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
95944 ** the "op" parameter to findTerm when we are resolving equality constraints.
95945 ** ISNULL constraints will then not be used on the right table of a left
95946 ** join.  Tickets #2177 and #2189.
95947 */
95948 #define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
95949 #define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
95950 #define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
95951 #define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
95952 #define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
95953 #define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
95954 #define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
95955 #define WHERE_NOT_FULLSCAN 0x100f3000  /* Does not do a full table scan */
95956 #define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
95957 #define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
95958 #define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
95959 #define WHERE_BOTH_LIMIT   0x00300000  /* Both x>EXPR and x<EXPR */
95960 #define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
95961 #define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
95962 #define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
95963 #define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
95964 #define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
95965 #define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
95966 #define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
95967
95968 /*
95969 ** Initialize a preallocated WhereClause structure.
95970 */
95971 static void whereClauseInit(
95972   WhereClause *pWC,        /* The WhereClause to be initialized */
95973   Parse *pParse,           /* The parsing context */
95974   WhereMaskSet *pMaskSet   /* Mapping from table cursor numbers to bitmasks */
95975 ){
95976   pWC->pParse = pParse;
95977   pWC->pMaskSet = pMaskSet;
95978   pWC->nTerm = 0;
95979   pWC->nSlot = ArraySize(pWC->aStatic);
95980   pWC->a = pWC->aStatic;
95981   pWC->vmask = 0;
95982 }
95983
95984 /* Forward reference */
95985 static void whereClauseClear(WhereClause*);
95986
95987 /*
95988 ** Deallocate all memory associated with a WhereOrInfo object.
95989 */
95990 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
95991   whereClauseClear(&p->wc);
95992   sqlite3DbFree(db, p);
95993 }
95994
95995 /*
95996 ** Deallocate all memory associated with a WhereAndInfo object.
95997 */
95998 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
95999   whereClauseClear(&p->wc);
96000   sqlite3DbFree(db, p);
96001 }
96002
96003 /*
96004 ** Deallocate a WhereClause structure.  The WhereClause structure
96005 ** itself is not freed.  This routine is the inverse of whereClauseInit().
96006 */
96007 static void whereClauseClear(WhereClause *pWC){
96008   int i;
96009   WhereTerm *a;
96010   sqlite3 *db = pWC->pParse->db;
96011   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
96012     if( a->wtFlags & TERM_DYNAMIC ){
96013       sqlite3ExprDelete(db, a->pExpr);
96014     }
96015     if( a->wtFlags & TERM_ORINFO ){
96016       whereOrInfoDelete(db, a->u.pOrInfo);
96017     }else if( a->wtFlags & TERM_ANDINFO ){
96018       whereAndInfoDelete(db, a->u.pAndInfo);
96019     }
96020   }
96021   if( pWC->a!=pWC->aStatic ){
96022     sqlite3DbFree(db, pWC->a);
96023   }
96024 }
96025
96026 /*
96027 ** Add a single new WhereTerm entry to the WhereClause object pWC.
96028 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
96029 ** The index in pWC->a[] of the new WhereTerm is returned on success.
96030 ** 0 is returned if the new WhereTerm could not be added due to a memory
96031 ** allocation error.  The memory allocation failure will be recorded in
96032 ** the db->mallocFailed flag so that higher-level functions can detect it.
96033 **
96034 ** This routine will increase the size of the pWC->a[] array as necessary.
96035 **
96036 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
96037 ** for freeing the expression p is assumed by the WhereClause object pWC.
96038 ** This is true even if this routine fails to allocate a new WhereTerm.
96039 **
96040 ** WARNING:  This routine might reallocate the space used to store
96041 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
96042 ** calling this routine.  Such pointers may be reinitialized by referencing
96043 ** the pWC->a[] array.
96044 */
96045 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
96046   WhereTerm *pTerm;
96047   int idx;
96048   testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */
96049   if( pWC->nTerm>=pWC->nSlot ){
96050     WhereTerm *pOld = pWC->a;
96051     sqlite3 *db = pWC->pParse->db;
96052     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
96053     if( pWC->a==0 ){
96054       if( wtFlags & TERM_DYNAMIC ){
96055         sqlite3ExprDelete(db, p);
96056       }
96057       pWC->a = pOld;
96058       return 0;
96059     }
96060     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
96061     if( pOld!=pWC->aStatic ){
96062       sqlite3DbFree(db, pOld);
96063     }
96064     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
96065   }
96066   pTerm = &pWC->a[idx = pWC->nTerm++];
96067   pTerm->pExpr = p;
96068   pTerm->wtFlags = wtFlags;
96069   pTerm->pWC = pWC;
96070   pTerm->iParent = -1;
96071   return idx;
96072 }
96073
96074 /*
96075 ** This routine identifies subexpressions in the WHERE clause where
96076 ** each subexpression is separated by the AND operator or some other
96077 ** operator specified in the op parameter.  The WhereClause structure
96078 ** is filled with pointers to subexpressions.  For example:
96079 **
96080 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
96081 **           \________/     \_______________/     \________________/
96082 **            slot[0]            slot[1]               slot[2]
96083 **
96084 ** The original WHERE clause in pExpr is unaltered.  All this routine
96085 ** does is make slot[] entries point to substructure within pExpr.
96086 **
96087 ** In the previous sentence and in the diagram, "slot[]" refers to
96088 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
96089 ** all terms of the WHERE clause.
96090 */
96091 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
96092   pWC->op = (u8)op;
96093   if( pExpr==0 ) return;
96094   if( pExpr->op!=op ){
96095     whereClauseInsert(pWC, pExpr, 0);
96096   }else{
96097     whereSplit(pWC, pExpr->pLeft, op);
96098     whereSplit(pWC, pExpr->pRight, op);
96099   }
96100 }
96101
96102 /*
96103 ** Initialize an expression mask set (a WhereMaskSet object)
96104 */
96105 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
96106
96107 /*
96108 ** Return the bitmask for the given cursor number.  Return 0 if
96109 ** iCursor is not in the set.
96110 */
96111 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
96112   int i;
96113   assert( pMaskSet->n<=sizeof(Bitmask)*8 );
96114   for(i=0; i<pMaskSet->n; i++){
96115     if( pMaskSet->ix[i]==iCursor ){
96116       return ((Bitmask)1)<<i;
96117     }
96118   }
96119   return 0;
96120 }
96121
96122 /*
96123 ** Create a new mask for cursor iCursor.
96124 **
96125 ** There is one cursor per table in the FROM clause.  The number of
96126 ** tables in the FROM clause is limited by a test early in the
96127 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
96128 ** array will never overflow.
96129 */
96130 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
96131   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
96132   pMaskSet->ix[pMaskSet->n++] = iCursor;
96133 }
96134
96135 /*
96136 ** This routine walks (recursively) an expression tree and generates
96137 ** a bitmask indicating which tables are used in that expression
96138 ** tree.
96139 **
96140 ** In order for this routine to work, the calling function must have
96141 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
96142 ** the header comment on that routine for additional information.
96143 ** The sqlite3ResolveExprNames() routines looks for column names and
96144 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
96145 ** the VDBE cursor number of the table.  This routine just has to
96146 ** translate the cursor numbers into bitmask values and OR all
96147 ** the bitmasks together.
96148 */
96149 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
96150 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
96151 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
96152   Bitmask mask = 0;
96153   if( p==0 ) return 0;
96154   if( p->op==TK_COLUMN ){
96155     mask = getMask(pMaskSet, p->iTable);
96156     return mask;
96157   }
96158   mask = exprTableUsage(pMaskSet, p->pRight);
96159   mask |= exprTableUsage(pMaskSet, p->pLeft);
96160   if( ExprHasProperty(p, EP_xIsSelect) ){
96161     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
96162   }else{
96163     mask |= exprListTableUsage(pMaskSet, p->x.pList);
96164   }
96165   return mask;
96166 }
96167 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
96168   int i;
96169   Bitmask mask = 0;
96170   if( pList ){
96171     for(i=0; i<pList->nExpr; i++){
96172       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
96173     }
96174   }
96175   return mask;
96176 }
96177 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
96178   Bitmask mask = 0;
96179   while( pS ){
96180     mask |= exprListTableUsage(pMaskSet, pS->pEList);
96181     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
96182     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
96183     mask |= exprTableUsage(pMaskSet, pS->pWhere);
96184     mask |= exprTableUsage(pMaskSet, pS->pHaving);
96185     pS = pS->pPrior;
96186   }
96187   return mask;
96188 }
96189
96190 /*
96191 ** Return TRUE if the given operator is one of the operators that is
96192 ** allowed for an indexable WHERE clause term.  The allowed operators are
96193 ** "=", "<", ">", "<=", ">=", and "IN".
96194 **
96195 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
96196 ** of one of the following forms: column = expression column > expression
96197 ** column >= expression column < expression column <= expression
96198 ** expression = column expression > column expression >= column
96199 ** expression < column expression <= column column IN
96200 ** (expression-list) column IN (subquery) column IS NULL
96201 */
96202 static int allowedOp(int op){
96203   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
96204   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
96205   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
96206   assert( TK_GE==TK_EQ+4 );
96207   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
96208 }
96209
96210 /*
96211 ** Swap two objects of type TYPE.
96212 */
96213 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
96214
96215 /*
96216 ** Commute a comparison operator.  Expressions of the form "X op Y"
96217 ** are converted into "Y op X".
96218 **
96219 ** If a collation sequence is associated with either the left or right
96220 ** side of the comparison, it remains associated with the same side after
96221 ** the commutation. So "Y collate NOCASE op X" becomes 
96222 ** "X collate NOCASE op Y". This is because any collation sequence on
96223 ** the left hand side of a comparison overrides any collation sequence 
96224 ** attached to the right. For the same reason the EP_ExpCollate flag
96225 ** is not commuted.
96226 */
96227 static void exprCommute(Parse *pParse, Expr *pExpr){
96228   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
96229   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
96230   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
96231   pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
96232   pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
96233   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
96234   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
96235   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
96236   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
96237   if( pExpr->op>=TK_GT ){
96238     assert( TK_LT==TK_GT+2 );
96239     assert( TK_GE==TK_LE+2 );
96240     assert( TK_GT>TK_EQ );
96241     assert( TK_GT<TK_LE );
96242     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
96243     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
96244   }
96245 }
96246
96247 /*
96248 ** Translate from TK_xx operator to WO_xx bitmask.
96249 */
96250 static u16 operatorMask(int op){
96251   u16 c;
96252   assert( allowedOp(op) );
96253   if( op==TK_IN ){
96254     c = WO_IN;
96255   }else if( op==TK_ISNULL ){
96256     c = WO_ISNULL;
96257   }else{
96258     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
96259     c = (u16)(WO_EQ<<(op-TK_EQ));
96260   }
96261   assert( op!=TK_ISNULL || c==WO_ISNULL );
96262   assert( op!=TK_IN || c==WO_IN );
96263   assert( op!=TK_EQ || c==WO_EQ );
96264   assert( op!=TK_LT || c==WO_LT );
96265   assert( op!=TK_LE || c==WO_LE );
96266   assert( op!=TK_GT || c==WO_GT );
96267   assert( op!=TK_GE || c==WO_GE );
96268   return c;
96269 }
96270
96271 /*
96272 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
96273 ** where X is a reference to the iColumn of table iCur and <op> is one of
96274 ** the WO_xx operator codes specified by the op parameter.
96275 ** Return a pointer to the term.  Return 0 if not found.
96276 */
96277 static WhereTerm *findTerm(
96278   WhereClause *pWC,     /* The WHERE clause to be searched */
96279   int iCur,             /* Cursor number of LHS */
96280   int iColumn,          /* Column number of LHS */
96281   Bitmask notReady,     /* RHS must not overlap with this mask */
96282   u32 op,               /* Mask of WO_xx values describing operator */
96283   Index *pIdx           /* Must be compatible with this index, if not NULL */
96284 ){
96285   WhereTerm *pTerm;
96286   int k;
96287   assert( iCur>=0 );
96288   op &= WO_ALL;
96289   for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
96290     if( pTerm->leftCursor==iCur
96291        && (pTerm->prereqRight & notReady)==0
96292        && pTerm->u.leftColumn==iColumn
96293        && (pTerm->eOperator & op)!=0
96294     ){
96295       if( pIdx && pTerm->eOperator!=WO_ISNULL ){
96296         Expr *pX = pTerm->pExpr;
96297         CollSeq *pColl;
96298         char idxaff;
96299         int j;
96300         Parse *pParse = pWC->pParse;
96301
96302         idxaff = pIdx->pTable->aCol[iColumn].affinity;
96303         if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
96304
96305         /* Figure out the collation sequence required from an index for
96306         ** it to be useful for optimising expression pX. Store this
96307         ** value in variable pColl.
96308         */
96309         assert(pX->pLeft);
96310         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
96311         assert(pColl || pParse->nErr);
96312
96313         for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
96314           if( NEVER(j>=pIdx->nColumn) ) return 0;
96315         }
96316         if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
96317       }
96318       return pTerm;
96319     }
96320   }
96321   return 0;
96322 }
96323
96324 /* Forward reference */
96325 static void exprAnalyze(SrcList*, WhereClause*, int);
96326
96327 /*
96328 ** Call exprAnalyze on all terms in a WHERE clause.  
96329 **
96330 **
96331 */
96332 static void exprAnalyzeAll(
96333   SrcList *pTabList,       /* the FROM clause */
96334   WhereClause *pWC         /* the WHERE clause to be analyzed */
96335 ){
96336   int i;
96337   for(i=pWC->nTerm-1; i>=0; i--){
96338     exprAnalyze(pTabList, pWC, i);
96339   }
96340 }
96341
96342 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
96343 /*
96344 ** Check to see if the given expression is a LIKE or GLOB operator that
96345 ** can be optimized using inequality constraints.  Return TRUE if it is
96346 ** so and false if not.
96347 **
96348 ** In order for the operator to be optimizible, the RHS must be a string
96349 ** literal that does not begin with a wildcard.  
96350 */
96351 static int isLikeOrGlob(
96352   Parse *pParse,    /* Parsing and code generating context */
96353   Expr *pExpr,      /* Test this expression */
96354   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
96355   int *pisComplete, /* True if the only wildcard is % in the last character */
96356   int *pnoCase      /* True if uppercase is equivalent to lowercase */
96357 ){
96358   const char *z = 0;         /* String on RHS of LIKE operator */
96359   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
96360   ExprList *pList;           /* List of operands to the LIKE operator */
96361   int c;                     /* One character in z[] */
96362   int cnt;                   /* Number of non-wildcard prefix characters */
96363   char wc[3];                /* Wildcard characters */
96364   sqlite3 *db = pParse->db;  /* Database connection */
96365   sqlite3_value *pVal = 0;
96366   int op;                    /* Opcode of pRight */
96367
96368   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
96369     return 0;
96370   }
96371 #ifdef SQLITE_EBCDIC
96372   if( *pnoCase ) return 0;
96373 #endif
96374   pList = pExpr->x.pList;
96375   pLeft = pList->a[1].pExpr;
96376   if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
96377     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
96378     ** be the name of an indexed column with TEXT affinity. */
96379     return 0;
96380   }
96381   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
96382
96383   pRight = pList->a[0].pExpr;
96384   op = pRight->op;
96385   if( op==TK_REGISTER ){
96386     op = pRight->op2;
96387   }
96388   if( op==TK_VARIABLE ){
96389     Vdbe *pReprepare = pParse->pReprepare;
96390     int iCol = pRight->iColumn;
96391     pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
96392     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
96393       z = (char *)sqlite3_value_text(pVal);
96394     }
96395     sqlite3VdbeSetVarmask(pParse->pVdbe, iCol); /* IMP: R-23257-02778 */
96396     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
96397   }else if( op==TK_STRING ){
96398     z = pRight->u.zToken;
96399   }
96400   if( z ){
96401     cnt = 0;
96402     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
96403       cnt++;
96404     }
96405     if( cnt!=0 && 255!=(u8)z[cnt-1] ){
96406       Expr *pPrefix;
96407       *pisComplete = c==wc[0] && z[cnt+1]==0;
96408       pPrefix = sqlite3Expr(db, TK_STRING, z);
96409       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
96410       *ppPrefix = pPrefix;
96411       if( op==TK_VARIABLE ){
96412         Vdbe *v = pParse->pVdbe;
96413         sqlite3VdbeSetVarmask(v, pRight->iColumn); /* IMP: R-23257-02778 */
96414         if( *pisComplete && pRight->u.zToken[1] ){
96415           /* If the rhs of the LIKE expression is a variable, and the current
96416           ** value of the variable means there is no need to invoke the LIKE
96417           ** function, then no OP_Variable will be added to the program.
96418           ** This causes problems for the sqlite3_bind_parameter_name()
96419           ** API. To workaround them, add a dummy OP_Variable here.
96420           */ 
96421           int r1 = sqlite3GetTempReg(pParse);
96422           sqlite3ExprCodeTarget(pParse, pRight, r1);
96423           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
96424           sqlite3ReleaseTempReg(pParse, r1);
96425         }
96426       }
96427     }else{
96428       z = 0;
96429     }
96430   }
96431
96432   sqlite3ValueFree(pVal);
96433   return (z!=0);
96434 }
96435 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
96436
96437
96438 #ifndef SQLITE_OMIT_VIRTUALTABLE
96439 /*
96440 ** Check to see if the given expression is of the form
96441 **
96442 **         column MATCH expr
96443 **
96444 ** If it is then return TRUE.  If not, return FALSE.
96445 */
96446 static int isMatchOfColumn(
96447   Expr *pExpr      /* Test this expression */
96448 ){
96449   ExprList *pList;
96450
96451   if( pExpr->op!=TK_FUNCTION ){
96452     return 0;
96453   }
96454   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
96455     return 0;
96456   }
96457   pList = pExpr->x.pList;
96458   if( pList->nExpr!=2 ){
96459     return 0;
96460   }
96461   if( pList->a[1].pExpr->op != TK_COLUMN ){
96462     return 0;
96463   }
96464   return 1;
96465 }
96466 #endif /* SQLITE_OMIT_VIRTUALTABLE */
96467
96468 /*
96469 ** If the pBase expression originated in the ON or USING clause of
96470 ** a join, then transfer the appropriate markings over to derived.
96471 */
96472 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
96473   pDerived->flags |= pBase->flags & EP_FromJoin;
96474   pDerived->iRightJoinTable = pBase->iRightJoinTable;
96475 }
96476
96477 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
96478 /*
96479 ** Analyze a term that consists of two or more OR-connected
96480 ** subterms.  So in:
96481 **
96482 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
96483 **                          ^^^^^^^^^^^^^^^^^^^^
96484 **
96485 ** This routine analyzes terms such as the middle term in the above example.
96486 ** A WhereOrTerm object is computed and attached to the term under
96487 ** analysis, regardless of the outcome of the analysis.  Hence:
96488 **
96489 **     WhereTerm.wtFlags   |=  TERM_ORINFO
96490 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
96491 **
96492 ** The term being analyzed must have two or more of OR-connected subterms.
96493 ** A single subterm might be a set of AND-connected sub-subterms.
96494 ** Examples of terms under analysis:
96495 **
96496 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
96497 **     (B)     x=expr1 OR expr2=x OR x=expr3
96498 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
96499 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
96500 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
96501 **
96502 ** CASE 1:
96503 **
96504 ** If all subterms are of the form T.C=expr for some single column of C
96505 ** a single table T (as shown in example B above) then create a new virtual
96506 ** term that is an equivalent IN expression.  In other words, if the term
96507 ** being analyzed is:
96508 **
96509 **      x = expr1  OR  expr2 = x  OR  x = expr3
96510 **
96511 ** then create a new virtual term like this:
96512 **
96513 **      x IN (expr1,expr2,expr3)
96514 **
96515 ** CASE 2:
96516 **
96517 ** If all subterms are indexable by a single table T, then set
96518 **
96519 **     WhereTerm.eOperator              =  WO_OR
96520 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
96521 **
96522 ** A subterm is "indexable" if it is of the form
96523 ** "T.C <op> <expr>" where C is any column of table T and 
96524 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
96525 ** A subterm is also indexable if it is an AND of two or more
96526 ** subsubterms at least one of which is indexable.  Indexable AND 
96527 ** subterms have their eOperator set to WO_AND and they have
96528 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
96529 **
96530 ** From another point of view, "indexable" means that the subterm could
96531 ** potentially be used with an index if an appropriate index exists.
96532 ** This analysis does not consider whether or not the index exists; that
96533 ** is something the bestIndex() routine will determine.  This analysis
96534 ** only looks at whether subterms appropriate for indexing exist.
96535 **
96536 ** All examples A through E above all satisfy case 2.  But if a term
96537 ** also statisfies case 1 (such as B) we know that the optimizer will
96538 ** always prefer case 1, so in that case we pretend that case 2 is not
96539 ** satisfied.
96540 **
96541 ** It might be the case that multiple tables are indexable.  For example,
96542 ** (E) above is indexable on tables P, Q, and R.
96543 **
96544 ** Terms that satisfy case 2 are candidates for lookup by using
96545 ** separate indices to find rowids for each subterm and composing
96546 ** the union of all rowids using a RowSet object.  This is similar
96547 ** to "bitmap indices" in other database engines.
96548 **
96549 ** OTHERWISE:
96550 **
96551 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
96552 ** zero.  This term is not useful for search.
96553 */
96554 static void exprAnalyzeOrTerm(
96555   SrcList *pSrc,            /* the FROM clause */
96556   WhereClause *pWC,         /* the complete WHERE clause */
96557   int idxTerm               /* Index of the OR-term to be analyzed */
96558 ){
96559   Parse *pParse = pWC->pParse;            /* Parser context */
96560   sqlite3 *db = pParse->db;               /* Database connection */
96561   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
96562   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
96563   WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
96564   int i;                                  /* Loop counters */
96565   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
96566   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
96567   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
96568   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
96569   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
96570
96571   /*
96572   ** Break the OR clause into its separate subterms.  The subterms are
96573   ** stored in a WhereClause structure containing within the WhereOrInfo
96574   ** object that is attached to the original OR clause term.
96575   */
96576   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
96577   assert( pExpr->op==TK_OR );
96578   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
96579   if( pOrInfo==0 ) return;
96580   pTerm->wtFlags |= TERM_ORINFO;
96581   pOrWc = &pOrInfo->wc;
96582   whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
96583   whereSplit(pOrWc, pExpr, TK_OR);
96584   exprAnalyzeAll(pSrc, pOrWc);
96585   if( db->mallocFailed ) return;
96586   assert( pOrWc->nTerm>=2 );
96587
96588   /*
96589   ** Compute the set of tables that might satisfy cases 1 or 2.
96590   */
96591   indexable = ~(Bitmask)0;
96592   chngToIN = ~(pWC->vmask);
96593   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
96594     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
96595       WhereAndInfo *pAndInfo;
96596       assert( pOrTerm->eOperator==0 );
96597       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
96598       chngToIN = 0;
96599       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
96600       if( pAndInfo ){
96601         WhereClause *pAndWC;
96602         WhereTerm *pAndTerm;
96603         int j;
96604         Bitmask b = 0;
96605         pOrTerm->u.pAndInfo = pAndInfo;
96606         pOrTerm->wtFlags |= TERM_ANDINFO;
96607         pOrTerm->eOperator = WO_AND;
96608         pAndWC = &pAndInfo->wc;
96609         whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
96610         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
96611         exprAnalyzeAll(pSrc, pAndWC);
96612         testcase( db->mallocFailed );
96613         if( !db->mallocFailed ){
96614           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
96615             assert( pAndTerm->pExpr );
96616             if( allowedOp(pAndTerm->pExpr->op) ){
96617               b |= getMask(pMaskSet, pAndTerm->leftCursor);
96618             }
96619           }
96620         }
96621         indexable &= b;
96622       }
96623     }else if( pOrTerm->wtFlags & TERM_COPIED ){
96624       /* Skip this term for now.  We revisit it when we process the
96625       ** corresponding TERM_VIRTUAL term */
96626     }else{
96627       Bitmask b;
96628       b = getMask(pMaskSet, pOrTerm->leftCursor);
96629       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
96630         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
96631         b |= getMask(pMaskSet, pOther->leftCursor);
96632       }
96633       indexable &= b;
96634       if( pOrTerm->eOperator!=WO_EQ ){
96635         chngToIN = 0;
96636       }else{
96637         chngToIN &= b;
96638       }
96639     }
96640   }
96641
96642   /*
96643   ** Record the set of tables that satisfy case 2.  The set might be
96644   ** empty.
96645   */
96646   pOrInfo->indexable = indexable;
96647   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
96648
96649   /*
96650   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
96651   ** we have to do some additional checking to see if case 1 really
96652   ** is satisfied.
96653   **
96654   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
96655   ** that there is no possibility of transforming the OR clause into an
96656   ** IN operator because one or more terms in the OR clause contain
96657   ** something other than == on a column in the single table.  The 1-bit
96658   ** case means that every term of the OR clause is of the form
96659   ** "table.column=expr" for some single table.  The one bit that is set
96660   ** will correspond to the common table.  We still need to check to make
96661   ** sure the same column is used on all terms.  The 2-bit case is when
96662   ** the all terms are of the form "table1.column=table2.column".  It
96663   ** might be possible to form an IN operator with either table1.column
96664   ** or table2.column as the LHS if either is common to every term of
96665   ** the OR clause.
96666   **
96667   ** Note that terms of the form "table.column1=table.column2" (the
96668   ** same table on both sizes of the ==) cannot be optimized.
96669   */
96670   if( chngToIN ){
96671     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
96672     int iColumn = -1;         /* Column index on lhs of IN operator */
96673     int iCursor = -1;         /* Table cursor common to all terms */
96674     int j = 0;                /* Loop counter */
96675
96676     /* Search for a table and column that appears on one side or the
96677     ** other of the == operator in every subterm.  That table and column
96678     ** will be recorded in iCursor and iColumn.  There might not be any
96679     ** such table and column.  Set okToChngToIN if an appropriate table
96680     ** and column is found but leave okToChngToIN false if not found.
96681     */
96682     for(j=0; j<2 && !okToChngToIN; j++){
96683       pOrTerm = pOrWc->a;
96684       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
96685         assert( pOrTerm->eOperator==WO_EQ );
96686         pOrTerm->wtFlags &= ~TERM_OR_OK;
96687         if( pOrTerm->leftCursor==iCursor ){
96688           /* This is the 2-bit case and we are on the second iteration and
96689           ** current term is from the first iteration.  So skip this term. */
96690           assert( j==1 );
96691           continue;
96692         }
96693         if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
96694           /* This term must be of the form t1.a==t2.b where t2 is in the
96695           ** chngToIN set but t1 is not.  This term will be either preceeded
96696           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term 
96697           ** and use its inversion. */
96698           testcase( pOrTerm->wtFlags & TERM_COPIED );
96699           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
96700           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
96701           continue;
96702         }
96703         iColumn = pOrTerm->u.leftColumn;
96704         iCursor = pOrTerm->leftCursor;
96705         break;
96706       }
96707       if( i<0 ){
96708         /* No candidate table+column was found.  This can only occur
96709         ** on the second iteration */
96710         assert( j==1 );
96711         assert( (chngToIN&(chngToIN-1))==0 );
96712         assert( chngToIN==getMask(pMaskSet, iCursor) );
96713         break;
96714       }
96715       testcase( j==1 );
96716
96717       /* We have found a candidate table and column.  Check to see if that
96718       ** table and column is common to every term in the OR clause */
96719       okToChngToIN = 1;
96720       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
96721         assert( pOrTerm->eOperator==WO_EQ );
96722         if( pOrTerm->leftCursor!=iCursor ){
96723           pOrTerm->wtFlags &= ~TERM_OR_OK;
96724         }else if( pOrTerm->u.leftColumn!=iColumn ){
96725           okToChngToIN = 0;
96726         }else{
96727           int affLeft, affRight;
96728           /* If the right-hand side is also a column, then the affinities
96729           ** of both right and left sides must be such that no type
96730           ** conversions are required on the right.  (Ticket #2249)
96731           */
96732           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
96733           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
96734           if( affRight!=0 && affRight!=affLeft ){
96735             okToChngToIN = 0;
96736           }else{
96737             pOrTerm->wtFlags |= TERM_OR_OK;
96738           }
96739         }
96740       }
96741     }
96742
96743     /* At this point, okToChngToIN is true if original pTerm satisfies
96744     ** case 1.  In that case, construct a new virtual term that is 
96745     ** pTerm converted into an IN operator.
96746     **
96747     ** EV: R-00211-15100
96748     */
96749     if( okToChngToIN ){
96750       Expr *pDup;            /* A transient duplicate expression */
96751       ExprList *pList = 0;   /* The RHS of the IN operator */
96752       Expr *pLeft = 0;       /* The LHS of the IN operator */
96753       Expr *pNew;            /* The complete IN operator */
96754
96755       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
96756         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
96757         assert( pOrTerm->eOperator==WO_EQ );
96758         assert( pOrTerm->leftCursor==iCursor );
96759         assert( pOrTerm->u.leftColumn==iColumn );
96760         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
96761         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
96762         pLeft = pOrTerm->pExpr->pLeft;
96763       }
96764       assert( pLeft!=0 );
96765       pDup = sqlite3ExprDup(db, pLeft, 0);
96766       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
96767       if( pNew ){
96768         int idxNew;
96769         transferJoinMarkings(pNew, pExpr);
96770         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
96771         pNew->x.pList = pList;
96772         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
96773         testcase( idxNew==0 );
96774         exprAnalyze(pSrc, pWC, idxNew);
96775         pTerm = &pWC->a[idxTerm];
96776         pWC->a[idxNew].iParent = idxTerm;
96777         pTerm->nChild = 1;
96778       }else{
96779         sqlite3ExprListDelete(db, pList);
96780       }
96781       pTerm->eOperator = 0;  /* case 1 trumps case 2 */
96782     }
96783   }
96784 }
96785 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
96786
96787
96788 /*
96789 ** The input to this routine is an WhereTerm structure with only the
96790 ** "pExpr" field filled in.  The job of this routine is to analyze the
96791 ** subexpression and populate all the other fields of the WhereTerm
96792 ** structure.
96793 **
96794 ** If the expression is of the form "<expr> <op> X" it gets commuted
96795 ** to the standard form of "X <op> <expr>".
96796 **
96797 ** If the expression is of the form "X <op> Y" where both X and Y are
96798 ** columns, then the original expression is unchanged and a new virtual
96799 ** term of the form "Y <op> X" is added to the WHERE clause and
96800 ** analyzed separately.  The original term is marked with TERM_COPIED
96801 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
96802 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
96803 ** is a commuted copy of a prior term.)  The original term has nChild=1
96804 ** and the copy has idxParent set to the index of the original term.
96805 */
96806 static void exprAnalyze(
96807   SrcList *pSrc,            /* the FROM clause */
96808   WhereClause *pWC,         /* the WHERE clause */
96809   int idxTerm               /* Index of the term to be analyzed */
96810 ){
96811   WhereTerm *pTerm;                /* The term to be analyzed */
96812   WhereMaskSet *pMaskSet;          /* Set of table index masks */
96813   Expr *pExpr;                     /* The expression to be analyzed */
96814   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
96815   Bitmask prereqAll;               /* Prerequesites of pExpr */
96816   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
96817   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
96818   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
96819   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
96820   int op;                          /* Top-level operator.  pExpr->op */
96821   Parse *pParse = pWC->pParse;     /* Parsing context */
96822   sqlite3 *db = pParse->db;        /* Database connection */
96823
96824   if( db->mallocFailed ){
96825     return;
96826   }
96827   pTerm = &pWC->a[idxTerm];
96828   pMaskSet = pWC->pMaskSet;
96829   pExpr = pTerm->pExpr;
96830   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
96831   op = pExpr->op;
96832   if( op==TK_IN ){
96833     assert( pExpr->pRight==0 );
96834     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
96835       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
96836     }else{
96837       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
96838     }
96839   }else if( op==TK_ISNULL ){
96840     pTerm->prereqRight = 0;
96841   }else{
96842     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
96843   }
96844   prereqAll = exprTableUsage(pMaskSet, pExpr);
96845   if( ExprHasProperty(pExpr, EP_FromJoin) ){
96846     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
96847     prereqAll |= x;
96848     extraRight = x-1;  /* ON clause terms may not be used with an index
96849                        ** on left table of a LEFT JOIN.  Ticket #3015 */
96850   }
96851   pTerm->prereqAll = prereqAll;
96852   pTerm->leftCursor = -1;
96853   pTerm->iParent = -1;
96854   pTerm->eOperator = 0;
96855   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
96856     Expr *pLeft = pExpr->pLeft;
96857     Expr *pRight = pExpr->pRight;
96858     if( pLeft->op==TK_COLUMN ){
96859       pTerm->leftCursor = pLeft->iTable;
96860       pTerm->u.leftColumn = pLeft->iColumn;
96861       pTerm->eOperator = operatorMask(op);
96862     }
96863     if( pRight && pRight->op==TK_COLUMN ){
96864       WhereTerm *pNew;
96865       Expr *pDup;
96866       if( pTerm->leftCursor>=0 ){
96867         int idxNew;
96868         pDup = sqlite3ExprDup(db, pExpr, 0);
96869         if( db->mallocFailed ){
96870           sqlite3ExprDelete(db, pDup);
96871           return;
96872         }
96873         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
96874         if( idxNew==0 ) return;
96875         pNew = &pWC->a[idxNew];
96876         pNew->iParent = idxTerm;
96877         pTerm = &pWC->a[idxTerm];
96878         pTerm->nChild = 1;
96879         pTerm->wtFlags |= TERM_COPIED;
96880       }else{
96881         pDup = pExpr;
96882         pNew = pTerm;
96883       }
96884       exprCommute(pParse, pDup);
96885       pLeft = pDup->pLeft;
96886       pNew->leftCursor = pLeft->iTable;
96887       pNew->u.leftColumn = pLeft->iColumn;
96888       testcase( (prereqLeft | extraRight) != prereqLeft );
96889       pNew->prereqRight = prereqLeft | extraRight;
96890       pNew->prereqAll = prereqAll;
96891       pNew->eOperator = operatorMask(pDup->op);
96892     }
96893   }
96894
96895 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
96896   /* If a term is the BETWEEN operator, create two new virtual terms
96897   ** that define the range that the BETWEEN implements.  For example:
96898   **
96899   **      a BETWEEN b AND c
96900   **
96901   ** is converted into:
96902   **
96903   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
96904   **
96905   ** The two new terms are added onto the end of the WhereClause object.
96906   ** The new terms are "dynamic" and are children of the original BETWEEN
96907   ** term.  That means that if the BETWEEN term is coded, the children are
96908   ** skipped.  Or, if the children are satisfied by an index, the original
96909   ** BETWEEN term is skipped.
96910   */
96911   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
96912     ExprList *pList = pExpr->x.pList;
96913     int i;
96914     static const u8 ops[] = {TK_GE, TK_LE};
96915     assert( pList!=0 );
96916     assert( pList->nExpr==2 );
96917     for(i=0; i<2; i++){
96918       Expr *pNewExpr;
96919       int idxNew;
96920       pNewExpr = sqlite3PExpr(pParse, ops[i], 
96921                              sqlite3ExprDup(db, pExpr->pLeft, 0),
96922                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
96923       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
96924       testcase( idxNew==0 );
96925       exprAnalyze(pSrc, pWC, idxNew);
96926       pTerm = &pWC->a[idxTerm];
96927       pWC->a[idxNew].iParent = idxTerm;
96928     }
96929     pTerm->nChild = 2;
96930   }
96931 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
96932
96933 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
96934   /* Analyze a term that is composed of two or more subterms connected by
96935   ** an OR operator.
96936   */
96937   else if( pExpr->op==TK_OR ){
96938     assert( pWC->op==TK_AND );
96939     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
96940     pTerm = &pWC->a[idxTerm];
96941   }
96942 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
96943
96944 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
96945   /* Add constraints to reduce the search space on a LIKE or GLOB
96946   ** operator.
96947   **
96948   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
96949   **
96950   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
96951   **
96952   ** The last character of the prefix "abc" is incremented to form the
96953   ** termination condition "abd".
96954   */
96955   if( pWC->op==TK_AND 
96956    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
96957   ){
96958     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
96959     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
96960     Expr *pNewExpr1;
96961     Expr *pNewExpr2;
96962     int idxNew1;
96963     int idxNew2;
96964     CollSeq *pColl;    /* Collating sequence to use */
96965
96966     pLeft = pExpr->x.pList->a[1].pExpr;
96967     pStr2 = sqlite3ExprDup(db, pStr1, 0);
96968     if( !db->mallocFailed ){
96969       u8 c, *pC;       /* Last character before the first wildcard */
96970       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
96971       c = *pC;
96972       if( noCase ){
96973         /* The point is to increment the last character before the first
96974         ** wildcard.  But if we increment '@', that will push it into the
96975         ** alphabetic range where case conversions will mess up the 
96976         ** inequality.  To avoid this, make sure to also run the full
96977         ** LIKE on all candidate expressions by clearing the isComplete flag
96978         */
96979         if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */
96980
96981
96982         c = sqlite3UpperToLower[c];
96983       }
96984       *pC = c + 1;
96985     }
96986     pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, noCase ? "NOCASE" : "BINARY",0);
96987     pNewExpr1 = sqlite3PExpr(pParse, TK_GE, 
96988                      sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
96989                      pStr1, 0);
96990     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
96991     testcase( idxNew1==0 );
96992     exprAnalyze(pSrc, pWC, idxNew1);
96993     pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
96994                      sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
96995                      pStr2, 0);
96996     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
96997     testcase( idxNew2==0 );
96998     exprAnalyze(pSrc, pWC, idxNew2);
96999     pTerm = &pWC->a[idxTerm];
97000     if( isComplete ){
97001       pWC->a[idxNew1].iParent = idxTerm;
97002       pWC->a[idxNew2].iParent = idxTerm;
97003       pTerm->nChild = 2;
97004     }
97005   }
97006 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
97007
97008 #ifndef SQLITE_OMIT_VIRTUALTABLE
97009   /* Add a WO_MATCH auxiliary term to the constraint set if the
97010   ** current expression is of the form:  column MATCH expr.
97011   ** This information is used by the xBestIndex methods of
97012   ** virtual tables.  The native query optimizer does not attempt
97013   ** to do anything with MATCH functions.
97014   */
97015   if( isMatchOfColumn(pExpr) ){
97016     int idxNew;
97017     Expr *pRight, *pLeft;
97018     WhereTerm *pNewTerm;
97019     Bitmask prereqColumn, prereqExpr;
97020
97021     pRight = pExpr->x.pList->a[0].pExpr;
97022     pLeft = pExpr->x.pList->a[1].pExpr;
97023     prereqExpr = exprTableUsage(pMaskSet, pRight);
97024     prereqColumn = exprTableUsage(pMaskSet, pLeft);
97025     if( (prereqExpr & prereqColumn)==0 ){
97026       Expr *pNewExpr;
97027       pNewExpr = sqlite3PExpr(pParse, TK_MATCH, 
97028                               0, sqlite3ExprDup(db, pRight, 0), 0);
97029       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
97030       testcase( idxNew==0 );
97031       pNewTerm = &pWC->a[idxNew];
97032       pNewTerm->prereqRight = prereqExpr;
97033       pNewTerm->leftCursor = pLeft->iTable;
97034       pNewTerm->u.leftColumn = pLeft->iColumn;
97035       pNewTerm->eOperator = WO_MATCH;
97036       pNewTerm->iParent = idxTerm;
97037       pTerm = &pWC->a[idxTerm];
97038       pTerm->nChild = 1;
97039       pTerm->wtFlags |= TERM_COPIED;
97040       pNewTerm->prereqAll = pTerm->prereqAll;
97041     }
97042   }
97043 #endif /* SQLITE_OMIT_VIRTUALTABLE */
97044
97045   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
97046   ** an index for tables to the left of the join.
97047   */
97048   pTerm->prereqRight |= extraRight;
97049 }
97050
97051 /*
97052 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
97053 ** a reference to any table other than the iBase table.
97054 */
97055 static int referencesOtherTables(
97056   ExprList *pList,          /* Search expressions in ths list */
97057   WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
97058   int iFirst,               /* Be searching with the iFirst-th expression */
97059   int iBase                 /* Ignore references to this table */
97060 ){
97061   Bitmask allowed = ~getMask(pMaskSet, iBase);
97062   while( iFirst<pList->nExpr ){
97063     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
97064       return 1;
97065     }
97066   }
97067   return 0;
97068 }
97069
97070
97071 /*
97072 ** This routine decides if pIdx can be used to satisfy the ORDER BY
97073 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
97074 ** ORDER BY clause, this routine returns 0.
97075 **
97076 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
97077 ** left-most table in the FROM clause of that same SELECT statement and
97078 ** the table has a cursor number of "base".  pIdx is an index on pTab.
97079 **
97080 ** nEqCol is the number of columns of pIdx that are used as equality
97081 ** constraints.  Any of these columns may be missing from the ORDER BY
97082 ** clause and the match can still be a success.
97083 **
97084 ** All terms of the ORDER BY that match against the index must be either
97085 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
97086 ** index do not need to satisfy this constraint.)  The *pbRev value is
97087 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
97088 ** the ORDER BY clause is all ASC.
97089 */
97090 static int isSortingIndex(
97091   Parse *pParse,          /* Parsing context */
97092   WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
97093   Index *pIdx,            /* The index we are testing */
97094   int base,               /* Cursor number for the table to be sorted */
97095   ExprList *pOrderBy,     /* The ORDER BY clause */
97096   int nEqCol,             /* Number of index columns with == constraints */
97097   int *pbRev              /* Set to 1 if ORDER BY is DESC */
97098 ){
97099   int i, j;                       /* Loop counters */
97100   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
97101   int nTerm;                      /* Number of ORDER BY terms */
97102   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
97103   sqlite3 *db = pParse->db;
97104
97105   assert( pOrderBy!=0 );
97106   nTerm = pOrderBy->nExpr;
97107   assert( nTerm>0 );
97108
97109   /* Argument pIdx must either point to a 'real' named index structure, 
97110   ** or an index structure allocated on the stack by bestBtreeIndex() to
97111   ** represent the rowid index that is part of every table.  */
97112   assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
97113
97114   /* Match terms of the ORDER BY clause against columns of
97115   ** the index.
97116   **
97117   ** Note that indices have pIdx->nColumn regular columns plus
97118   ** one additional column containing the rowid.  The rowid column
97119   ** of the index is also allowed to match against the ORDER BY
97120   ** clause.
97121   */
97122   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
97123     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
97124     CollSeq *pColl;    /* The collating sequence of pExpr */
97125     int termSortOrder; /* Sort order for this term */
97126     int iColumn;       /* The i-th column of the index.  -1 for rowid */
97127     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
97128     const char *zColl; /* Name of the collating sequence for i-th index term */
97129
97130     pExpr = pTerm->pExpr;
97131     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
97132       /* Can not use an index sort on anything that is not a column in the
97133       ** left-most table of the FROM clause */
97134       break;
97135     }
97136     pColl = sqlite3ExprCollSeq(pParse, pExpr);
97137     if( !pColl ){
97138       pColl = db->pDfltColl;
97139     }
97140     if( pIdx->zName && i<pIdx->nColumn ){
97141       iColumn = pIdx->aiColumn[i];
97142       if( iColumn==pIdx->pTable->iPKey ){
97143         iColumn = -1;
97144       }
97145       iSortOrder = pIdx->aSortOrder[i];
97146       zColl = pIdx->azColl[i];
97147     }else{
97148       iColumn = -1;
97149       iSortOrder = 0;
97150       zColl = pColl->zName;
97151     }
97152     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
97153       /* Term j of the ORDER BY clause does not match column i of the index */
97154       if( i<nEqCol ){
97155         /* If an index column that is constrained by == fails to match an
97156         ** ORDER BY term, that is OK.  Just ignore that column of the index
97157         */
97158         continue;
97159       }else if( i==pIdx->nColumn ){
97160         /* Index column i is the rowid.  All other terms match. */
97161         break;
97162       }else{
97163         /* If an index column fails to match and is not constrained by ==
97164         ** then the index cannot satisfy the ORDER BY constraint.
97165         */
97166         return 0;
97167       }
97168     }
97169     assert( pIdx->aSortOrder!=0 || iColumn==-1 );
97170     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
97171     assert( iSortOrder==0 || iSortOrder==1 );
97172     termSortOrder = iSortOrder ^ pTerm->sortOrder;
97173     if( i>nEqCol ){
97174       if( termSortOrder!=sortOrder ){
97175         /* Indices can only be used if all ORDER BY terms past the
97176         ** equality constraints are all either DESC or ASC. */
97177         return 0;
97178       }
97179     }else{
97180       sortOrder = termSortOrder;
97181     }
97182     j++;
97183     pTerm++;
97184     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
97185       /* If the indexed column is the primary key and everything matches
97186       ** so far and none of the ORDER BY terms to the right reference other
97187       ** tables in the join, then we are assured that the index can be used 
97188       ** to sort because the primary key is unique and so none of the other
97189       ** columns will make any difference
97190       */
97191       j = nTerm;
97192     }
97193   }
97194
97195   *pbRev = sortOrder!=0;
97196   if( j>=nTerm ){
97197     /* All terms of the ORDER BY clause are covered by this index so
97198     ** this index can be used for sorting. */
97199     return 1;
97200   }
97201   if( pIdx->onError!=OE_None && i==pIdx->nColumn
97202       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
97203     /* All terms of this index match some prefix of the ORDER BY clause
97204     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
97205     ** clause reference other tables in a join.  If this is all true then
97206     ** the order by clause is superfluous. */
97207     return 1;
97208   }
97209   return 0;
97210 }
97211
97212 /*
97213 ** Prepare a crude estimate of the logarithm of the input value.
97214 ** The results need not be exact.  This is only used for estimating
97215 ** the total cost of performing operations with O(logN) or O(NlogN)
97216 ** complexity.  Because N is just a guess, it is no great tragedy if
97217 ** logN is a little off.
97218 */
97219 static double estLog(double N){
97220   double logN = 1;
97221   double x = 10;
97222   while( N>x ){
97223     logN += 1;
97224     x *= 10;
97225   }
97226   return logN;
97227 }
97228
97229 /*
97230 ** Two routines for printing the content of an sqlite3_index_info
97231 ** structure.  Used for testing and debugging only.  If neither
97232 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
97233 ** are no-ops.
97234 */
97235 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
97236 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
97237   int i;
97238   if( !sqlite3WhereTrace ) return;
97239   for(i=0; i<p->nConstraint; i++){
97240     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
97241        i,
97242        p->aConstraint[i].iColumn,
97243        p->aConstraint[i].iTermOffset,
97244        p->aConstraint[i].op,
97245        p->aConstraint[i].usable);
97246   }
97247   for(i=0; i<p->nOrderBy; i++){
97248     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
97249        i,
97250        p->aOrderBy[i].iColumn,
97251        p->aOrderBy[i].desc);
97252   }
97253 }
97254 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
97255   int i;
97256   if( !sqlite3WhereTrace ) return;
97257   for(i=0; i<p->nConstraint; i++){
97258     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
97259        i,
97260        p->aConstraintUsage[i].argvIndex,
97261        p->aConstraintUsage[i].omit);
97262   }
97263   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
97264   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
97265   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
97266   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
97267 }
97268 #else
97269 #define TRACE_IDX_INPUTS(A)
97270 #define TRACE_IDX_OUTPUTS(A)
97271 #endif
97272
97273 /* 
97274 ** Required because bestIndex() is called by bestOrClauseIndex() 
97275 */
97276 static void bestIndex(
97277     Parse*, WhereClause*, struct SrcList_item*,
97278     Bitmask, Bitmask, ExprList*, WhereCost*);
97279
97280 /*
97281 ** This routine attempts to find an scanning strategy that can be used 
97282 ** to optimize an 'OR' expression that is part of a WHERE clause. 
97283 **
97284 ** The table associated with FROM clause term pSrc may be either a
97285 ** regular B-Tree table or a virtual table.
97286 */
97287 static void bestOrClauseIndex(
97288   Parse *pParse,              /* The parsing context */
97289   WhereClause *pWC,           /* The WHERE clause */
97290   struct SrcList_item *pSrc,  /* The FROM clause term to search */
97291   Bitmask notReady,           /* Mask of cursors not available for indexing */
97292   Bitmask notValid,           /* Cursors not available for any purpose */
97293   ExprList *pOrderBy,         /* The ORDER BY clause */
97294   WhereCost *pCost            /* Lowest cost query plan */
97295 ){
97296 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
97297   const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
97298   const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
97299   WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
97300   WhereTerm *pTerm;                 /* A single term of the WHERE clause */
97301
97302   /* No OR-clause optimization allowed if the INDEXED BY or NOT INDEXED clauses
97303   ** are used */
97304   if( pSrc->notIndexed || pSrc->pIndex!=0 ){
97305     return;
97306   }
97307
97308   /* Search the WHERE clause terms for a usable WO_OR term. */
97309   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
97310     if( pTerm->eOperator==WO_OR 
97311      && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
97312      && (pTerm->u.pOrInfo->indexable & maskSrc)!=0 
97313     ){
97314       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
97315       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
97316       WhereTerm *pOrTerm;
97317       int flags = WHERE_MULTI_OR;
97318       double rTotal = 0;
97319       double nRow = 0;
97320       Bitmask used = 0;
97321
97322       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
97323         WhereCost sTermCost;
97324         WHERETRACE(("... Multi-index OR testing for term %d of %d....\n", 
97325           (pOrTerm - pOrWC->a), (pTerm - pWC->a)
97326         ));
97327         if( pOrTerm->eOperator==WO_AND ){
97328           WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
97329           bestIndex(pParse, pAndWC, pSrc, notReady, notValid, 0, &sTermCost);
97330         }else if( pOrTerm->leftCursor==iCur ){
97331           WhereClause tempWC;
97332           tempWC.pParse = pWC->pParse;
97333           tempWC.pMaskSet = pWC->pMaskSet;
97334           tempWC.op = TK_AND;
97335           tempWC.a = pOrTerm;
97336           tempWC.nTerm = 1;
97337           bestIndex(pParse, &tempWC, pSrc, notReady, notValid, 0, &sTermCost);
97338         }else{
97339           continue;
97340         }
97341         rTotal += sTermCost.rCost;
97342         nRow += sTermCost.plan.nRow;
97343         used |= sTermCost.used;
97344         if( rTotal>=pCost->rCost ) break;
97345       }
97346
97347       /* If there is an ORDER BY clause, increase the scan cost to account 
97348       ** for the cost of the sort. */
97349       if( pOrderBy!=0 ){
97350         WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
97351                     rTotal, rTotal+nRow*estLog(nRow)));
97352         rTotal += nRow*estLog(nRow);
97353       }
97354
97355       /* If the cost of scanning using this OR term for optimization is
97356       ** less than the current cost stored in pCost, replace the contents
97357       ** of pCost. */
97358       WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
97359       if( rTotal<pCost->rCost ){
97360         pCost->rCost = rTotal;
97361         pCost->used = used;
97362         pCost->plan.nRow = nRow;
97363         pCost->plan.wsFlags = flags;
97364         pCost->plan.u.pTerm = pTerm;
97365       }
97366     }
97367   }
97368 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
97369 }
97370
97371 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
97372 /*
97373 ** Return TRUE if the WHERE clause term pTerm is of a form where it
97374 ** could be used with an index to access pSrc, assuming an appropriate
97375 ** index existed.
97376 */
97377 static int termCanDriveIndex(
97378   WhereTerm *pTerm,              /* WHERE clause term to check */
97379   struct SrcList_item *pSrc,     /* Table we are trying to access */
97380   Bitmask notReady               /* Tables in outer loops of the join */
97381 ){
97382   char aff;
97383   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
97384   if( pTerm->eOperator!=WO_EQ ) return 0;
97385   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
97386   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
97387   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
97388   return 1;
97389 }
97390 #endif
97391
97392 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
97393 /*
97394 ** If the query plan for pSrc specified in pCost is a full table scan
97395 ** and indexing is allows (if there is no NOT INDEXED clause) and it
97396 ** possible to construct a transient index that would perform better
97397 ** than a full table scan even when the cost of constructing the index
97398 ** is taken into account, then alter the query plan to use the
97399 ** transient index.
97400 */
97401 static void bestAutomaticIndex(
97402   Parse *pParse,              /* The parsing context */
97403   WhereClause *pWC,           /* The WHERE clause */
97404   struct SrcList_item *pSrc,  /* The FROM clause term to search */
97405   Bitmask notReady,           /* Mask of cursors that are not available */
97406   WhereCost *pCost            /* Lowest cost query plan */
97407 ){
97408   double nTableRow;           /* Rows in the input table */
97409   double logN;                /* log(nTableRow) */
97410   double costTempIdx;         /* per-query cost of the transient index */
97411   WhereTerm *pTerm;           /* A single term of the WHERE clause */
97412   WhereTerm *pWCEnd;          /* End of pWC->a[] */
97413   Table *pTable;              /* Table tht might be indexed */
97414
97415   if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
97416     /* Automatic indices are disabled at run-time */
97417     return;
97418   }
97419   if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){
97420     /* We already have some kind of index in use for this query. */
97421     return;
97422   }
97423   if( pSrc->notIndexed ){
97424     /* The NOT INDEXED clause appears in the SQL. */
97425     return;
97426   }
97427
97428   assert( pParse->nQueryLoop >= (double)1 );
97429   pTable = pSrc->pTab;
97430   nTableRow = pTable->nRowEst;
97431   logN = estLog(nTableRow);
97432   costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
97433   if( costTempIdx>=pCost->rCost ){
97434     /* The cost of creating the transient table would be greater than
97435     ** doing the full table scan */
97436     return;
97437   }
97438
97439   /* Search for any equality comparison term */
97440   pWCEnd = &pWC->a[pWC->nTerm];
97441   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
97442     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
97443       WHERETRACE(("auto-index reduces cost from %.2f to %.2f\n",
97444                     pCost->rCost, costTempIdx));
97445       pCost->rCost = costTempIdx;
97446       pCost->plan.nRow = logN + 1;
97447       pCost->plan.wsFlags = WHERE_TEMP_INDEX;
97448       pCost->used = pTerm->prereqRight;
97449       break;
97450     }
97451   }
97452 }
97453 #else
97454 # define bestAutomaticIndex(A,B,C,D,E)  /* no-op */
97455 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
97456
97457
97458 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
97459 /*
97460 ** Generate code to construct the Index object for an automatic index
97461 ** and to set up the WhereLevel object pLevel so that the code generator
97462 ** makes use of the automatic index.
97463 */
97464 static void constructAutomaticIndex(
97465   Parse *pParse,              /* The parsing context */
97466   WhereClause *pWC,           /* The WHERE clause */
97467   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
97468   Bitmask notReady,           /* Mask of cursors that are not available */
97469   WhereLevel *pLevel          /* Write new index here */
97470 ){
97471   int nColumn;                /* Number of columns in the constructed index */
97472   WhereTerm *pTerm;           /* A single term of the WHERE clause */
97473   WhereTerm *pWCEnd;          /* End of pWC->a[] */
97474   int nByte;                  /* Byte of memory needed for pIdx */
97475   Index *pIdx;                /* Object describing the transient index */
97476   Vdbe *v;                    /* Prepared statement under construction */
97477   int regIsInit;              /* Register set by initialization */
97478   int addrInit;               /* Address of the initialization bypass jump */
97479   Table *pTable;              /* The table being indexed */
97480   KeyInfo *pKeyinfo;          /* Key information for the index */   
97481   int addrTop;                /* Top of the index fill loop */
97482   int regRecord;              /* Register holding an index record */
97483   int n;                      /* Column counter */
97484   int i;                      /* Loop counter */
97485   int mxBitCol;               /* Maximum column in pSrc->colUsed */
97486   CollSeq *pColl;             /* Collating sequence to on a column */
97487   Bitmask idxCols;            /* Bitmap of columns used for indexing */
97488   Bitmask extraCols;          /* Bitmap of additional columns */
97489
97490   /* Generate code to skip over the creation and initialization of the
97491   ** transient index on 2nd and subsequent iterations of the loop. */
97492   v = pParse->pVdbe;
97493   assert( v!=0 );
97494   regIsInit = ++pParse->nMem;
97495   addrInit = sqlite3VdbeAddOp1(v, OP_If, regIsInit);
97496   sqlite3VdbeAddOp2(v, OP_Integer, 1, regIsInit);
97497
97498   /* Count the number of columns that will be added to the index
97499   ** and used to match WHERE clause constraints */
97500   nColumn = 0;
97501   pTable = pSrc->pTab;
97502   pWCEnd = &pWC->a[pWC->nTerm];
97503   idxCols = 0;
97504   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
97505     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
97506       int iCol = pTerm->u.leftColumn;
97507       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
97508       testcase( iCol==BMS );
97509       testcase( iCol==BMS-1 );
97510       if( (idxCols & cMask)==0 ){
97511         nColumn++;
97512         idxCols |= cMask;
97513       }
97514     }
97515   }
97516   assert( nColumn>0 );
97517   pLevel->plan.nEq = nColumn;
97518
97519   /* Count the number of additional columns needed to create a
97520   ** covering index.  A "covering index" is an index that contains all
97521   ** columns that are needed by the query.  With a covering index, the
97522   ** original table never needs to be accessed.  Automatic indices must
97523   ** be a covering index because the index will not be updated if the
97524   ** original table changes and the index and table cannot both be used
97525   ** if they go out of sync.
97526   */
97527   extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
97528   mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
97529   testcase( pTable->nCol==BMS-1 );
97530   testcase( pTable->nCol==BMS-2 );
97531   for(i=0; i<mxBitCol; i++){
97532     if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
97533   }
97534   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
97535     nColumn += pTable->nCol - BMS + 1;
97536   }
97537   pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
97538
97539   /* Construct the Index object to describe this index */
97540   nByte = sizeof(Index);
97541   nByte += nColumn*sizeof(int);     /* Index.aiColumn */
97542   nByte += nColumn*sizeof(char*);   /* Index.azColl */
97543   nByte += nColumn;                 /* Index.aSortOrder */
97544   pIdx = sqlite3DbMallocZero(pParse->db, nByte);
97545   if( pIdx==0 ) return;
97546   pLevel->plan.u.pIdx = pIdx;
97547   pIdx->azColl = (char**)&pIdx[1];
97548   pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
97549   pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
97550   pIdx->zName = "auto-index";
97551   pIdx->nColumn = nColumn;
97552   pIdx->pTable = pTable;
97553   n = 0;
97554   idxCols = 0;
97555   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
97556     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
97557       int iCol = pTerm->u.leftColumn;
97558       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
97559       if( (idxCols & cMask)==0 ){
97560         Expr *pX = pTerm->pExpr;
97561         idxCols |= cMask;
97562         pIdx->aiColumn[n] = pTerm->u.leftColumn;
97563         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
97564         pIdx->azColl[n] = pColl->zName;
97565         n++;
97566       }
97567     }
97568   }
97569   assert( (u32)n==pLevel->plan.nEq );
97570
97571   /* Add additional columns needed to make the automatic index into
97572   ** a covering index */
97573   for(i=0; i<mxBitCol; i++){
97574     if( extraCols & (((Bitmask)1)<<i) ){
97575       pIdx->aiColumn[n] = i;
97576       pIdx->azColl[n] = "BINARY";
97577       n++;
97578     }
97579   }
97580   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
97581     for(i=BMS-1; i<pTable->nCol; i++){
97582       pIdx->aiColumn[n] = i;
97583       pIdx->azColl[n] = "BINARY";
97584       n++;
97585     }
97586   }
97587   assert( n==nColumn );
97588
97589   /* Create the automatic index */
97590   pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
97591   assert( pLevel->iIdxCur>=0 );
97592   sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
97593                     (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
97594   VdbeComment((v, "for %s", pTable->zName));
97595
97596   /* Fill the automatic index with content */
97597   addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
97598   regRecord = sqlite3GetTempReg(pParse);
97599   sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
97600   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
97601   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
97602   sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
97603   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
97604   sqlite3VdbeJumpHere(v, addrTop);
97605   sqlite3ReleaseTempReg(pParse, regRecord);
97606   
97607   /* Jump here when skipping the initialization */
97608   sqlite3VdbeJumpHere(v, addrInit);
97609 }
97610 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
97611
97612 #ifndef SQLITE_OMIT_VIRTUALTABLE
97613 /*
97614 ** Allocate and populate an sqlite3_index_info structure. It is the 
97615 ** responsibility of the caller to eventually release the structure
97616 ** by passing the pointer returned by this function to sqlite3_free().
97617 */
97618 static sqlite3_index_info *allocateIndexInfo(
97619   Parse *pParse, 
97620   WhereClause *pWC,
97621   struct SrcList_item *pSrc,
97622   ExprList *pOrderBy
97623 ){
97624   int i, j;
97625   int nTerm;
97626   struct sqlite3_index_constraint *pIdxCons;
97627   struct sqlite3_index_orderby *pIdxOrderBy;
97628   struct sqlite3_index_constraint_usage *pUsage;
97629   WhereTerm *pTerm;
97630   int nOrderBy;
97631   sqlite3_index_info *pIdxInfo;
97632
97633   WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
97634
97635   /* Count the number of possible WHERE clause constraints referring
97636   ** to this virtual table */
97637   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
97638     if( pTerm->leftCursor != pSrc->iCursor ) continue;
97639     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
97640     testcase( pTerm->eOperator==WO_IN );
97641     testcase( pTerm->eOperator==WO_ISNULL );
97642     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
97643     nTerm++;
97644   }
97645
97646   /* If the ORDER BY clause contains only columns in the current 
97647   ** virtual table then allocate space for the aOrderBy part of
97648   ** the sqlite3_index_info structure.
97649   */
97650   nOrderBy = 0;
97651   if( pOrderBy ){
97652     for(i=0; i<pOrderBy->nExpr; i++){
97653       Expr *pExpr = pOrderBy->a[i].pExpr;
97654       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
97655     }
97656     if( i==pOrderBy->nExpr ){
97657       nOrderBy = pOrderBy->nExpr;
97658     }
97659   }
97660
97661   /* Allocate the sqlite3_index_info structure
97662   */
97663   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
97664                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
97665                            + sizeof(*pIdxOrderBy)*nOrderBy );
97666   if( pIdxInfo==0 ){
97667     sqlite3ErrorMsg(pParse, "out of memory");
97668     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
97669     return 0;
97670   }
97671
97672   /* Initialize the structure.  The sqlite3_index_info structure contains
97673   ** many fields that are declared "const" to prevent xBestIndex from
97674   ** changing them.  We have to do some funky casting in order to
97675   ** initialize those fields.
97676   */
97677   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
97678   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
97679   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
97680   *(int*)&pIdxInfo->nConstraint = nTerm;
97681   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
97682   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
97683   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
97684   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
97685                                                                    pUsage;
97686
97687   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
97688     if( pTerm->leftCursor != pSrc->iCursor ) continue;
97689     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
97690     testcase( pTerm->eOperator==WO_IN );
97691     testcase( pTerm->eOperator==WO_ISNULL );
97692     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
97693     pIdxCons[j].iColumn = pTerm->u.leftColumn;
97694     pIdxCons[j].iTermOffset = i;
97695     pIdxCons[j].op = (u8)pTerm->eOperator;
97696     /* The direct assignment in the previous line is possible only because
97697     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
97698     ** following asserts verify this fact. */
97699     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
97700     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
97701     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
97702     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
97703     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
97704     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
97705     assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
97706     j++;
97707   }
97708   for(i=0; i<nOrderBy; i++){
97709     Expr *pExpr = pOrderBy->a[i].pExpr;
97710     pIdxOrderBy[i].iColumn = pExpr->iColumn;
97711     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
97712   }
97713
97714   return pIdxInfo;
97715 }
97716
97717 /*
97718 ** The table object reference passed as the second argument to this function
97719 ** must represent a virtual table. This function invokes the xBestIndex()
97720 ** method of the virtual table with the sqlite3_index_info pointer passed
97721 ** as the argument.
97722 **
97723 ** If an error occurs, pParse is populated with an error message and a
97724 ** non-zero value is returned. Otherwise, 0 is returned and the output
97725 ** part of the sqlite3_index_info structure is left populated.
97726 **
97727 ** Whether or not an error is returned, it is the responsibility of the
97728 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
97729 ** that this is required.
97730 */
97731 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
97732   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
97733   int i;
97734   int rc;
97735
97736   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
97737   TRACE_IDX_INPUTS(p);
97738   rc = pVtab->pModule->xBestIndex(pVtab, p);
97739   TRACE_IDX_OUTPUTS(p);
97740
97741   if( rc!=SQLITE_OK ){
97742     if( rc==SQLITE_NOMEM ){
97743       pParse->db->mallocFailed = 1;
97744     }else if( !pVtab->zErrMsg ){
97745       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
97746     }else{
97747       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
97748     }
97749   }
97750   sqlite3_free(pVtab->zErrMsg);
97751   pVtab->zErrMsg = 0;
97752
97753   for(i=0; i<p->nConstraint; i++){
97754     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
97755       sqlite3ErrorMsg(pParse, 
97756           "table %s: xBestIndex returned an invalid plan", pTab->zName);
97757     }
97758   }
97759
97760   return pParse->nErr;
97761 }
97762
97763
97764 /*
97765 ** Compute the best index for a virtual table.
97766 **
97767 ** The best index is computed by the xBestIndex method of the virtual
97768 ** table module.  This routine is really just a wrapper that sets up
97769 ** the sqlite3_index_info structure that is used to communicate with
97770 ** xBestIndex.
97771 **
97772 ** In a join, this routine might be called multiple times for the
97773 ** same virtual table.  The sqlite3_index_info structure is created
97774 ** and initialized on the first invocation and reused on all subsequent
97775 ** invocations.  The sqlite3_index_info structure is also used when
97776 ** code is generated to access the virtual table.  The whereInfoDelete() 
97777 ** routine takes care of freeing the sqlite3_index_info structure after
97778 ** everybody has finished with it.
97779 */
97780 static void bestVirtualIndex(
97781   Parse *pParse,                  /* The parsing context */
97782   WhereClause *pWC,               /* The WHERE clause */
97783   struct SrcList_item *pSrc,      /* The FROM clause term to search */
97784   Bitmask notReady,               /* Mask of cursors not available for index */
97785   Bitmask notValid,               /* Cursors not valid for any purpose */
97786   ExprList *pOrderBy,             /* The order by clause */
97787   WhereCost *pCost,               /* Lowest cost query plan */
97788   sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
97789 ){
97790   Table *pTab = pSrc->pTab;
97791   sqlite3_index_info *pIdxInfo;
97792   struct sqlite3_index_constraint *pIdxCons;
97793   struct sqlite3_index_constraint_usage *pUsage;
97794   WhereTerm *pTerm;
97795   int i, j;
97796   int nOrderBy;
97797   double rCost;
97798
97799   /* Make sure wsFlags is initialized to some sane value. Otherwise, if the 
97800   ** malloc in allocateIndexInfo() fails and this function returns leaving
97801   ** wsFlags in an uninitialized state, the caller may behave unpredictably.
97802   */
97803   memset(pCost, 0, sizeof(*pCost));
97804   pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
97805
97806   /* If the sqlite3_index_info structure has not been previously
97807   ** allocated and initialized, then allocate and initialize it now.
97808   */
97809   pIdxInfo = *ppIdxInfo;
97810   if( pIdxInfo==0 ){
97811     *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
97812   }
97813   if( pIdxInfo==0 ){
97814     return;
97815   }
97816
97817   /* At this point, the sqlite3_index_info structure that pIdxInfo points
97818   ** to will have been initialized, either during the current invocation or
97819   ** during some prior invocation.  Now we just have to customize the
97820   ** details of pIdxInfo for the current invocation and pass it to
97821   ** xBestIndex.
97822   */
97823
97824   /* The module name must be defined. Also, by this point there must
97825   ** be a pointer to an sqlite3_vtab structure. Otherwise
97826   ** sqlite3ViewGetColumnNames() would have picked up the error. 
97827   */
97828   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
97829   assert( sqlite3GetVTable(pParse->db, pTab) );
97830
97831   /* Set the aConstraint[].usable fields and initialize all 
97832   ** output variables to zero.
97833   **
97834   ** aConstraint[].usable is true for constraints where the right-hand
97835   ** side contains only references to tables to the left of the current
97836   ** table.  In other words, if the constraint is of the form:
97837   **
97838   **           column = expr
97839   **
97840   ** and we are evaluating a join, then the constraint on column is 
97841   ** only valid if all tables referenced in expr occur to the left
97842   ** of the table containing column.
97843   **
97844   ** The aConstraints[] array contains entries for all constraints
97845   ** on the current table.  That way we only have to compute it once
97846   ** even though we might try to pick the best index multiple times.
97847   ** For each attempt at picking an index, the order of tables in the
97848   ** join might be different so we have to recompute the usable flag
97849   ** each time.
97850   */
97851   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
97852   pUsage = pIdxInfo->aConstraintUsage;
97853   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
97854     j = pIdxCons->iTermOffset;
97855     pTerm = &pWC->a[j];
97856     pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
97857   }
97858   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
97859   if( pIdxInfo->needToFreeIdxStr ){
97860     sqlite3_free(pIdxInfo->idxStr);
97861   }
97862   pIdxInfo->idxStr = 0;
97863   pIdxInfo->idxNum = 0;
97864   pIdxInfo->needToFreeIdxStr = 0;
97865   pIdxInfo->orderByConsumed = 0;
97866   /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
97867   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
97868   nOrderBy = pIdxInfo->nOrderBy;
97869   if( !pOrderBy ){
97870     pIdxInfo->nOrderBy = 0;
97871   }
97872
97873   if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
97874     return;
97875   }
97876
97877   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
97878   for(i=0; i<pIdxInfo->nConstraint; i++){
97879     if( pUsage[i].argvIndex>0 ){
97880       pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
97881     }
97882   }
97883
97884   /* If there is an ORDER BY clause, and the selected virtual table index
97885   ** does not satisfy it, increase the cost of the scan accordingly. This
97886   ** matches the processing for non-virtual tables in bestBtreeIndex().
97887   */
97888   rCost = pIdxInfo->estimatedCost;
97889   if( pOrderBy && pIdxInfo->orderByConsumed==0 ){
97890     rCost += estLog(rCost)*rCost;
97891   }
97892
97893   /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
97894   ** inital value of lowestCost in this loop. If it is, then the
97895   ** (cost<lowestCost) test below will never be true.
97896   ** 
97897   ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT 
97898   ** is defined.
97899   */
97900   if( (SQLITE_BIG_DBL/((double)2))<rCost ){
97901     pCost->rCost = (SQLITE_BIG_DBL/((double)2));
97902   }else{
97903     pCost->rCost = rCost;
97904   }
97905   pCost->plan.u.pVtabIdx = pIdxInfo;
97906   if( pIdxInfo->orderByConsumed ){
97907     pCost->plan.wsFlags |= WHERE_ORDERBY;
97908   }
97909   pCost->plan.nEq = 0;
97910   pIdxInfo->nOrderBy = nOrderBy;
97911
97912   /* Try to find a more efficient access pattern by using multiple indexes
97913   ** to optimize an OR expression within the WHERE clause. 
97914   */
97915   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
97916 }
97917 #endif /* SQLITE_OMIT_VIRTUALTABLE */
97918
97919 /*
97920 ** Argument pIdx is a pointer to an index structure that has an array of
97921 ** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column
97922 ** stored in Index.aSample. The domain of values stored in said column
97923 ** may be thought of as divided into (SQLITE_INDEX_SAMPLES+1) regions.
97924 ** Region 0 contains all values smaller than the first sample value. Region
97925 ** 1 contains values larger than or equal to the value of the first sample,
97926 ** but smaller than the value of the second. And so on.
97927 **
97928 ** If successful, this function determines which of the regions value 
97929 ** pVal lies in, sets *piRegion to the region index (a value between 0
97930 ** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK.
97931 ** Or, if an OOM occurs while converting text values between encodings,
97932 ** SQLITE_NOMEM is returned and *piRegion is undefined.
97933 */
97934 #ifdef SQLITE_ENABLE_STAT2
97935 static int whereRangeRegion(
97936   Parse *pParse,              /* Database connection */
97937   Index *pIdx,                /* Index to consider domain of */
97938   sqlite3_value *pVal,        /* Value to consider */
97939   int *piRegion               /* OUT: Region of domain in which value lies */
97940 ){
97941   if( ALWAYS(pVal) ){
97942     IndexSample *aSample = pIdx->aSample;
97943     int i = 0;
97944     int eType = sqlite3_value_type(pVal);
97945
97946     if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
97947       double r = sqlite3_value_double(pVal);
97948       for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
97949         if( aSample[i].eType==SQLITE_NULL ) continue;
97950         if( aSample[i].eType>=SQLITE_TEXT || aSample[i].u.r>r ) break;
97951       }
97952     }else{ 
97953       sqlite3 *db = pParse->db;
97954       CollSeq *pColl;
97955       const u8 *z;
97956       int n;
97957
97958       /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */
97959       assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
97960
97961       if( eType==SQLITE_BLOB ){
97962         z = (const u8 *)sqlite3_value_blob(pVal);
97963         pColl = db->pDfltColl;
97964         assert( pColl->enc==SQLITE_UTF8 );
97965       }else{
97966         pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
97967         if( pColl==0 ){
97968           sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
97969                           *pIdx->azColl);
97970           return SQLITE_ERROR;
97971         }
97972         z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
97973         if( !z ){
97974           return SQLITE_NOMEM;
97975         }
97976         assert( z && pColl && pColl->xCmp );
97977       }
97978       n = sqlite3ValueBytes(pVal, pColl->enc);
97979
97980       for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
97981         int r;
97982         int eSampletype = aSample[i].eType;
97983         if( eSampletype==SQLITE_NULL || eSampletype<eType ) continue;
97984         if( (eSampletype!=eType) ) break;
97985 #ifndef SQLITE_OMIT_UTF16
97986         if( pColl->enc!=SQLITE_UTF8 ){
97987           int nSample;
97988           char *zSample = sqlite3Utf8to16(
97989               db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
97990           );
97991           if( !zSample ){
97992             assert( db->mallocFailed );
97993             return SQLITE_NOMEM;
97994           }
97995           r = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
97996           sqlite3DbFree(db, zSample);
97997         }else
97998 #endif
97999         {
98000           r = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
98001         }
98002         if( r>0 ) break;
98003       }
98004     }
98005
98006     assert( i>=0 && i<=SQLITE_INDEX_SAMPLES );
98007     *piRegion = i;
98008   }
98009   return SQLITE_OK;
98010 }
98011 #endif   /* #ifdef SQLITE_ENABLE_STAT2 */
98012
98013 /*
98014 ** If expression pExpr represents a literal value, set *pp to point to
98015 ** an sqlite3_value structure containing the same value, with affinity
98016 ** aff applied to it, before returning. It is the responsibility of the 
98017 ** caller to eventually release this structure by passing it to 
98018 ** sqlite3ValueFree().
98019 **
98020 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
98021 ** is an SQL variable that currently has a non-NULL value bound to it,
98022 ** create an sqlite3_value structure containing this value, again with
98023 ** affinity aff applied to it, instead.
98024 **
98025 ** If neither of the above apply, set *pp to NULL.
98026 **
98027 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
98028 */
98029 #ifdef SQLITE_ENABLE_STAT2
98030 static int valueFromExpr(
98031   Parse *pParse, 
98032   Expr *pExpr, 
98033   u8 aff, 
98034   sqlite3_value **pp
98035 ){
98036   if( pExpr->op==TK_VARIABLE
98037    || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
98038   ){
98039     int iVar = pExpr->iColumn;
98040     sqlite3VdbeSetVarmask(pParse->pVdbe, iVar); /* IMP: R-23257-02778 */
98041     *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
98042     return SQLITE_OK;
98043   }
98044   return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
98045 }
98046 #endif
98047
98048 /*
98049 ** This function is used to estimate the number of rows that will be visited
98050 ** by scanning an index for a range of values. The range may have an upper
98051 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
98052 ** and lower bounds are represented by pLower and pUpper respectively. For
98053 ** example, assuming that index p is on t1(a):
98054 **
98055 **   ... FROM t1 WHERE a > ? AND a < ? ...
98056 **                    |_____|   |_____|
98057 **                       |         |
98058 **                     pLower    pUpper
98059 **
98060 ** If either of the upper or lower bound is not present, then NULL is passed in
98061 ** place of the corresponding WhereTerm.
98062 **
98063 ** The nEq parameter is passed the index of the index column subject to the
98064 ** range constraint. Or, equivalently, the number of equality constraints
98065 ** optimized by the proposed index scan. For example, assuming index p is
98066 ** on t1(a, b), and the SQL query is:
98067 **
98068 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
98069 **
98070 ** then nEq should be passed the value 1 (as the range restricted column,
98071 ** b, is the second left-most column of the index). Or, if the query is:
98072 **
98073 **   ... FROM t1 WHERE a > ? AND a < ? ...
98074 **
98075 ** then nEq should be passed 0.
98076 **
98077 ** The returned value is an integer between 1 and 100, inclusive. A return
98078 ** value of 1 indicates that the proposed range scan is expected to visit
98079 ** approximately 1/100th (1%) of the rows selected by the nEq equality
98080 ** constraints (if any). A return value of 100 indicates that it is expected
98081 ** that the range scan will visit every row (100%) selected by the equality
98082 ** constraints.
98083 **
98084 ** In the absence of sqlite_stat2 ANALYZE data, each range inequality
98085 ** reduces the search space by 2/3rds.  Hence a single constraint (x>?)
98086 ** results in a return of 33 and a range constraint (x>? AND x<?) results
98087 ** in a return of 11.
98088 */
98089 static int whereRangeScanEst(
98090   Parse *pParse,       /* Parsing & code generating context */
98091   Index *p,            /* The index containing the range-compared column; "x" */
98092   int nEq,             /* index into p->aCol[] of the range-compared column */
98093   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
98094   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
98095   int *piEst           /* OUT: Return value */
98096 ){
98097   int rc = SQLITE_OK;
98098
98099 #ifdef SQLITE_ENABLE_STAT2
98100
98101   if( nEq==0 && p->aSample ){
98102     sqlite3_value *pLowerVal = 0;
98103     sqlite3_value *pUpperVal = 0;
98104     int iEst;
98105     int iLower = 0;
98106     int iUpper = SQLITE_INDEX_SAMPLES;
98107     u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
98108
98109     if( pLower ){
98110       Expr *pExpr = pLower->pExpr->pRight;
98111       rc = valueFromExpr(pParse, pExpr, aff, &pLowerVal);
98112     }
98113     if( rc==SQLITE_OK && pUpper ){
98114       Expr *pExpr = pUpper->pExpr->pRight;
98115       rc = valueFromExpr(pParse, pExpr, aff, &pUpperVal);
98116     }
98117
98118     if( rc!=SQLITE_OK || (pLowerVal==0 && pUpperVal==0) ){
98119       sqlite3ValueFree(pLowerVal);
98120       sqlite3ValueFree(pUpperVal);
98121       goto range_est_fallback;
98122     }else if( pLowerVal==0 ){
98123       rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
98124       if( pLower ) iLower = iUpper/2;
98125     }else if( pUpperVal==0 ){
98126       rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
98127       if( pUpper ) iUpper = (iLower + SQLITE_INDEX_SAMPLES + 1)/2;
98128     }else{
98129       rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
98130       if( rc==SQLITE_OK ){
98131         rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
98132       }
98133     }
98134
98135     iEst = iUpper - iLower;
98136     testcase( iEst==SQLITE_INDEX_SAMPLES );
98137     assert( iEst<=SQLITE_INDEX_SAMPLES );
98138     if( iEst<1 ){
98139       iEst = 1;
98140     }
98141
98142     sqlite3ValueFree(pLowerVal);
98143     sqlite3ValueFree(pUpperVal);
98144     *piEst = (iEst * 100)/SQLITE_INDEX_SAMPLES;
98145     return rc;
98146   }
98147 range_est_fallback:
98148 #else
98149   UNUSED_PARAMETER(pParse);
98150   UNUSED_PARAMETER(p);
98151   UNUSED_PARAMETER(nEq);
98152 #endif
98153   assert( pLower || pUpper );
98154   if( pLower && pUpper ){
98155     *piEst = 11;
98156   }else{
98157     *piEst = 33;
98158   }
98159   return rc;
98160 }
98161
98162
98163 /*
98164 ** Find the query plan for accessing a particular table.  Write the
98165 ** best query plan and its cost into the WhereCost object supplied as the
98166 ** last parameter.
98167 **
98168 ** The lowest cost plan wins.  The cost is an estimate of the amount of
98169 ** CPU and disk I/O need to process the request using the selected plan.
98170 ** Factors that influence cost include:
98171 **
98172 **    *  The estimated number of rows that will be retrieved.  (The
98173 **       fewer the better.)
98174 **
98175 **    *  Whether or not sorting must occur.
98176 **
98177 **    *  Whether or not there must be separate lookups in the
98178 **       index and in the main table.
98179 **
98180 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
98181 ** the SQL statement, then this function only considers plans using the 
98182 ** named index. If no such plan is found, then the returned cost is
98183 ** SQLITE_BIG_DBL. If a plan is found that uses the named index, 
98184 ** then the cost is calculated in the usual way.
98185 **
98186 ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table 
98187 ** in the SELECT statement, then no indexes are considered. However, the 
98188 ** selected plan may still take advantage of the tables built-in rowid
98189 ** index.
98190 */
98191 static void bestBtreeIndex(
98192   Parse *pParse,              /* The parsing context */
98193   WhereClause *pWC,           /* The WHERE clause */
98194   struct SrcList_item *pSrc,  /* The FROM clause term to search */
98195   Bitmask notReady,           /* Mask of cursors not available for indexing */
98196   Bitmask notValid,           /* Cursors not available for any purpose */
98197   ExprList *pOrderBy,         /* The ORDER BY clause */
98198   WhereCost *pCost            /* Lowest cost query plan */
98199 ){
98200   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
98201   Index *pProbe;              /* An index we are evaluating */
98202   Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
98203   int eqTermMask;             /* Current mask of valid equality operators */
98204   int idxEqTermMask;          /* Index mask of valid equality operators */
98205   Index sPk;                  /* A fake index object for the primary key */
98206   unsigned int aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
98207   int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
98208   int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
98209
98210   /* Initialize the cost to a worst-case value */
98211   memset(pCost, 0, sizeof(*pCost));
98212   pCost->rCost = SQLITE_BIG_DBL;
98213
98214   /* If the pSrc table is the right table of a LEFT JOIN then we may not
98215   ** use an index to satisfy IS NULL constraints on that table.  This is
98216   ** because columns might end up being NULL if the table does not match -
98217   ** a circumstance which the index cannot help us discover.  Ticket #2177.
98218   */
98219   if( pSrc->jointype & JT_LEFT ){
98220     idxEqTermMask = WO_EQ|WO_IN;
98221   }else{
98222     idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
98223   }
98224
98225   if( pSrc->pIndex ){
98226     /* An INDEXED BY clause specifies a particular index to use */
98227     pIdx = pProbe = pSrc->pIndex;
98228     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
98229     eqTermMask = idxEqTermMask;
98230   }else{
98231     /* There is no INDEXED BY clause.  Create a fake Index object to
98232     ** represent the primary key */
98233     Index *pFirst;                /* Any other index on the table */
98234     memset(&sPk, 0, sizeof(Index));
98235     sPk.nColumn = 1;
98236     sPk.aiColumn = &aiColumnPk;
98237     sPk.aiRowEst = aiRowEstPk;
98238     sPk.onError = OE_Replace;
98239     sPk.pTable = pSrc->pTab;
98240     aiRowEstPk[0] = pSrc->pTab->nRowEst;
98241     aiRowEstPk[1] = 1;
98242     pFirst = pSrc->pTab->pIndex;
98243     if( pSrc->notIndexed==0 ){
98244       sPk.pNext = pFirst;
98245     }
98246     pProbe = &sPk;
98247     wsFlagMask = ~(
98248         WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
98249     );
98250     eqTermMask = WO_EQ|WO_IN;
98251     pIdx = 0;
98252   }
98253
98254   /* Loop over all indices looking for the best one to use
98255   */
98256   for(; pProbe; pIdx=pProbe=pProbe->pNext){
98257     const unsigned int * const aiRowEst = pProbe->aiRowEst;
98258     double cost;                /* Cost of using pProbe */
98259     double nRow;                /* Estimated number of rows in result set */
98260     int rev;                    /* True to scan in reverse order */
98261     int wsFlags = 0;
98262     Bitmask used = 0;
98263
98264     /* The following variables are populated based on the properties of
98265     ** scan being evaluated. They are then used to determine the expected
98266     ** cost and number of rows returned.
98267     **
98268     **  nEq: 
98269     **    Number of equality terms that can be implemented using the index.
98270     **
98271     **  nInMul:  
98272     **    The "in-multiplier". This is an estimate of how many seek operations 
98273     **    SQLite must perform on the index in question. For example, if the 
98274     **    WHERE clause is:
98275     **
98276     **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
98277     **
98278     **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is 
98279     **    set to 9. Given the same schema and either of the following WHERE 
98280     **    clauses:
98281     **
98282     **      WHERE a =  1
98283     **      WHERE a >= 2
98284     **
98285     **    nInMul is set to 1.
98286     **
98287     **    If there exists a WHERE term of the form "x IN (SELECT ...)", then 
98288     **    the sub-select is assumed to return 25 rows for the purposes of 
98289     **    determining nInMul.
98290     **
98291     **  bInEst:  
98292     **    Set to true if there was at least one "x IN (SELECT ...)" term used 
98293     **    in determining the value of nInMul.
98294     **
98295     **  estBound:
98296     **    An estimate on the amount of the table that must be searched.  A
98297     **    value of 100 means the entire table is searched.  Range constraints
98298     **    might reduce this to a value less than 100 to indicate that only
98299     **    a fraction of the table needs searching.  In the absence of
98300     **    sqlite_stat2 ANALYZE data, a single inequality reduces the search
98301     **    space to 1/3rd its original size.  So an x>? constraint reduces
98302     **    estBound to 33.  Two constraints (x>? AND x<?) reduce estBound to 11.
98303     **
98304     **  bSort:   
98305     **    Boolean. True if there is an ORDER BY clause that will require an 
98306     **    external sort (i.e. scanning the index being evaluated will not 
98307     **    correctly order records).
98308     **
98309     **  bLookup: 
98310     **    Boolean. True if for each index entry visited a lookup on the 
98311     **    corresponding table b-tree is required. This is always false 
98312     **    for the rowid index. For other indexes, it is true unless all the 
98313     **    columns of the table used by the SELECT statement are present in 
98314     **    the index (such an index is sometimes described as a covering index).
98315     **    For example, given the index on (a, b), the second of the following 
98316     **    two queries requires table b-tree lookups, but the first does not.
98317     **
98318     **             SELECT a, b    FROM tbl WHERE a = 1;
98319     **             SELECT a, b, c FROM tbl WHERE a = 1;
98320     */
98321     int nEq;
98322     int bInEst = 0;
98323     int nInMul = 1;
98324     int estBound = 100;
98325     int nBound = 0;             /* Number of range constraints seen */
98326     int bSort = 0;
98327     int bLookup = 0;
98328     WhereTerm *pTerm;           /* A single term of the WHERE clause */
98329
98330     /* Determine the values of nEq and nInMul */
98331     for(nEq=0; nEq<pProbe->nColumn; nEq++){
98332       int j = pProbe->aiColumn[nEq];
98333       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
98334       if( pTerm==0 ) break;
98335       wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
98336       if( pTerm->eOperator & WO_IN ){
98337         Expr *pExpr = pTerm->pExpr;
98338         wsFlags |= WHERE_COLUMN_IN;
98339         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
98340           nInMul *= 25;
98341           bInEst = 1;
98342         }else if( ALWAYS(pExpr->x.pList) ){
98343           nInMul *= pExpr->x.pList->nExpr + 1;
98344         }
98345       }else if( pTerm->eOperator & WO_ISNULL ){
98346         wsFlags |= WHERE_COLUMN_NULL;
98347       }
98348       used |= pTerm->prereqRight;
98349     }
98350
98351     /* Determine the value of estBound. */
98352     if( nEq<pProbe->nColumn ){
98353       int j = pProbe->aiColumn[nEq];
98354       if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
98355         WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
98356         WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
98357         whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &estBound);
98358         if( pTop ){
98359           nBound = 1;
98360           wsFlags |= WHERE_TOP_LIMIT;
98361           used |= pTop->prereqRight;
98362         }
98363         if( pBtm ){
98364           nBound++;
98365           wsFlags |= WHERE_BTM_LIMIT;
98366           used |= pBtm->prereqRight;
98367         }
98368         wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
98369       }
98370     }else if( pProbe->onError!=OE_None ){
98371       testcase( wsFlags & WHERE_COLUMN_IN );
98372       testcase( wsFlags & WHERE_COLUMN_NULL );
98373       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
98374         wsFlags |= WHERE_UNIQUE;
98375       }
98376     }
98377
98378     /* If there is an ORDER BY clause and the index being considered will
98379     ** naturally scan rows in the required order, set the appropriate flags
98380     ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
98381     ** will scan rows in a different order, set the bSort variable.  */
98382     if( pOrderBy ){
98383       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0
98384         && isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev)
98385       ){
98386         wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
98387         wsFlags |= (rev ? WHERE_REVERSE : 0);
98388       }else{
98389         bSort = 1;
98390       }
98391     }
98392
98393     /* If currently calculating the cost of using an index (not the IPK
98394     ** index), determine if all required column data may be obtained without 
98395     ** using the main table (i.e. if the index is a covering
98396     ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
98397     ** wsFlags. Otherwise, set the bLookup variable to true.  */
98398     if( pIdx && wsFlags ){
98399       Bitmask m = pSrc->colUsed;
98400       int j;
98401       for(j=0; j<pIdx->nColumn; j++){
98402         int x = pIdx->aiColumn[j];
98403         if( x<BMS-1 ){
98404           m &= ~(((Bitmask)1)<<x);
98405         }
98406       }
98407       if( m==0 ){
98408         wsFlags |= WHERE_IDX_ONLY;
98409       }else{
98410         bLookup = 1;
98411       }
98412     }
98413
98414     /*
98415     ** Estimate the number of rows of output.  For an IN operator,
98416     ** do not let the estimate exceed half the rows in the table.
98417     */
98418     nRow = (double)(aiRowEst[nEq] * nInMul);
98419     if( bInEst && nRow*2>aiRowEst[0] ){
98420       nRow = aiRowEst[0]/2;
98421       nInMul = (int)(nRow / aiRowEst[nEq]);
98422     }
98423
98424     /* Assume constant cost to access a row and logarithmic cost to
98425     ** do a binary search.  Hence, the initial cost is the number of output
98426     ** rows plus log2(table-size) times the number of binary searches.
98427     */
98428     cost = nRow + nInMul*estLog(aiRowEst[0]);
98429
98430     /* Adjust the number of rows and the cost downward to reflect rows
98431     ** that are excluded by range constraints.
98432     */
98433     nRow = (nRow * (double)estBound) / (double)100;
98434     cost = (cost * (double)estBound) / (double)100;
98435
98436     /* Add in the estimated cost of sorting the result
98437     */
98438     if( bSort ){
98439       cost += cost*estLog(cost);
98440     }
98441
98442     /* If all information can be taken directly from the index, we avoid
98443     ** doing table lookups.  This reduces the cost by half.  (Not really -
98444     ** this needs to be fixed.)
98445     */
98446     if( pIdx && bLookup==0 ){
98447       cost /= (double)2;
98448     }
98449     /**** Cost of using this index has now been computed ****/
98450
98451     /* If there are additional constraints on this table that cannot
98452     ** be used with the current index, but which might lower the number
98453     ** of output rows, adjust the nRow value accordingly.  This only 
98454     ** matters if the current index is the least costly, so do not bother
98455     ** with this step if we already know this index will not be chosen.
98456     ** Also, never reduce the output row count below 2 using this step.
98457     **
98458     ** It is critical that the notValid mask be used here instead of
98459     ** the notReady mask.  When computing an "optimal" index, the notReady
98460     ** mask will only have one bit set - the bit for the current table.
98461     ** The notValid mask, on the other hand, always has all bits set for
98462     ** tables that are not in outer loops.  If notReady is used here instead
98463     ** of notValid, then a optimal index that depends on inner joins loops
98464     ** might be selected even when there exists an optimal index that has
98465     ** no such dependency.
98466     */
98467     if( nRow>2 && cost<=pCost->rCost ){
98468       int k;                       /* Loop counter */
98469       int nSkipEq = nEq;           /* Number of == constraints to skip */
98470       int nSkipRange = nBound;     /* Number of < constraints to skip */
98471       Bitmask thisTab;             /* Bitmap for pSrc */
98472
98473       thisTab = getMask(pWC->pMaskSet, iCur);
98474       for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){
98475         if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
98476         if( (pTerm->prereqAll & notValid)!=thisTab ) continue;
98477         if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
98478           if( nSkipEq ){
98479             /* Ignore the first nEq equality matches since the index
98480             ** has already accounted for these */
98481             nSkipEq--;
98482           }else{
98483             /* Assume each additional equality match reduces the result
98484             ** set size by a factor of 10 */
98485             nRow /= 10;
98486           }
98487         }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
98488           if( nSkipRange ){
98489             /* Ignore the first nBound range constraints since the index
98490             ** has already accounted for these */
98491             nSkipRange--;
98492           }else{
98493             /* Assume each additional range constraint reduces the result
98494             ** set size by a factor of 3 */
98495             nRow /= 3;
98496           }
98497         }else{
98498           /* Any other expression lowers the output row count by half */
98499           nRow /= 2;
98500         }
98501       }
98502       if( nRow<2 ) nRow = 2;
98503     }
98504
98505
98506     WHERETRACE((
98507       "%s(%s): nEq=%d nInMul=%d estBound=%d bSort=%d bLookup=%d wsFlags=0x%x\n"
98508       "         notReady=0x%llx nRow=%.2f cost=%.2f used=0x%llx\n",
98509       pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"), 
98510       nEq, nInMul, estBound, bSort, bLookup, wsFlags,
98511       notReady, nRow, cost, used
98512     ));
98513
98514     /* If this index is the best we have seen so far, then record this
98515     ** index and its cost in the pCost structure.
98516     */
98517     if( (!pIdx || wsFlags)
98518      && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->plan.nRow))
98519     ){
98520       pCost->rCost = cost;
98521       pCost->used = used;
98522       pCost->plan.nRow = nRow;
98523       pCost->plan.wsFlags = (wsFlags&wsFlagMask);
98524       pCost->plan.nEq = nEq;
98525       pCost->plan.u.pIdx = pIdx;
98526     }
98527
98528     /* If there was an INDEXED BY clause, then only that one index is
98529     ** considered. */
98530     if( pSrc->pIndex ) break;
98531
98532     /* Reset masks for the next index in the loop */
98533     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
98534     eqTermMask = idxEqTermMask;
98535   }
98536
98537   /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
98538   ** is set, then reverse the order that the index will be scanned
98539   ** in. This is used for application testing, to help find cases
98540   ** where application behaviour depends on the (undefined) order that
98541   ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
98542   if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
98543     pCost->plan.wsFlags |= WHERE_REVERSE;
98544   }
98545
98546   assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
98547   assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
98548   assert( pSrc->pIndex==0 
98549        || pCost->plan.u.pIdx==0 
98550        || pCost->plan.u.pIdx==pSrc->pIndex 
98551   );
98552
98553   WHERETRACE(("best index is: %s\n", 
98554     ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" : 
98555          pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
98556   ));
98557   
98558   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
98559   bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);
98560   pCost->plan.wsFlags |= eqTermMask;
98561 }
98562
98563 /*
98564 ** Find the query plan for accessing table pSrc->pTab. Write the
98565 ** best query plan and its cost into the WhereCost object supplied 
98566 ** as the last parameter. This function may calculate the cost of
98567 ** both real and virtual table scans.
98568 */
98569 static void bestIndex(
98570   Parse *pParse,              /* The parsing context */
98571   WhereClause *pWC,           /* The WHERE clause */
98572   struct SrcList_item *pSrc,  /* The FROM clause term to search */
98573   Bitmask notReady,           /* Mask of cursors not available for indexing */
98574   Bitmask notValid,           /* Cursors not available for any purpose */
98575   ExprList *pOrderBy,         /* The ORDER BY clause */
98576   WhereCost *pCost            /* Lowest cost query plan */
98577 ){
98578 #ifndef SQLITE_OMIT_VIRTUALTABLE
98579   if( IsVirtual(pSrc->pTab) ){
98580     sqlite3_index_info *p = 0;
98581     bestVirtualIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost,&p);
98582     if( p->needToFreeIdxStr ){
98583       sqlite3_free(p->idxStr);
98584     }
98585     sqlite3DbFree(pParse->db, p);
98586   }else
98587 #endif
98588   {
98589     bestBtreeIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
98590   }
98591 }
98592
98593 /*
98594 ** Disable a term in the WHERE clause.  Except, do not disable the term
98595 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
98596 ** or USING clause of that join.
98597 **
98598 ** Consider the term t2.z='ok' in the following queries:
98599 **
98600 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
98601 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
98602 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
98603 **
98604 ** The t2.z='ok' is disabled in the in (2) because it originates
98605 ** in the ON clause.  The term is disabled in (3) because it is not part
98606 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
98607 **
98608 ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
98609 ** completely satisfied by indices.
98610 **
98611 ** Disabling a term causes that term to not be tested in the inner loop
98612 ** of the join.  Disabling is an optimization.  When terms are satisfied
98613 ** by indices, we disable them to prevent redundant tests in the inner
98614 ** loop.  We would get the correct results if nothing were ever disabled,
98615 ** but joins might run a little slower.  The trick is to disable as much
98616 ** as we can without disabling too much.  If we disabled in (1), we'd get
98617 ** the wrong answer.  See ticket #813.
98618 */
98619 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
98620   if( pTerm
98621       && (pTerm->wtFlags & TERM_CODED)==0
98622       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
98623   ){
98624     pTerm->wtFlags |= TERM_CODED;
98625     if( pTerm->iParent>=0 ){
98626       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
98627       if( (--pOther->nChild)==0 ){
98628         disableTerm(pLevel, pOther);
98629       }
98630     }
98631   }
98632 }
98633
98634 /*
98635 ** Code an OP_Affinity opcode to apply the column affinity string zAff
98636 ** to the n registers starting at base. 
98637 **
98638 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
98639 ** beginning and end of zAff are ignored.  If all entries in zAff are
98640 ** SQLITE_AFF_NONE, then no code gets generated.
98641 **
98642 ** This routine makes its own copy of zAff so that the caller is free
98643 ** to modify zAff after this routine returns.
98644 */
98645 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
98646   Vdbe *v = pParse->pVdbe;
98647   if( zAff==0 ){
98648     assert( pParse->db->mallocFailed );
98649     return;
98650   }
98651   assert( v!=0 );
98652
98653   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
98654   ** and end of the affinity string.
98655   */
98656   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
98657     n--;
98658     base++;
98659     zAff++;
98660   }
98661   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
98662     n--;
98663   }
98664
98665   /* Code the OP_Affinity opcode if there is anything left to do. */
98666   if( n>0 ){
98667     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
98668     sqlite3VdbeChangeP4(v, -1, zAff, n);
98669     sqlite3ExprCacheAffinityChange(pParse, base, n);
98670   }
98671 }
98672
98673
98674 /*
98675 ** Generate code for a single equality term of the WHERE clause.  An equality
98676 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
98677 ** coded.
98678 **
98679 ** The current value for the constraint is left in register iReg.
98680 **
98681 ** For a constraint of the form X=expr, the expression is evaluated and its
98682 ** result is left on the stack.  For constraints of the form X IN (...)
98683 ** this routine sets up a loop that will iterate over all values of X.
98684 */
98685 static int codeEqualityTerm(
98686   Parse *pParse,      /* The parsing context */
98687   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
98688   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
98689   int iTarget         /* Attempt to leave results in this register */
98690 ){
98691   Expr *pX = pTerm->pExpr;
98692   Vdbe *v = pParse->pVdbe;
98693   int iReg;                  /* Register holding results */
98694
98695   assert( iTarget>0 );
98696   if( pX->op==TK_EQ ){
98697     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
98698   }else if( pX->op==TK_ISNULL ){
98699     iReg = iTarget;
98700     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
98701 #ifndef SQLITE_OMIT_SUBQUERY
98702   }else{
98703     int eType;
98704     int iTab;
98705     struct InLoop *pIn;
98706
98707     assert( pX->op==TK_IN );
98708     iReg = iTarget;
98709     eType = sqlite3FindInIndex(pParse, pX, 0);
98710     iTab = pX->iTable;
98711     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
98712     assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
98713     if( pLevel->u.in.nIn==0 ){
98714       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
98715     }
98716     pLevel->u.in.nIn++;
98717     pLevel->u.in.aInLoop =
98718        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
98719                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
98720     pIn = pLevel->u.in.aInLoop;
98721     if( pIn ){
98722       pIn += pLevel->u.in.nIn - 1;
98723       pIn->iCur = iTab;
98724       if( eType==IN_INDEX_ROWID ){
98725         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
98726       }else{
98727         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
98728       }
98729       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
98730     }else{
98731       pLevel->u.in.nIn = 0;
98732     }
98733 #endif
98734   }
98735   disableTerm(pLevel, pTerm);
98736   return iReg;
98737 }
98738
98739 /*
98740 ** Generate code that will evaluate all == and IN constraints for an
98741 ** index.
98742 **
98743 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
98744 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
98745 ** The index has as many as three equality constraints, but in this
98746 ** example, the third "c" value is an inequality.  So only two 
98747 ** constraints are coded.  This routine will generate code to evaluate
98748 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
98749 ** in consecutive registers and the index of the first register is returned.
98750 **
98751 ** In the example above nEq==2.  But this subroutine works for any value
98752 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
98753 ** The only thing it does is allocate the pLevel->iMem memory cell and
98754 ** compute the affinity string.
98755 **
98756 ** This routine always allocates at least one memory cell and returns
98757 ** the index of that memory cell. The code that
98758 ** calls this routine will use that memory cell to store the termination
98759 ** key value of the loop.  If one or more IN operators appear, then
98760 ** this routine allocates an additional nEq memory cells for internal
98761 ** use.
98762 **
98763 ** Before returning, *pzAff is set to point to a buffer containing a
98764 ** copy of the column affinity string of the index allocated using
98765 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
98766 ** with equality constraints that use NONE affinity are set to
98767 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
98768 **
98769 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
98770 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
98771 **
98772 ** In the example above, the index on t1(a) has TEXT affinity. But since
98773 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
98774 ** no conversion should be attempted before using a t2.b value as part of
98775 ** a key to search the index. Hence the first byte in the returned affinity
98776 ** string in this example would be set to SQLITE_AFF_NONE.
98777 */
98778 static int codeAllEqualityTerms(
98779   Parse *pParse,        /* Parsing context */
98780   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
98781   WhereClause *pWC,     /* The WHERE clause */
98782   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
98783   int nExtraReg,        /* Number of extra registers to allocate */
98784   char **pzAff          /* OUT: Set to point to affinity string */
98785 ){
98786   int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
98787   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
98788   Index *pIdx;                  /* The index being used for this loop */
98789   int iCur = pLevel->iTabCur;   /* The cursor of the table */
98790   WhereTerm *pTerm;             /* A single constraint term */
98791   int j;                        /* Loop counter */
98792   int regBase;                  /* Base register */
98793   int nReg;                     /* Number of registers to allocate */
98794   char *zAff;                   /* Affinity string to return */
98795
98796   /* This module is only called on query plans that use an index. */
98797   assert( pLevel->plan.wsFlags & WHERE_INDEXED );
98798   pIdx = pLevel->plan.u.pIdx;
98799
98800   /* Figure out how many memory cells we will need then allocate them.
98801   */
98802   regBase = pParse->nMem + 1;
98803   nReg = pLevel->plan.nEq + nExtraReg;
98804   pParse->nMem += nReg;
98805
98806   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
98807   if( !zAff ){
98808     pParse->db->mallocFailed = 1;
98809   }
98810
98811   /* Evaluate the equality constraints
98812   */
98813   assert( pIdx->nColumn>=nEq );
98814   for(j=0; j<nEq; j++){
98815     int r1;
98816     int k = pIdx->aiColumn[j];
98817     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
98818     if( NEVER(pTerm==0) ) break;
98819     /* The following true for indices with redundant columns. 
98820     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
98821     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
98822     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
98823     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
98824     if( r1!=regBase+j ){
98825       if( nReg==1 ){
98826         sqlite3ReleaseTempReg(pParse, regBase);
98827         regBase = r1;
98828       }else{
98829         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
98830       }
98831     }
98832     testcase( pTerm->eOperator & WO_ISNULL );
98833     testcase( pTerm->eOperator & WO_IN );
98834     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
98835       Expr *pRight = pTerm->pExpr->pRight;
98836       sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
98837       if( zAff ){
98838         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
98839           zAff[j] = SQLITE_AFF_NONE;
98840         }
98841         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
98842           zAff[j] = SQLITE_AFF_NONE;
98843         }
98844       }
98845     }
98846   }
98847   *pzAff = zAff;
98848   return regBase;
98849 }
98850
98851 #ifndef SQLITE_OMIT_EXPLAIN
98852 /*
98853 ** This routine is a helper for explainIndexRange() below
98854 **
98855 ** pStr holds the text of an expression that we are building up one term
98856 ** at a time.  This routine adds a new term to the end of the expression.
98857 ** Terms are separated by AND so add the "AND" text for second and subsequent
98858 ** terms only.
98859 */
98860 static void explainAppendTerm(
98861   StrAccum *pStr,             /* The text expression being built */
98862   int iTerm,                  /* Index of this term.  First is zero */
98863   const char *zColumn,        /* Name of the column */
98864   const char *zOp             /* Name of the operator */
98865 ){
98866   if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
98867   sqlite3StrAccumAppend(pStr, zColumn, -1);
98868   sqlite3StrAccumAppend(pStr, zOp, 1);
98869   sqlite3StrAccumAppend(pStr, "?", 1);
98870 }
98871
98872 /*
98873 ** Argument pLevel describes a strategy for scanning table pTab. This 
98874 ** function returns a pointer to a string buffer containing a description
98875 ** of the subset of table rows scanned by the strategy in the form of an
98876 ** SQL expression. Or, if all rows are scanned, NULL is returned.
98877 **
98878 ** For example, if the query:
98879 **
98880 **   SELECT * FROM t1 WHERE a=1 AND b>2;
98881 **
98882 ** is run and there is an index on (a, b), then this function returns a
98883 ** string similar to:
98884 **
98885 **   "a=? AND b>?"
98886 **
98887 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
98888 ** It is the responsibility of the caller to free the buffer when it is
98889 ** no longer required.
98890 */
98891 static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
98892   WherePlan *pPlan = &pLevel->plan;
98893   Index *pIndex = pPlan->u.pIdx;
98894   int nEq = pPlan->nEq;
98895   int i, j;
98896   Column *aCol = pTab->aCol;
98897   int *aiColumn = pIndex->aiColumn;
98898   StrAccum txt;
98899
98900   if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
98901     return 0;
98902   }
98903   sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
98904   txt.db = db;
98905   sqlite3StrAccumAppend(&txt, " (", 2);
98906   for(i=0; i<nEq; i++){
98907     explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
98908   }
98909
98910   j = i;
98911   if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
98912     explainAppendTerm(&txt, i++, aCol[aiColumn[j]].zName, ">");
98913   }
98914   if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
98915     explainAppendTerm(&txt, i, aCol[aiColumn[j]].zName, "<");
98916   }
98917   sqlite3StrAccumAppend(&txt, ")", 1);
98918   return sqlite3StrAccumFinish(&txt);
98919 }
98920
98921 /*
98922 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
98923 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
98924 ** record is added to the output to describe the table scan strategy in 
98925 ** pLevel.
98926 */
98927 static void explainOneScan(
98928   Parse *pParse,                  /* Parse context */
98929   SrcList *pTabList,              /* Table list this loop refers to */
98930   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
98931   int iLevel,                     /* Value for "level" column of output */
98932   int iFrom,                      /* Value for "from" column of output */
98933   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
98934 ){
98935   if( pParse->explain==2 ){
98936     u32 flags = pLevel->plan.wsFlags;
98937     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
98938     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
98939     sqlite3 *db = pParse->db;     /* Database handle */
98940     char *zMsg;                   /* Text to add to EQP output */
98941     sqlite3_int64 nRow;           /* Expected number of rows visited by scan */
98942     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
98943     int isSearch;                 /* True for a SEARCH. False for SCAN. */
98944
98945     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
98946
98947     isSearch = (pLevel->plan.nEq>0)
98948              || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
98949              || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
98950
98951     zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
98952     if( pItem->pSelect ){
98953       zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
98954     }else{
98955       zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
98956     }
98957
98958     if( pItem->zAlias ){
98959       zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
98960     }
98961     if( (flags & WHERE_INDEXED)!=0 ){
98962       char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
98963       zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg, 
98964           ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
98965           ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
98966           ((flags & WHERE_TEMP_INDEX)?"":" "),
98967           ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
98968           zWhere
98969       );
98970       sqlite3DbFree(db, zWhere);
98971     }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
98972       zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
98973
98974       if( flags&WHERE_ROWID_EQ ){
98975         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
98976       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
98977         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
98978       }else if( flags&WHERE_BTM_LIMIT ){
98979         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
98980       }else if( flags&WHERE_TOP_LIMIT ){
98981         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
98982       }
98983     }
98984 #ifndef SQLITE_OMIT_VIRTUALTABLE
98985     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
98986       sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
98987       zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
98988                   pVtabIdx->idxNum, pVtabIdx->idxStr);
98989     }
98990 #endif
98991     if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
98992       testcase( wctrlFlags & WHERE_ORDERBY_MIN );
98993       nRow = 1;
98994     }else{
98995       nRow = (sqlite3_int64)pLevel->plan.nRow;
98996     }
98997     zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
98998     sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
98999   }
99000 }
99001 #else
99002 # define explainOneScan(u,v,w,x,y,z)
99003 #endif /* SQLITE_OMIT_EXPLAIN */
99004
99005
99006 /*
99007 ** Generate code for the start of the iLevel-th loop in the WHERE clause
99008 ** implementation described by pWInfo.
99009 */
99010 static Bitmask codeOneLoopStart(
99011   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
99012   int iLevel,          /* Which level of pWInfo->a[] should be coded */
99013   u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
99014   Bitmask notReady     /* Which tables are currently available */
99015 ){
99016   int j, k;            /* Loop counters */
99017   int iCur;            /* The VDBE cursor for the table */
99018   int addrNxt;         /* Where to jump to continue with the next IN case */
99019   int omitTable;       /* True if we use the index only */
99020   int bRev;            /* True if we need to scan in reverse order */
99021   WhereLevel *pLevel;  /* The where level to be coded */
99022   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
99023   WhereTerm *pTerm;               /* A WHERE clause term */
99024   Parse *pParse;                  /* Parsing context */
99025   Vdbe *v;                        /* The prepared stmt under constructions */
99026   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
99027   int addrBrk;                    /* Jump here to break out of the loop */
99028   int addrCont;                   /* Jump here to continue with next cycle */
99029   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
99030   int iReleaseReg = 0;      /* Temp register to free before returning */
99031
99032   pParse = pWInfo->pParse;
99033   v = pParse->pVdbe;
99034   pWC = pWInfo->pWC;
99035   pLevel = &pWInfo->a[iLevel];
99036   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
99037   iCur = pTabItem->iCursor;
99038   bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
99039   omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0 
99040            && (wctrlFlags & WHERE_FORCE_TABLE)==0;
99041
99042   /* Create labels for the "break" and "continue" instructions
99043   ** for the current loop.  Jump to addrBrk to break out of a loop.
99044   ** Jump to cont to go immediately to the next iteration of the
99045   ** loop.
99046   **
99047   ** When there is an IN operator, we also have a "addrNxt" label that
99048   ** means to continue with the next IN value combination.  When
99049   ** there are no IN operators in the constraints, the "addrNxt" label
99050   ** is the same as "addrBrk".
99051   */
99052   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
99053   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
99054
99055   /* If this is the right table of a LEFT OUTER JOIN, allocate and
99056   ** initialize a memory cell that records if this table matches any
99057   ** row of the left table of the join.
99058   */
99059   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
99060     pLevel->iLeftJoin = ++pParse->nMem;
99061     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
99062     VdbeComment((v, "init LEFT JOIN no-match flag"));
99063   }
99064
99065 #ifndef SQLITE_OMIT_VIRTUALTABLE
99066   if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
99067     /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
99068     **          to access the data.
99069     */
99070     int iReg;   /* P3 Value for OP_VFilter */
99071     sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
99072     int nConstraint = pVtabIdx->nConstraint;
99073     struct sqlite3_index_constraint_usage *aUsage =
99074                                                 pVtabIdx->aConstraintUsage;
99075     const struct sqlite3_index_constraint *aConstraint =
99076                                                 pVtabIdx->aConstraint;
99077
99078     sqlite3ExprCachePush(pParse);
99079     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
99080     for(j=1; j<=nConstraint; j++){
99081       for(k=0; k<nConstraint; k++){
99082         if( aUsage[k].argvIndex==j ){
99083           int iTerm = aConstraint[k].iTermOffset;
99084           sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
99085           break;
99086         }
99087       }
99088       if( k==nConstraint ) break;
99089     }
99090     sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
99091     sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
99092     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
99093                       pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
99094     pVtabIdx->needToFreeIdxStr = 0;
99095     for(j=0; j<nConstraint; j++){
99096       if( aUsage[j].omit ){
99097         int iTerm = aConstraint[j].iTermOffset;
99098         disableTerm(pLevel, &pWC->a[iTerm]);
99099       }
99100     }
99101     pLevel->op = OP_VNext;
99102     pLevel->p1 = iCur;
99103     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
99104     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
99105     sqlite3ExprCachePop(pParse, 1);
99106   }else
99107 #endif /* SQLITE_OMIT_VIRTUALTABLE */
99108
99109   if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
99110     /* Case 1:  We can directly reference a single row using an
99111     **          equality comparison against the ROWID field.  Or
99112     **          we reference multiple rows using a "rowid IN (...)"
99113     **          construct.
99114     */
99115     iReleaseReg = sqlite3GetTempReg(pParse);
99116     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
99117     assert( pTerm!=0 );
99118     assert( pTerm->pExpr!=0 );
99119     assert( pTerm->leftCursor==iCur );
99120     assert( omitTable==0 );
99121     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
99122     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
99123     addrNxt = pLevel->addrNxt;
99124     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
99125     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
99126     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
99127     VdbeComment((v, "pk"));
99128     pLevel->op = OP_Noop;
99129   }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
99130     /* Case 2:  We have an inequality comparison against the ROWID field.
99131     */
99132     int testOp = OP_Noop;
99133     int start;
99134     int memEndValue = 0;
99135     WhereTerm *pStart, *pEnd;
99136
99137     assert( omitTable==0 );
99138     pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
99139     pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
99140     if( bRev ){
99141       pTerm = pStart;
99142       pStart = pEnd;
99143       pEnd = pTerm;
99144     }
99145     if( pStart ){
99146       Expr *pX;             /* The expression that defines the start bound */
99147       int r1, rTemp;        /* Registers for holding the start boundary */
99148
99149       /* The following constant maps TK_xx codes into corresponding 
99150       ** seek opcodes.  It depends on a particular ordering of TK_xx
99151       */
99152       const u8 aMoveOp[] = {
99153            /* TK_GT */  OP_SeekGt,
99154            /* TK_LE */  OP_SeekLe,
99155            /* TK_LT */  OP_SeekLt,
99156            /* TK_GE */  OP_SeekGe
99157       };
99158       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
99159       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
99160       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
99161
99162       testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
99163       pX = pStart->pExpr;
99164       assert( pX!=0 );
99165       assert( pStart->leftCursor==iCur );
99166       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
99167       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
99168       VdbeComment((v, "pk"));
99169       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
99170       sqlite3ReleaseTempReg(pParse, rTemp);
99171       disableTerm(pLevel, pStart);
99172     }else{
99173       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
99174     }
99175     if( pEnd ){
99176       Expr *pX;
99177       pX = pEnd->pExpr;
99178       assert( pX!=0 );
99179       assert( pEnd->leftCursor==iCur );
99180       testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
99181       memEndValue = ++pParse->nMem;
99182       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
99183       if( pX->op==TK_LT || pX->op==TK_GT ){
99184         testOp = bRev ? OP_Le : OP_Ge;
99185       }else{
99186         testOp = bRev ? OP_Lt : OP_Gt;
99187       }
99188       disableTerm(pLevel, pEnd);
99189     }
99190     start = sqlite3VdbeCurrentAddr(v);
99191     pLevel->op = bRev ? OP_Prev : OP_Next;
99192     pLevel->p1 = iCur;
99193     pLevel->p2 = start;
99194     if( pStart==0 && pEnd==0 ){
99195       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
99196     }else{
99197       assert( pLevel->p5==0 );
99198     }
99199     if( testOp!=OP_Noop ){
99200       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
99201       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
99202       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
99203       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
99204       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
99205     }
99206   }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
99207     /* Case 3: A scan using an index.
99208     **
99209     **         The WHERE clause may contain zero or more equality 
99210     **         terms ("==" or "IN" operators) that refer to the N
99211     **         left-most columns of the index. It may also contain
99212     **         inequality constraints (>, <, >= or <=) on the indexed
99213     **         column that immediately follows the N equalities. Only 
99214     **         the right-most column can be an inequality - the rest must
99215     **         use the "==" and "IN" operators. For example, if the 
99216     **         index is on (x,y,z), then the following clauses are all 
99217     **         optimized:
99218     **
99219     **            x=5
99220     **            x=5 AND y=10
99221     **            x=5 AND y<10
99222     **            x=5 AND y>5 AND y<10
99223     **            x=5 AND y=5 AND z<=10
99224     **
99225     **         The z<10 term of the following cannot be used, only
99226     **         the x=5 term:
99227     **
99228     **            x=5 AND z<10
99229     **
99230     **         N may be zero if there are inequality constraints.
99231     **         If there are no inequality constraints, then N is at
99232     **         least one.
99233     **
99234     **         This case is also used when there are no WHERE clause
99235     **         constraints but an index is selected anyway, in order
99236     **         to force the output order to conform to an ORDER BY.
99237     */  
99238     static const u8 aStartOp[] = {
99239       0,
99240       0,
99241       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
99242       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
99243       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
99244       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
99245       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
99246       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
99247     };
99248     static const u8 aEndOp[] = {
99249       OP_Noop,             /* 0: (!end_constraints) */
99250       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
99251       OP_IdxLT             /* 2: (end_constraints && bRev) */
99252     };
99253     int nEq = pLevel->plan.nEq;  /* Number of == or IN terms */
99254     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
99255     int regBase;                 /* Base register holding constraint values */
99256     int r1;                      /* Temp register */
99257     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
99258     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
99259     int startEq;                 /* True if range start uses ==, >= or <= */
99260     int endEq;                   /* True if range end uses ==, >= or <= */
99261     int start_constraints;       /* Start of range is constrained */
99262     int nConstraint;             /* Number of constraint terms */
99263     Index *pIdx;                 /* The index we will be using */
99264     int iIdxCur;                 /* The VDBE cursor for the index */
99265     int nExtraReg = 0;           /* Number of extra registers needed */
99266     int op;                      /* Instruction opcode */
99267     char *zStartAff;             /* Affinity for start of range constraint */
99268     char *zEndAff;               /* Affinity for end of range constraint */
99269
99270     pIdx = pLevel->plan.u.pIdx;
99271     iIdxCur = pLevel->iIdxCur;
99272     k = pIdx->aiColumn[nEq];     /* Column for inequality constraints */
99273
99274     /* If this loop satisfies a sort order (pOrderBy) request that 
99275     ** was passed to this function to implement a "SELECT min(x) ..." 
99276     ** query, then the caller will only allow the loop to run for
99277     ** a single iteration. This means that the first row returned
99278     ** should not have a NULL value stored in 'x'. If column 'x' is
99279     ** the first one after the nEq equality constraints in the index,
99280     ** this requires some special handling.
99281     */
99282     if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
99283      && (pLevel->plan.wsFlags&WHERE_ORDERBY)
99284      && (pIdx->nColumn>nEq)
99285     ){
99286       /* assert( pOrderBy->nExpr==1 ); */
99287       /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
99288       isMinQuery = 1;
99289       nExtraReg = 1;
99290     }
99291
99292     /* Find any inequality constraint terms for the start and end 
99293     ** of the range. 
99294     */
99295     if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
99296       pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
99297       nExtraReg = 1;
99298     }
99299     if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
99300       pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
99301       nExtraReg = 1;
99302     }
99303
99304     /* Generate code to evaluate all constraint terms using == or IN
99305     ** and store the values of those terms in an array of registers
99306     ** starting at regBase.
99307     */
99308     regBase = codeAllEqualityTerms(
99309         pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
99310     );
99311     zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
99312     addrNxt = pLevel->addrNxt;
99313
99314     /* If we are doing a reverse order scan on an ascending index, or
99315     ** a forward order scan on a descending index, interchange the 
99316     ** start and end terms (pRangeStart and pRangeEnd).
99317     */
99318     if( nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
99319       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
99320     }
99321
99322     testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
99323     testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
99324     testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
99325     testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
99326     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
99327     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
99328     start_constraints = pRangeStart || nEq>0;
99329
99330     /* Seek the index cursor to the start of the range. */
99331     nConstraint = nEq;
99332     if( pRangeStart ){
99333       Expr *pRight = pRangeStart->pExpr->pRight;
99334       sqlite3ExprCode(pParse, pRight, regBase+nEq);
99335       sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
99336       if( zStartAff ){
99337         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
99338           /* Since the comparison is to be performed with no conversions
99339           ** applied to the operands, set the affinity to apply to pRight to 
99340           ** SQLITE_AFF_NONE.  */
99341           zStartAff[nEq] = SQLITE_AFF_NONE;
99342         }
99343         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
99344           zStartAff[nEq] = SQLITE_AFF_NONE;
99345         }
99346       }  
99347       nConstraint++;
99348       testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
99349     }else if( isMinQuery ){
99350       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
99351       nConstraint++;
99352       startEq = 0;
99353       start_constraints = 1;
99354     }
99355     codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
99356     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
99357     assert( op!=0 );
99358     testcase( op==OP_Rewind );
99359     testcase( op==OP_Last );
99360     testcase( op==OP_SeekGt );
99361     testcase( op==OP_SeekGe );
99362     testcase( op==OP_SeekLe );
99363     testcase( op==OP_SeekLt );
99364     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
99365
99366     /* Load the value for the inequality constraint at the end of the
99367     ** range (if any).
99368     */
99369     nConstraint = nEq;
99370     if( pRangeEnd ){
99371       Expr *pRight = pRangeEnd->pExpr->pRight;
99372       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
99373       sqlite3ExprCode(pParse, pRight, regBase+nEq);
99374       sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
99375       if( zEndAff ){
99376         if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
99377           /* Since the comparison is to be performed with no conversions
99378           ** applied to the operands, set the affinity to apply to pRight to 
99379           ** SQLITE_AFF_NONE.  */
99380           zEndAff[nEq] = SQLITE_AFF_NONE;
99381         }
99382         if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
99383           zEndAff[nEq] = SQLITE_AFF_NONE;
99384         }
99385       }  
99386       codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
99387       nConstraint++;
99388       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
99389     }
99390     sqlite3DbFree(pParse->db, zStartAff);
99391     sqlite3DbFree(pParse->db, zEndAff);
99392
99393     /* Top of the loop body */
99394     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
99395
99396     /* Check if the index cursor is past the end of the range. */
99397     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
99398     testcase( op==OP_Noop );
99399     testcase( op==OP_IdxGE );
99400     testcase( op==OP_IdxLT );
99401     if( op!=OP_Noop ){
99402       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
99403       sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
99404     }
99405
99406     /* If there are inequality constraints, check that the value
99407     ** of the table column that the inequality contrains is not NULL.
99408     ** If it is, jump to the next iteration of the loop.
99409     */
99410     r1 = sqlite3GetTempReg(pParse);
99411     testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
99412     testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
99413     if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
99414       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
99415       sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
99416     }
99417     sqlite3ReleaseTempReg(pParse, r1);
99418
99419     /* Seek the table cursor, if required */
99420     disableTerm(pLevel, pRangeStart);
99421     disableTerm(pLevel, pRangeEnd);
99422     if( !omitTable ){
99423       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
99424       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
99425       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
99426       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
99427     }
99428
99429     /* Record the instruction used to terminate the loop. Disable 
99430     ** WHERE clause terms made redundant by the index range scan.
99431     */
99432     pLevel->op = bRev ? OP_Prev : OP_Next;
99433     pLevel->p1 = iIdxCur;
99434   }else
99435
99436 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
99437   if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
99438     /* Case 4:  Two or more separately indexed terms connected by OR
99439     **
99440     ** Example:
99441     **
99442     **   CREATE TABLE t1(a,b,c,d);
99443     **   CREATE INDEX i1 ON t1(a);
99444     **   CREATE INDEX i2 ON t1(b);
99445     **   CREATE INDEX i3 ON t1(c);
99446     **
99447     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
99448     **
99449     ** In the example, there are three indexed terms connected by OR.
99450     ** The top of the loop looks like this:
99451     **
99452     **          Null       1                # Zero the rowset in reg 1
99453     **
99454     ** Then, for each indexed term, the following. The arguments to
99455     ** RowSetTest are such that the rowid of the current row is inserted
99456     ** into the RowSet. If it is already present, control skips the
99457     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
99458     **
99459     **        sqlite3WhereBegin(<term>)
99460     **          RowSetTest                  # Insert rowid into rowset
99461     **          Gosub      2 A
99462     **        sqlite3WhereEnd()
99463     **
99464     ** Following the above, code to terminate the loop. Label A, the target
99465     ** of the Gosub above, jumps to the instruction right after the Goto.
99466     **
99467     **          Null       1                # Zero the rowset in reg 1
99468     **          Goto       B                # The loop is finished.
99469     **
99470     **       A: <loop body>                 # Return data, whatever.
99471     **
99472     **          Return     2                # Jump back to the Gosub
99473     **
99474     **       B: <after the loop>
99475     **
99476     */
99477     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
99478     WhereTerm *pFinal;     /* Final subterm within the OR-clause. */
99479     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
99480
99481     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
99482     int regRowset = 0;                        /* Register for RowSet object */
99483     int regRowid = 0;                         /* Register holding rowid */
99484     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
99485     int iRetInit;                             /* Address of regReturn init */
99486     int untestedTerms = 0;             /* Some terms not completely tested */
99487     int ii;
99488    
99489     pTerm = pLevel->plan.u.pTerm;
99490     assert( pTerm!=0 );
99491     assert( pTerm->eOperator==WO_OR );
99492     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
99493     pOrWc = &pTerm->u.pOrInfo->wc;
99494     pFinal = &pOrWc->a[pOrWc->nTerm-1];
99495     pLevel->op = OP_Return;
99496     pLevel->p1 = regReturn;
99497
99498     /* Set up a new SrcList ni pOrTab containing the table being scanned
99499     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
99500     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
99501     */
99502     if( pWInfo->nLevel>1 ){
99503       int nNotReady;                 /* The number of notReady tables */
99504       struct SrcList_item *origSrc;     /* Original list of tables */
99505       nNotReady = pWInfo->nLevel - iLevel - 1;
99506       pOrTab = sqlite3StackAllocRaw(pParse->db,
99507                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
99508       if( pOrTab==0 ) return notReady;
99509       pOrTab->nAlloc = (i16)(nNotReady + 1);
99510       pOrTab->nSrc = pOrTab->nAlloc;
99511       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
99512       origSrc = pWInfo->pTabList->a;
99513       for(k=1; k<=nNotReady; k++){
99514         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
99515       }
99516     }else{
99517       pOrTab = pWInfo->pTabList;
99518     }
99519
99520     /* Initialize the rowset register to contain NULL. An SQL NULL is 
99521     ** equivalent to an empty rowset.
99522     **
99523     ** Also initialize regReturn to contain the address of the instruction 
99524     ** immediately following the OP_Return at the bottom of the loop. This
99525     ** is required in a few obscure LEFT JOIN cases where control jumps
99526     ** over the top of the loop into the body of it. In this case the 
99527     ** correct response for the end-of-loop code (the OP_Return) is to 
99528     ** fall through to the next instruction, just as an OP_Next does if
99529     ** called on an uninitialized cursor.
99530     */
99531     if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
99532       regRowset = ++pParse->nMem;
99533       regRowid = ++pParse->nMem;
99534       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
99535     }
99536     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
99537
99538     for(ii=0; ii<pOrWc->nTerm; ii++){
99539       WhereTerm *pOrTerm = &pOrWc->a[ii];
99540       if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
99541         WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
99542         /* Loop through table entries that match term pOrTerm. */
99543         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrTerm->pExpr, 0,
99544                         WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE |
99545                         WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
99546         if( pSubWInfo ){
99547           explainOneScan(
99548               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
99549           );
99550           if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
99551             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
99552             int r;
99553             r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur, 
99554                                          regRowid);
99555             sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
99556                                  sqlite3VdbeCurrentAddr(v)+2, r, iSet);
99557           }
99558           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
99559
99560           /* The pSubWInfo->untestedTerms flag means that this OR term
99561           ** contained one or more AND term from a notReady table.  The
99562           ** terms from the notReady table could not be tested and will
99563           ** need to be tested later.
99564           */
99565           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
99566
99567           /* Finish the loop through table entries that match term pOrTerm. */
99568           sqlite3WhereEnd(pSubWInfo);
99569         }
99570       }
99571     }
99572     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
99573     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
99574     sqlite3VdbeResolveLabel(v, iLoopBody);
99575
99576     if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
99577     if( !untestedTerms ) disableTerm(pLevel, pTerm);
99578   }else
99579 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
99580
99581   {
99582     /* Case 5:  There is no usable index.  We must do a complete
99583     **          scan of the entire table.
99584     */
99585     static const u8 aStep[] = { OP_Next, OP_Prev };
99586     static const u8 aStart[] = { OP_Rewind, OP_Last };
99587     assert( bRev==0 || bRev==1 );
99588     assert( omitTable==0 );
99589     pLevel->op = aStep[bRev];
99590     pLevel->p1 = iCur;
99591     pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
99592     pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
99593   }
99594   notReady &= ~getMask(pWC->pMaskSet, iCur);
99595
99596   /* Insert code to test every subexpression that can be completely
99597   ** computed using the current set of tables.
99598   **
99599   ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
99600   ** the use of indices become tests that are evaluated against each row of
99601   ** the relevant input tables.
99602   */
99603   k = 0;
99604   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
99605     Expr *pE;
99606     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
99607     testcase( pTerm->wtFlags & TERM_CODED );
99608     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
99609     if( (pTerm->prereqAll & notReady)!=0 ){
99610       testcase( pWInfo->untestedTerms==0
99611                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
99612       pWInfo->untestedTerms = 1;
99613       continue;
99614     }
99615     pE = pTerm->pExpr;
99616     assert( pE!=0 );
99617     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
99618       continue;
99619     }
99620     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
99621     k = 1;
99622     pTerm->wtFlags |= TERM_CODED;
99623   }
99624
99625   /* For a LEFT OUTER JOIN, generate code that will record the fact that
99626   ** at least one row of the right table has matched the left table.  
99627   */
99628   if( pLevel->iLeftJoin ){
99629     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
99630     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
99631     VdbeComment((v, "record LEFT JOIN hit"));
99632     sqlite3ExprCacheClear(pParse);
99633     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
99634       testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */
99635       testcase( pTerm->wtFlags & TERM_CODED );
99636       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
99637       if( (pTerm->prereqAll & notReady)!=0 ){
99638         assert( pWInfo->untestedTerms );
99639         continue;
99640       }
99641       assert( pTerm->pExpr );
99642       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
99643       pTerm->wtFlags |= TERM_CODED;
99644     }
99645   }
99646   sqlite3ReleaseTempReg(pParse, iReleaseReg);
99647
99648   return notReady;
99649 }
99650
99651 #if defined(SQLITE_TEST)
99652 /*
99653 ** The following variable holds a text description of query plan generated
99654 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
99655 ** overwrites the previous.  This information is used for testing and
99656 ** analysis only.
99657 */
99658 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
99659 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
99660
99661 #endif /* SQLITE_TEST */
99662
99663
99664 /*
99665 ** Free a WhereInfo structure
99666 */
99667 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
99668   if( ALWAYS(pWInfo) ){
99669     int i;
99670     for(i=0; i<pWInfo->nLevel; i++){
99671       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
99672       if( pInfo ){
99673         /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
99674         if( pInfo->needToFreeIdxStr ){
99675           sqlite3_free(pInfo->idxStr);
99676         }
99677         sqlite3DbFree(db, pInfo);
99678       }
99679       if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
99680         Index *pIdx = pWInfo->a[i].plan.u.pIdx;
99681         if( pIdx ){
99682           sqlite3DbFree(db, pIdx->zColAff);
99683           sqlite3DbFree(db, pIdx);
99684         }
99685       }
99686     }
99687     whereClauseClear(pWInfo->pWC);
99688     sqlite3DbFree(db, pWInfo);
99689   }
99690 }
99691
99692
99693 /*
99694 ** Generate the beginning of the loop used for WHERE clause processing.
99695 ** The return value is a pointer to an opaque structure that contains
99696 ** information needed to terminate the loop.  Later, the calling routine
99697 ** should invoke sqlite3WhereEnd() with the return value of this function
99698 ** in order to complete the WHERE clause processing.
99699 **
99700 ** If an error occurs, this routine returns NULL.
99701 **
99702 ** The basic idea is to do a nested loop, one loop for each table in
99703 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
99704 ** same as a SELECT with only a single table in the FROM clause.)  For
99705 ** example, if the SQL is this:
99706 **
99707 **       SELECT * FROM t1, t2, t3 WHERE ...;
99708 **
99709 ** Then the code generated is conceptually like the following:
99710 **
99711 **      foreach row1 in t1 do       \    Code generated
99712 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
99713 **          foreach row3 in t3 do   /
99714 **            ...
99715 **          end                     \    Code generated
99716 **        end                        |-- by sqlite3WhereEnd()
99717 **      end                         /
99718 **
99719 ** Note that the loops might not be nested in the order in which they
99720 ** appear in the FROM clause if a different order is better able to make
99721 ** use of indices.  Note also that when the IN operator appears in
99722 ** the WHERE clause, it might result in additional nested loops for
99723 ** scanning through all values on the right-hand side of the IN.
99724 **
99725 ** There are Btree cursors associated with each table.  t1 uses cursor
99726 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
99727 ** And so forth.  This routine generates code to open those VDBE cursors
99728 ** and sqlite3WhereEnd() generates the code to close them.
99729 **
99730 ** The code that sqlite3WhereBegin() generates leaves the cursors named
99731 ** in pTabList pointing at their appropriate entries.  The [...] code
99732 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
99733 ** data from the various tables of the loop.
99734 **
99735 ** If the WHERE clause is empty, the foreach loops must each scan their
99736 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
99737 ** the tables have indices and there are terms in the WHERE clause that
99738 ** refer to those indices, a complete table scan can be avoided and the
99739 ** code will run much faster.  Most of the work of this routine is checking
99740 ** to see if there are indices that can be used to speed up the loop.
99741 **
99742 ** Terms of the WHERE clause are also used to limit which rows actually
99743 ** make it to the "..." in the middle of the loop.  After each "foreach",
99744 ** terms of the WHERE clause that use only terms in that loop and outer
99745 ** loops are evaluated and if false a jump is made around all subsequent
99746 ** inner loops (or around the "..." if the test occurs within the inner-
99747 ** most loop)
99748 **
99749 ** OUTER JOINS
99750 **
99751 ** An outer join of tables t1 and t2 is conceptally coded as follows:
99752 **
99753 **    foreach row1 in t1 do
99754 **      flag = 0
99755 **      foreach row2 in t2 do
99756 **        start:
99757 **          ...
99758 **          flag = 1
99759 **      end
99760 **      if flag==0 then
99761 **        move the row2 cursor to a null row
99762 **        goto start
99763 **      fi
99764 **    end
99765 **
99766 ** ORDER BY CLAUSE PROCESSING
99767 **
99768 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
99769 ** if there is one.  If there is no ORDER BY clause or if this routine
99770 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
99771 **
99772 ** If an index can be used so that the natural output order of the table
99773 ** scan is correct for the ORDER BY clause, then that index is used and
99774 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
99775 ** unnecessary sort of the result set if an index appropriate for the
99776 ** ORDER BY clause already exists.
99777 **
99778 ** If the where clause loops cannot be arranged to provide the correct
99779 ** output order, then the *ppOrderBy is unchanged.
99780 */
99781 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
99782   Parse *pParse,        /* The parser context */
99783   SrcList *pTabList,    /* A list of all tables to be scanned */
99784   Expr *pWhere,         /* The WHERE clause */
99785   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
99786   u16 wctrlFlags        /* One of the WHERE_* flags defined in sqliteInt.h */
99787 ){
99788   int i;                     /* Loop counter */
99789   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
99790   int nTabList;              /* Number of elements in pTabList */
99791   WhereInfo *pWInfo;         /* Will become the return value of this function */
99792   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
99793   Bitmask notReady;          /* Cursors that are not yet positioned */
99794   WhereMaskSet *pMaskSet;    /* The expression mask set */
99795   WhereClause *pWC;               /* Decomposition of the WHERE clause */
99796   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
99797   WhereLevel *pLevel;             /* A single level in the pWInfo list */
99798   int iFrom;                      /* First unused FROM clause element */
99799   int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
99800   sqlite3 *db;               /* Database connection */
99801
99802   /* The number of tables in the FROM clause is limited by the number of
99803   ** bits in a Bitmask 
99804   */
99805   testcase( pTabList->nSrc==BMS );
99806   if( pTabList->nSrc>BMS ){
99807     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
99808     return 0;
99809   }
99810
99811   /* This function normally generates a nested loop for all tables in 
99812   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
99813   ** only generate code for the first table in pTabList and assume that
99814   ** any cursors associated with subsequent tables are uninitialized.
99815   */
99816   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
99817
99818   /* Allocate and initialize the WhereInfo structure that will become the
99819   ** return value. A single allocation is used to store the WhereInfo
99820   ** struct, the contents of WhereInfo.a[], the WhereClause structure
99821   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
99822   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
99823   ** some architectures. Hence the ROUND8() below.
99824   */
99825   db = pParse->db;
99826   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
99827   pWInfo = sqlite3DbMallocZero(db, 
99828       nByteWInfo + 
99829       sizeof(WhereClause) +
99830       sizeof(WhereMaskSet)
99831   );
99832   if( db->mallocFailed ){
99833     sqlite3DbFree(db, pWInfo);
99834     pWInfo = 0;
99835     goto whereBeginError;
99836   }
99837   pWInfo->nLevel = nTabList;
99838   pWInfo->pParse = pParse;
99839   pWInfo->pTabList = pTabList;
99840   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
99841   pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
99842   pWInfo->wctrlFlags = wctrlFlags;
99843   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
99844   pMaskSet = (WhereMaskSet*)&pWC[1];
99845
99846   /* Split the WHERE clause into separate subexpressions where each
99847   ** subexpression is separated by an AND operator.
99848   */
99849   initMaskSet(pMaskSet);
99850   whereClauseInit(pWC, pParse, pMaskSet);
99851   sqlite3ExprCodeConstants(pParse, pWhere);
99852   whereSplit(pWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */
99853     
99854   /* Special case: a WHERE clause that is constant.  Evaluate the
99855   ** expression and either jump over all of the code or fall thru.
99856   */
99857   if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
99858     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
99859     pWhere = 0;
99860   }
99861
99862   /* Assign a bit from the bitmask to every term in the FROM clause.
99863   **
99864   ** When assigning bitmask values to FROM clause cursors, it must be
99865   ** the case that if X is the bitmask for the N-th FROM clause term then
99866   ** the bitmask for all FROM clause terms to the left of the N-th term
99867   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
99868   ** its Expr.iRightJoinTable value to find the bitmask of the right table
99869   ** of the join.  Subtracting one from the right table bitmask gives a
99870   ** bitmask for all tables to the left of the join.  Knowing the bitmask
99871   ** for all tables to the left of a left join is important.  Ticket #3015.
99872   **
99873   ** Configure the WhereClause.vmask variable so that bits that correspond
99874   ** to virtual table cursors are set. This is used to selectively disable 
99875   ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful 
99876   ** with virtual tables.
99877   **
99878   ** Note that bitmasks are created for all pTabList->nSrc tables in
99879   ** pTabList, not just the first nTabList tables.  nTabList is normally
99880   ** equal to pTabList->nSrc but might be shortened to 1 if the
99881   ** WHERE_ONETABLE_ONLY flag is set.
99882   */
99883   assert( pWC->vmask==0 && pMaskSet->n==0 );
99884   for(i=0; i<pTabList->nSrc; i++){
99885     createMask(pMaskSet, pTabList->a[i].iCursor);
99886 #ifndef SQLITE_OMIT_VIRTUALTABLE
99887     if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
99888       pWC->vmask |= ((Bitmask)1 << i);
99889     }
99890 #endif
99891   }
99892 #ifndef NDEBUG
99893   {
99894     Bitmask toTheLeft = 0;
99895     for(i=0; i<pTabList->nSrc; i++){
99896       Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
99897       assert( (m-1)==toTheLeft );
99898       toTheLeft |= m;
99899     }
99900   }
99901 #endif
99902
99903   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
99904   ** add new virtual terms onto the end of the WHERE clause.  We do not
99905   ** want to analyze these virtual terms, so start analyzing at the end
99906   ** and work forward so that the added virtual terms are never processed.
99907   */
99908   exprAnalyzeAll(pTabList, pWC);
99909   if( db->mallocFailed ){
99910     goto whereBeginError;
99911   }
99912
99913   /* Chose the best index to use for each table in the FROM clause.
99914   **
99915   ** This loop fills in the following fields:
99916   **
99917   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
99918   **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
99919   **   pWInfo->a[].nEq       The number of == and IN constraints
99920   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
99921   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
99922   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
99923   **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
99924   **
99925   ** This loop also figures out the nesting order of tables in the FROM
99926   ** clause.
99927   */
99928   notReady = ~(Bitmask)0;
99929   pTabItem = pTabList->a;
99930   pLevel = pWInfo->a;
99931   andFlags = ~0;
99932   WHERETRACE(("*** Optimizer Start ***\n"));
99933   for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
99934     WhereCost bestPlan;         /* Most efficient plan seen so far */
99935     Index *pIdx;                /* Index for FROM table at pTabItem */
99936     int j;                      /* For looping over FROM tables */
99937     int bestJ = -1;             /* The value of j */
99938     Bitmask m;                  /* Bitmask value for j or bestJ */
99939     int isOptimal;              /* Iterator for optimal/non-optimal search */
99940     int nUnconstrained;         /* Number tables without INDEXED BY */
99941     Bitmask notIndexed;         /* Mask of tables that cannot use an index */
99942
99943     memset(&bestPlan, 0, sizeof(bestPlan));
99944     bestPlan.rCost = SQLITE_BIG_DBL;
99945     WHERETRACE(("*** Begin search for loop %d ***\n", i));
99946
99947     /* Loop through the remaining entries in the FROM clause to find the
99948     ** next nested loop. The loop tests all FROM clause entries
99949     ** either once or twice. 
99950     **
99951     ** The first test is always performed if there are two or more entries
99952     ** remaining and never performed if there is only one FROM clause entry
99953     ** to choose from.  The first test looks for an "optimal" scan.  In
99954     ** this context an optimal scan is one that uses the same strategy
99955     ** for the given FROM clause entry as would be selected if the entry
99956     ** were used as the innermost nested loop.  In other words, a table
99957     ** is chosen such that the cost of running that table cannot be reduced
99958     ** by waiting for other tables to run first.  This "optimal" test works
99959     ** by first assuming that the FROM clause is on the inner loop and finding
99960     ** its query plan, then checking to see if that query plan uses any
99961     ** other FROM clause terms that are notReady.  If no notReady terms are
99962     ** used then the "optimal" query plan works.
99963     **
99964     ** Note that the WhereCost.nRow parameter for an optimal scan might
99965     ** not be as small as it would be if the table really were the innermost
99966     ** join.  The nRow value can be reduced by WHERE clause constraints
99967     ** that do not use indices.  But this nRow reduction only happens if the
99968     ** table really is the innermost join.  
99969     **
99970     ** The second loop iteration is only performed if no optimal scan
99971     ** strategies were found by the first iteration. This second iteration
99972     ** is used to search for the lowest cost scan overall.
99973     **
99974     ** Previous versions of SQLite performed only the second iteration -
99975     ** the next outermost loop was always that with the lowest overall
99976     ** cost. However, this meant that SQLite could select the wrong plan
99977     ** for scripts such as the following:
99978     **   
99979     **   CREATE TABLE t1(a, b); 
99980     **   CREATE TABLE t2(c, d);
99981     **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
99982     **
99983     ** The best strategy is to iterate through table t1 first. However it
99984     ** is not possible to determine this with a simple greedy algorithm.
99985     ** Since the cost of a linear scan through table t2 is the same 
99986     ** as the cost of a linear scan through table t1, a simple greedy 
99987     ** algorithm may choose to use t2 for the outer loop, which is a much
99988     ** costlier approach.
99989     */
99990     nUnconstrained = 0;
99991     notIndexed = 0;
99992     for(isOptimal=(iFrom<nTabList-1); isOptimal>=0 && bestJ<0; isOptimal--){
99993       Bitmask mask;             /* Mask of tables not yet ready */
99994       for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
99995         int doNotReorder;    /* True if this table should not be reordered */
99996         WhereCost sCost;     /* Cost information from best[Virtual]Index() */
99997         ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
99998   
99999         doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
100000         if( j!=iFrom && doNotReorder ) break;
100001         m = getMask(pMaskSet, pTabItem->iCursor);
100002         if( (m & notReady)==0 ){
100003           if( j==iFrom ) iFrom++;
100004           continue;
100005         }
100006         mask = (isOptimal ? m : notReady);
100007         pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
100008         if( pTabItem->pIndex==0 ) nUnconstrained++;
100009   
100010         WHERETRACE(("=== trying table %d with isOptimal=%d ===\n",
100011                     j, isOptimal));
100012         assert( pTabItem->pTab );
100013 #ifndef SQLITE_OMIT_VIRTUALTABLE
100014         if( IsVirtual(pTabItem->pTab) ){
100015           sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
100016           bestVirtualIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
100017                            &sCost, pp);
100018         }else 
100019 #endif
100020         {
100021           bestBtreeIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
100022                          &sCost);
100023         }
100024         assert( isOptimal || (sCost.used&notReady)==0 );
100025
100026         /* If an INDEXED BY clause is present, then the plan must use that
100027         ** index if it uses any index at all */
100028         assert( pTabItem->pIndex==0 
100029                   || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
100030                   || sCost.plan.u.pIdx==pTabItem->pIndex );
100031
100032         if( isOptimal && (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
100033           notIndexed |= m;
100034         }
100035
100036         /* Conditions under which this table becomes the best so far:
100037         **
100038         **   (1) The table must not depend on other tables that have not
100039         **       yet run.
100040         **
100041         **   (2) A full-table-scan plan cannot supercede another plan unless
100042         **       it is an "optimal" plan as defined above.
100043         **
100044         **   (3) All tables have an INDEXED BY clause or this table lacks an
100045         **       INDEXED BY clause or this table uses the specific
100046         **       index specified by its INDEXED BY clause.  This rule ensures
100047         **       that a best-so-far is always selected even if an impossible
100048         **       combination of INDEXED BY clauses are given.  The error
100049         **       will be detected and relayed back to the application later.
100050         **       The NEVER() comes about because rule (2) above prevents
100051         **       An indexable full-table-scan from reaching rule (3).
100052         **
100053         **   (4) The plan cost must be lower than prior plans or else the
100054         **       cost must be the same and the number of rows must be lower.
100055         */
100056         if( (sCost.used&notReady)==0                       /* (1) */
100057             && (bestJ<0 || (notIndexed&m)!=0               /* (2) */
100058                 || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0)
100059             && (nUnconstrained==0 || pTabItem->pIndex==0   /* (3) */
100060                 || NEVER((sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
100061             && (bestJ<0 || sCost.rCost<bestPlan.rCost      /* (4) */
100062                 || (sCost.rCost<=bestPlan.rCost 
100063                  && sCost.plan.nRow<bestPlan.plan.nRow))
100064         ){
100065           WHERETRACE(("=== table %d is best so far"
100066                       " with cost=%g and nRow=%g\n",
100067                       j, sCost.rCost, sCost.plan.nRow));
100068           bestPlan = sCost;
100069           bestJ = j;
100070         }
100071         if( doNotReorder ) break;
100072       }
100073     }
100074     assert( bestJ>=0 );
100075     assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
100076     WHERETRACE(("*** Optimizer selects table %d for loop %d"
100077                 " with cost=%g and nRow=%g\n",
100078                 bestJ, pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow));
100079     if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
100080       *ppOrderBy = 0;
100081     }
100082     andFlags &= bestPlan.plan.wsFlags;
100083     pLevel->plan = bestPlan.plan;
100084     testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
100085     testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
100086     if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
100087       pLevel->iIdxCur = pParse->nTab++;
100088     }else{
100089       pLevel->iIdxCur = -1;
100090     }
100091     notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
100092     pLevel->iFrom = (u8)bestJ;
100093     if( bestPlan.plan.nRow>=(double)1 ){
100094       pParse->nQueryLoop *= bestPlan.plan.nRow;
100095     }
100096
100097     /* Check that if the table scanned by this loop iteration had an
100098     ** INDEXED BY clause attached to it, that the named index is being
100099     ** used for the scan. If not, then query compilation has failed.
100100     ** Return an error.
100101     */
100102     pIdx = pTabList->a[bestJ].pIndex;
100103     if( pIdx ){
100104       if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
100105         sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
100106         goto whereBeginError;
100107       }else{
100108         /* If an INDEXED BY clause is used, the bestIndex() function is
100109         ** guaranteed to find the index specified in the INDEXED BY clause
100110         ** if it find an index at all. */
100111         assert( bestPlan.plan.u.pIdx==pIdx );
100112       }
100113     }
100114   }
100115   WHERETRACE(("*** Optimizer Finished ***\n"));
100116   if( pParse->nErr || db->mallocFailed ){
100117     goto whereBeginError;
100118   }
100119
100120   /* If the total query only selects a single row, then the ORDER BY
100121   ** clause is irrelevant.
100122   */
100123   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
100124     *ppOrderBy = 0;
100125   }
100126
100127   /* If the caller is an UPDATE or DELETE statement that is requesting
100128   ** to use a one-pass algorithm, determine if this is appropriate.
100129   ** The one-pass algorithm only works if the WHERE clause constraints
100130   ** the statement to update a single row.
100131   */
100132   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
100133   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
100134     pWInfo->okOnePass = 1;
100135     pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
100136   }
100137
100138   /* Open all tables in the pTabList and any indices selected for
100139   ** searching those tables.
100140   */
100141   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
100142   notReady = ~(Bitmask)0;
100143   pWInfo->nRowOut = (double)1;
100144   for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
100145     Table *pTab;     /* Table to open */
100146     int iDb;         /* Index of database containing table/index */
100147
100148     pTabItem = &pTabList->a[pLevel->iFrom];
100149     pTab = pTabItem->pTab;
100150     pLevel->iTabCur = pTabItem->iCursor;
100151     pWInfo->nRowOut *= pLevel->plan.nRow;
100152     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
100153     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
100154       /* Do nothing */
100155     }else
100156 #ifndef SQLITE_OMIT_VIRTUALTABLE
100157     if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
100158       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
100159       int iCur = pTabItem->iCursor;
100160       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
100161     }else
100162 #endif
100163     if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
100164          && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
100165       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
100166       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
100167       testcase( pTab->nCol==BMS-1 );
100168       testcase( pTab->nCol==BMS );
100169       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
100170         Bitmask b = pTabItem->colUsed;
100171         int n = 0;
100172         for(; b; b=b>>1, n++){}
100173         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, 
100174                             SQLITE_INT_TO_PTR(n), P4_INT32);
100175         assert( n<=pTab->nCol );
100176       }
100177     }else{
100178       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
100179     }
100180 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
100181     if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
100182       constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);
100183     }else
100184 #endif
100185     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
100186       Index *pIx = pLevel->plan.u.pIdx;
100187       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
100188       int iIdxCur = pLevel->iIdxCur;
100189       assert( pIx->pSchema==pTab->pSchema );
100190       assert( iIdxCur>=0 );
100191       sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
100192                         (char*)pKey, P4_KEYINFO_HANDOFF);
100193       VdbeComment((v, "%s", pIx->zName));
100194     }
100195     sqlite3CodeVerifySchema(pParse, iDb);
100196     notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);
100197   }
100198   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
100199   if( db->mallocFailed ) goto whereBeginError;
100200
100201   /* Generate the code to do the search.  Each iteration of the for
100202   ** loop below generates code for a single nested loop of the VM
100203   ** program.
100204   */
100205   notReady = ~(Bitmask)0;
100206   for(i=0; i<nTabList; i++){
100207     pLevel = &pWInfo->a[i];
100208     explainOneScan(pParse, pTabList, pLevel, i, pLevel->iFrom, wctrlFlags);
100209     notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
100210     pWInfo->iContinue = pLevel->addrCont;
100211   }
100212
100213 #ifdef SQLITE_TEST  /* For testing and debugging use only */
100214   /* Record in the query plan information about the current table
100215   ** and the index used to access it (if any).  If the table itself
100216   ** is not used, its name is just '{}'.  If no index is used
100217   ** the index is listed as "{}".  If the primary key is used the
100218   ** index name is '*'.
100219   */
100220   for(i=0; i<nTabList; i++){
100221     char *z;
100222     int n;
100223     pLevel = &pWInfo->a[i];
100224     pTabItem = &pTabList->a[pLevel->iFrom];
100225     z = pTabItem->zAlias;
100226     if( z==0 ) z = pTabItem->pTab->zName;
100227     n = sqlite3Strlen30(z);
100228     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
100229       if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
100230         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
100231         nQPlan += 2;
100232       }else{
100233         memcpy(&sqlite3_query_plan[nQPlan], z, n);
100234         nQPlan += n;
100235       }
100236       sqlite3_query_plan[nQPlan++] = ' ';
100237     }
100238     testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
100239     testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
100240     if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
100241       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
100242       nQPlan += 2;
100243     }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
100244       n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
100245       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
100246         memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
100247         nQPlan += n;
100248         sqlite3_query_plan[nQPlan++] = ' ';
100249       }
100250     }else{
100251       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
100252       nQPlan += 3;
100253     }
100254   }
100255   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
100256     sqlite3_query_plan[--nQPlan] = 0;
100257   }
100258   sqlite3_query_plan[nQPlan] = 0;
100259   nQPlan = 0;
100260 #endif /* SQLITE_TEST // Testing and debugging use only */
100261
100262   /* Record the continuation address in the WhereInfo structure.  Then
100263   ** clean up and return.
100264   */
100265   return pWInfo;
100266
100267   /* Jump here if malloc fails */
100268 whereBeginError:
100269   if( pWInfo ){
100270     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
100271     whereInfoFree(db, pWInfo);
100272   }
100273   return 0;
100274 }
100275
100276 /*
100277 ** Generate the end of the WHERE loop.  See comments on 
100278 ** sqlite3WhereBegin() for additional information.
100279 */
100280 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
100281   Parse *pParse = pWInfo->pParse;
100282   Vdbe *v = pParse->pVdbe;
100283   int i;
100284   WhereLevel *pLevel;
100285   SrcList *pTabList = pWInfo->pTabList;
100286   sqlite3 *db = pParse->db;
100287
100288   /* Generate loop termination code.
100289   */
100290   sqlite3ExprCacheClear(pParse);
100291   for(i=pWInfo->nLevel-1; i>=0; i--){
100292     pLevel = &pWInfo->a[i];
100293     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
100294     if( pLevel->op!=OP_Noop ){
100295       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
100296       sqlite3VdbeChangeP5(v, pLevel->p5);
100297     }
100298     if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
100299       struct InLoop *pIn;
100300       int j;
100301       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
100302       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
100303         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
100304         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
100305         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
100306       }
100307       sqlite3DbFree(db, pLevel->u.in.aInLoop);
100308     }
100309     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
100310     if( pLevel->iLeftJoin ){
100311       int addr;
100312       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
100313       assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
100314            || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
100315       if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
100316         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
100317       }
100318       if( pLevel->iIdxCur>=0 ){
100319         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
100320       }
100321       if( pLevel->op==OP_Return ){
100322         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
100323       }else{
100324         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
100325       }
100326       sqlite3VdbeJumpHere(v, addr);
100327     }
100328   }
100329
100330   /* The "break" point is here, just past the end of the outer loop.
100331   ** Set it.
100332   */
100333   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
100334
100335   /* Close all of the cursors that were opened by sqlite3WhereBegin.
100336   */
100337   assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
100338   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
100339     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
100340     Table *pTab = pTabItem->pTab;
100341     assert( pTab!=0 );
100342     if( (pTab->tabFlags & TF_Ephemeral)==0
100343      && pTab->pSelect==0
100344      && (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0
100345     ){
100346       int ws = pLevel->plan.wsFlags;
100347       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
100348         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
100349       }
100350       if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
100351         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
100352       }
100353     }
100354
100355     /* If this scan uses an index, make code substitutions to read data
100356     ** from the index in preference to the table. Sometimes, this means
100357     ** the table need never be read from. This is a performance boost,
100358     ** as the vdbe level waits until the table is read before actually
100359     ** seeking the table cursor to the record corresponding to the current
100360     ** position in the index.
100361     ** 
100362     ** Calls to the code generator in between sqlite3WhereBegin and
100363     ** sqlite3WhereEnd will have created code that references the table
100364     ** directly.  This loop scans all that code looking for opcodes
100365     ** that reference the table and converts them into opcodes that
100366     ** reference the index.
100367     */
100368     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
100369       int k, j, last;
100370       VdbeOp *pOp;
100371       Index *pIdx = pLevel->plan.u.pIdx;
100372
100373       assert( pIdx!=0 );
100374       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
100375       last = sqlite3VdbeCurrentAddr(v);
100376       for(k=pWInfo->iTop; k<last; k++, pOp++){
100377         if( pOp->p1!=pLevel->iTabCur ) continue;
100378         if( pOp->opcode==OP_Column ){
100379           for(j=0; j<pIdx->nColumn; j++){
100380             if( pOp->p2==pIdx->aiColumn[j] ){
100381               pOp->p2 = j;
100382               pOp->p1 = pLevel->iIdxCur;
100383               break;
100384             }
100385           }
100386           assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
100387                || j<pIdx->nColumn );
100388         }else if( pOp->opcode==OP_Rowid ){
100389           pOp->p1 = pLevel->iIdxCur;
100390           pOp->opcode = OP_IdxRowid;
100391         }
100392       }
100393     }
100394   }
100395
100396   /* Final cleanup
100397   */
100398   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
100399   whereInfoFree(db, pWInfo);
100400   return;
100401 }
100402
100403 /************** End of where.c ***********************************************/
100404 /************** Begin file parse.c *******************************************/
100405 /* Driver template for the LEMON parser generator.
100406 ** The author disclaims copyright to this source code.
100407 **
100408 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
100409 ** The only modifications are the addition of a couple of NEVER()
100410 ** macros to disable tests that are needed in the case of a general
100411 ** LALR(1) grammar but which are always false in the
100412 ** specific grammar used by SQLite.
100413 */
100414 /* First off, code is included that follows the "include" declaration
100415 ** in the input grammar file. */
100416
100417
100418 /*
100419 ** Disable all error recovery processing in the parser push-down
100420 ** automaton.
100421 */
100422 #define YYNOERRORRECOVERY 1
100423
100424 /*
100425 ** Make yytestcase() the same as testcase()
100426 */
100427 #define yytestcase(X) testcase(X)
100428
100429 /*
100430 ** An instance of this structure holds information about the
100431 ** LIMIT clause of a SELECT statement.
100432 */
100433 struct LimitVal {
100434   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
100435   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
100436 };
100437
100438 /*
100439 ** An instance of this structure is used to store the LIKE,
100440 ** GLOB, NOT LIKE, and NOT GLOB operators.
100441 */
100442 struct LikeOp {
100443   Token eOperator;  /* "like" or "glob" or "regexp" */
100444   int not;         /* True if the NOT keyword is present */
100445 };
100446
100447 /*
100448 ** An instance of the following structure describes the event of a
100449 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
100450 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
100451 **
100452 **      UPDATE ON (a,b,c)
100453 **
100454 ** Then the "b" IdList records the list "a,b,c".
100455 */
100456 struct TrigEvent { int a; IdList * b; };
100457
100458 /*
100459 ** An instance of this structure holds the ATTACH key and the key type.
100460 */
100461 struct AttachKey { int type;  Token key; };
100462
100463
100464   /* This is a utility routine used to set the ExprSpan.zStart and
100465   ** ExprSpan.zEnd values of pOut so that the span covers the complete
100466   ** range of text beginning with pStart and going to the end of pEnd.
100467   */
100468   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
100469     pOut->zStart = pStart->z;
100470     pOut->zEnd = &pEnd->z[pEnd->n];
100471   }
100472
100473   /* Construct a new Expr object from a single identifier.  Use the
100474   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
100475   ** that created the expression.
100476   */
100477   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
100478     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
100479     pOut->zStart = pValue->z;
100480     pOut->zEnd = &pValue->z[pValue->n];
100481   }
100482
100483   /* This routine constructs a binary expression node out of two ExprSpan
100484   ** objects and uses the result to populate a new ExprSpan object.
100485   */
100486   static void spanBinaryExpr(
100487     ExprSpan *pOut,     /* Write the result here */
100488     Parse *pParse,      /* The parsing context.  Errors accumulate here */
100489     int op,             /* The binary operation */
100490     ExprSpan *pLeft,    /* The left operand */
100491     ExprSpan *pRight    /* The right operand */
100492   ){
100493     pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
100494     pOut->zStart = pLeft->zStart;
100495     pOut->zEnd = pRight->zEnd;
100496   }
100497
100498   /* Construct an expression node for a unary postfix operator
100499   */
100500   static void spanUnaryPostfix(
100501     ExprSpan *pOut,        /* Write the new expression node here */
100502     Parse *pParse,         /* Parsing context to record errors */
100503     int op,                /* The operator */
100504     ExprSpan *pOperand,    /* The operand */
100505     Token *pPostOp         /* The operand token for setting the span */
100506   ){
100507     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
100508     pOut->zStart = pOperand->zStart;
100509     pOut->zEnd = &pPostOp->z[pPostOp->n];
100510   }                           
100511
100512   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
100513   ** unary TK_ISNULL or TK_NOTNULL expression. */
100514   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
100515     sqlite3 *db = pParse->db;
100516     if( db->mallocFailed==0 && pY->op==TK_NULL ){
100517       pA->op = (u8)op;
100518       sqlite3ExprDelete(db, pA->pRight);
100519       pA->pRight = 0;
100520     }
100521   }
100522
100523   /* Construct an expression node for a unary prefix operator
100524   */
100525   static void spanUnaryPrefix(
100526     ExprSpan *pOut,        /* Write the new expression node here */
100527     Parse *pParse,         /* Parsing context to record errors */
100528     int op,                /* The operator */
100529     ExprSpan *pOperand,    /* The operand */
100530     Token *pPreOp         /* The operand token for setting the span */
100531   ){
100532     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
100533     pOut->zStart = pPreOp->z;
100534     pOut->zEnd = pOperand->zEnd;
100535   }
100536 /* Next is all token values, in a form suitable for use by makeheaders.
100537 ** This section will be null unless lemon is run with the -m switch.
100538 */
100539 /* 
100540 ** These constants (all generated automatically by the parser generator)
100541 ** specify the various kinds of tokens (terminals) that the parser
100542 ** understands. 
100543 **
100544 ** Each symbol here is a terminal symbol in the grammar.
100545 */
100546 /* Make sure the INTERFACE macro is defined.
100547 */
100548 #ifndef INTERFACE
100549 # define INTERFACE 1
100550 #endif
100551 /* The next thing included is series of defines which control
100552 ** various aspects of the generated parser.
100553 **    YYCODETYPE         is the data type used for storing terminal
100554 **                       and nonterminal numbers.  "unsigned char" is
100555 **                       used if there are fewer than 250 terminals
100556 **                       and nonterminals.  "int" is used otherwise.
100557 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
100558 **                       to no legal terminal or nonterminal number.  This
100559 **                       number is used to fill in empty slots of the hash 
100560 **                       table.
100561 **    YYFALLBACK         If defined, this indicates that one or more tokens
100562 **                       have fall-back values which should be used if the
100563 **                       original value of the token will not parse.
100564 **    YYACTIONTYPE       is the data type used for storing terminal
100565 **                       and nonterminal numbers.  "unsigned char" is
100566 **                       used if there are fewer than 250 rules and
100567 **                       states combined.  "int" is used otherwise.
100568 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given 
100569 **                       directly to the parser from the tokenizer.
100570 **    YYMINORTYPE        is the data type used for all minor tokens.
100571 **                       This is typically a union of many types, one of
100572 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
100573 **                       for base tokens is called "yy0".
100574 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
100575 **                       zero the stack is dynamically sized using realloc()
100576 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
100577 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
100578 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
100579 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
100580 **    YYNSTATE           the combined number of states.
100581 **    YYNRULE            the number of rules in the grammar
100582 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
100583 **                       defined, then do no error processing.
100584 */
100585 #define YYCODETYPE unsigned char
100586 #define YYNOCODE 253
100587 #define YYACTIONTYPE unsigned short int
100588 #define YYWILDCARD 67
100589 #define sqlite3ParserTOKENTYPE Token
100590 typedef union {
100591   int yyinit;
100592   sqlite3ParserTOKENTYPE yy0;
100593   int yy4;
100594   struct TrigEvent yy90;
100595   ExprSpan yy118;
100596   TriggerStep* yy203;
100597   u8 yy210;
100598   struct {int value; int mask;} yy215;
100599   SrcList* yy259;
100600   struct LimitVal yy292;
100601   Expr* yy314;
100602   ExprList* yy322;
100603   struct LikeOp yy342;
100604   IdList* yy384;
100605   Select* yy387;
100606 } YYMINORTYPE;
100607 #ifndef YYSTACKDEPTH
100608 #define YYSTACKDEPTH 100
100609 #endif
100610 #define sqlite3ParserARG_SDECL Parse *pParse;
100611 #define sqlite3ParserARG_PDECL ,Parse *pParse
100612 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
100613 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
100614 #define YYNSTATE 630
100615 #define YYNRULE 329
100616 #define YYFALLBACK 1
100617 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
100618 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
100619 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
100620
100621 /* The yyzerominor constant is used to initialize instances of
100622 ** YYMINORTYPE objects to zero. */
100623 static const YYMINORTYPE yyzerominor = { 0 };
100624
100625 /* Define the yytestcase() macro to be a no-op if is not already defined
100626 ** otherwise.
100627 **
100628 ** Applications can choose to define yytestcase() in the %include section
100629 ** to a macro that can assist in verifying code coverage.  For production
100630 ** code the yytestcase() macro should be turned off.  But it is useful
100631 ** for testing.
100632 */
100633 #ifndef yytestcase
100634 # define yytestcase(X)
100635 #endif
100636
100637
100638 /* Next are the tables used to determine what action to take based on the
100639 ** current state and lookahead token.  These tables are used to implement
100640 ** functions that take a state number and lookahead value and return an
100641 ** action integer.  
100642 **
100643 ** Suppose the action integer is N.  Then the action is determined as
100644 ** follows
100645 **
100646 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
100647 **                                      token onto the stack and goto state N.
100648 **
100649 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
100650 **
100651 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
100652 **
100653 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
100654 **
100655 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
100656 **                                      slots in the yy_action[] table.
100657 **
100658 ** The action table is constructed as a single large table named yy_action[].
100659 ** Given state S and lookahead X, the action is computed as
100660 **
100661 **      yy_action[ yy_shift_ofst[S] + X ]
100662 **
100663 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
100664 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
100665 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
100666 ** and that yy_default[S] should be used instead.  
100667 **
100668 ** The formula above is for computing the action when the lookahead is
100669 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
100670 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
100671 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
100672 ** YY_SHIFT_USE_DFLT.
100673 **
100674 ** The following are the tables generated in this section:
100675 **
100676 **  yy_action[]        A single table containing all actions.
100677 **  yy_lookahead[]     A table containing the lookahead for each entry in
100678 **                     yy_action.  Used to detect hash collisions.
100679 **  yy_shift_ofst[]    For each state, the offset into yy_action for
100680 **                     shifting terminals.
100681 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
100682 **                     shifting non-terminals after a reduce.
100683 **  yy_default[]       Default action for each state.
100684 */
100685 #define YY_ACTTAB_COUNT (1557)
100686 static const YYACTIONTYPE yy_action[] = {
100687  /*     0 */   313,  960,  186,  419,    2,  172,  627,  597,   55,   55,
100688  /*    10 */    55,   55,   48,   53,   53,   53,   53,   52,   52,   51,
100689  /*    20 */    51,   51,   50,  238,  302,  283,  623,  622,  516,  515,
100690  /*    30 */   590,  584,   55,   55,   55,   55,  282,   53,   53,   53,
100691  /*    40 */    53,   52,   52,   51,   51,   51,   50,  238,    6,   56,
100692  /*    50 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
100693  /*    60 */    55,   55,  608,   53,   53,   53,   53,   52,   52,   51,
100694  /*    70 */    51,   51,   50,  238,  313,  597,  409,  330,  579,  579,
100695  /*    80 */    32,   53,   53,   53,   53,   52,   52,   51,   51,   51,
100696  /*    90 */    50,  238,  330,  217,  620,  619,  166,  411,  624,  382,
100697  /*   100 */   379,  378,    7,  491,  590,  584,  200,  199,  198,   58,
100698  /*   110 */   377,  300,  414,  621,  481,   66,  623,  622,  621,  580,
100699  /*   120 */   254,  601,   94,   56,   57,   47,  582,  581,  583,  583,
100700  /*   130 */    54,   54,   55,   55,   55,   55,  671,   53,   53,   53,
100701  /*   140 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  532,
100702  /*   150 */   226,  506,  507,  133,  177,  139,  284,  385,  279,  384,
100703  /*   160 */   169,  197,  342,  398,  251,  226,  253,  275,  388,  167,
100704  /*   170 */   139,  284,  385,  279,  384,  169,  570,  236,  590,  584,
100705  /*   180 */   672,  240,  275,  157,  620,  619,  554,  437,   51,   51,
100706  /*   190 */    51,   50,  238,  343,  439,  553,  438,   56,   57,   47,
100707  /*   200 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
100708  /*   210 */   465,   53,   53,   53,   53,   52,   52,   51,   51,   51,
100709  /*   220 */    50,  238,  313,  390,   52,   52,   51,   51,   51,   50,
100710  /*   230 */   238,  391,  166,  491,  566,  382,  379,  378,  409,  440,
100711  /*   240 */   579,  579,  252,  440,  607,   66,  377,  513,  621,   49,
100712  /*   250 */    46,  147,  590,  584,  621,   16,  466,  189,  621,  441,
100713  /*   260 */   442,  673,  526,  441,  340,  577,  595,   64,  194,  482,
100714  /*   270 */   434,   56,   57,   47,  582,  581,  583,  583,   54,   54,
100715  /*   280 */    55,   55,   55,   55,   30,   53,   53,   53,   53,   52,
100716  /*   290 */    52,   51,   51,   51,   50,  238,  313,  593,  593,  593,
100717  /*   300 */   387,  578,  606,  493,  259,  351,  258,  411,    1,  623,
100718  /*   310 */   622,  496,  623,  622,   65,  240,  623,  622,  597,  443,
100719  /*   320 */   237,  239,  414,  341,  237,  602,  590,  584,   18,  603,
100720  /*   330 */   166,  601,   87,  382,  379,  378,   67,  623,  622,   38,
100721  /*   340 */   623,  622,  176,  270,  377,   56,   57,   47,  582,  581,
100722  /*   350 */   583,  583,   54,   54,   55,   55,   55,   55,  175,   53,
100723  /*   360 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
100724  /*   370 */   313,  396,  233,  411,  531,  565,  317,  620,  619,   44,
100725  /*   380 */   620,  619,  240,  206,  620,  619,  597,  266,  414,  268,
100726  /*   390 */   409,  597,  579,  579,  352,  184,  505,  601,   73,  533,
100727  /*   400 */   590,  584,  466,  548,  190,  620,  619,  576,  620,  619,
100728  /*   410 */   547,  383,  551,   35,  332,  575,  574,  600,  504,   56,
100729  /*   420 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
100730  /*   430 */    55,   55,  567,   53,   53,   53,   53,   52,   52,   51,
100731  /*   440 */    51,   51,   50,  238,  313,  411,  561,  561,  528,  364,
100732  /*   450 */   259,  351,  258,  183,  361,  549,  524,  374,  411,  597,
100733  /*   460 */   414,  240,  560,  560,  409,  604,  579,  579,  328,  601,
100734  /*   470 */    93,  623,  622,  414,  590,  584,  237,  564,  559,  559,
100735  /*   480 */   520,  402,  601,   87,  409,  210,  579,  579,  168,  421,
100736  /*   490 */   950,  519,  950,   56,   57,   47,  582,  581,  583,  583,
100737  /*   500 */    54,   54,   55,   55,   55,   55,  192,   53,   53,   53,
100738  /*   510 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  600,
100739  /*   520 */   293,  563,  511,  234,  357,  146,  475,  475,  367,  411,
100740  /*   530 */   562,  411,  358,  542,  425,  171,  411,  215,  144,  620,
100741  /*   540 */   619,  544,  318,  353,  414,  203,  414,  275,  590,  584,
100742  /*   550 */   549,  414,  174,  601,   94,  601,   79,  558,  471,   61,
100743  /*   560 */   601,   79,  421,  949,  350,  949,   34,   56,   57,   47,
100744  /*   570 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
100745  /*   580 */   535,   53,   53,   53,   53,   52,   52,   51,   51,   51,
100746  /*   590 */    50,  238,  313,  307,  424,  394,  272,   49,   46,  147,
100747  /*   600 */   349,  322,    4,  411,  491,  312,  321,  425,  568,  492,
100748  /*   610 */   216,  264,  407,  575,  574,  429,   66,  549,  414,  621,
100749  /*   620 */   540,  602,  590,  584,   13,  603,  621,  601,   72,   12,
100750  /*   630 */   618,  617,  616,  202,  210,  621,  546,  469,  422,  319,
100751  /*   640 */   148,   56,   57,   47,  582,  581,  583,  583,   54,   54,
100752  /*   650 */    55,   55,   55,   55,  338,   53,   53,   53,   53,   52,
100753  /*   660 */    52,   51,   51,   51,   50,  238,  313,  600,  600,  411,
100754  /*   670 */    39,   21,   37,  170,  237,  875,  411,  572,  572,  201,
100755  /*   680 */   144,  473,  538,  331,  414,  474,  143,  146,  630,  628,
100756  /*   690 */   334,  414,  353,  601,   68,  168,  590,  584,  132,  365,
100757  /*   700 */   601,   96,  307,  423,  530,  336,   49,   46,  147,  568,
100758  /*   710 */   406,  216,  549,  360,  529,   56,   57,   47,  582,  581,
100759  /*   720 */   583,  583,   54,   54,   55,   55,   55,   55,  411,   53,
100760  /*   730 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
100761  /*   740 */   313,  411,  605,  414,  484,  510,  172,  422,  597,  318,
100762  /*   750 */   496,  485,  601,   99,  411,  142,  414,  411,  231,  411,
100763  /*   760 */   540,  411,  359,  629,    2,  601,   97,  426,  308,  414,
100764  /*   770 */   590,  584,  414,   20,  414,  621,  414,  621,  601,  106,
100765  /*   780 */   503,  601,  105,  601,  108,  601,  109,  204,   28,   56,
100766  /*   790 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
100767  /*   800 */    55,   55,  411,   53,   53,   53,   53,   52,   52,   51,
100768  /*   810 */    51,   51,   50,  238,  313,  411,  597,  414,  411,  276,
100769  /*   820 */   214,  600,  411,  366,  213,  381,  601,  134,  274,  500,
100770  /*   830 */   414,  167,  130,  414,  621,  411,  354,  414,  376,  601,
100771  /*   840 */   135,  129,  601,  100,  590,  584,  601,  104,  522,  521,
100772  /*   850 */   414,  621,  224,  273,  600,  167,  327,  282,  600,  601,
100773  /*   860 */   103,  468,  521,   56,   57,   47,  582,  581,  583,  583,
100774  /*   870 */    54,   54,   55,   55,   55,   55,  411,   53,   53,   53,
100775  /*   880 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  411,
100776  /*   890 */    27,  414,  411,  375,  276,  167,  359,  544,   50,  238,
100777  /*   900 */   601,   95,  128,  223,  414,  411,  165,  414,  411,  621,
100778  /*   910 */   411,  621,  612,  601,  102,  372,  601,   76,  590,  584,
100779  /*   920 */   414,  570,  236,  414,  470,  414,  167,  621,  188,  601,
100780  /*   930 */    98,  225,  601,  138,  601,  137,  232,   56,   45,   47,
100781  /*   940 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
100782  /*   950 */   411,   53,   53,   53,   53,   52,   52,   51,   51,   51,
100783  /*   960 */    50,  238,  313,  276,  276,  414,  411,  276,  544,  459,
100784  /*   970 */   359,  171,  209,  479,  601,  136,  628,  334,  621,  621,
100785  /*   980 */   125,  414,  621,  368,  411,  621,  257,  540,  589,  588,
100786  /*   990 */   601,   75,  590,  584,  458,  446,   23,   23,  124,  414,
100787  /*  1000 */   326,  325,  621,  427,  324,  309,  600,  288,  601,   92,
100788  /*  1010 */   586,  585,   57,   47,  582,  581,  583,  583,   54,   54,
100789  /*  1020 */    55,   55,   55,   55,  411,   53,   53,   53,   53,   52,
100790  /*  1030 */    52,   51,   51,   51,   50,  238,  313,  587,  411,  414,
100791  /*  1040 */   411,  207,  611,  476,  171,  472,  160,  123,  601,   91,
100792  /*  1050 */   323,  261,   15,  414,  464,  414,  411,  621,  411,  354,
100793  /*  1060 */   222,  411,  601,   74,  601,   90,  590,  584,  159,  264,
100794  /*  1070 */   158,  414,  461,  414,  621,  600,  414,  121,  120,   25,
100795  /*  1080 */   601,   89,  601,  101,  621,  601,   88,   47,  582,  581,
100796  /*  1090 */   583,  583,   54,   54,   55,   55,   55,   55,  544,   53,
100797  /*  1100 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
100798  /*  1110 */    43,  405,  263,    3,  610,  264,  140,  415,  622,   24,
100799  /*  1120 */   410,   11,  456,  594,  118,  155,  219,  452,  408,  621,
100800  /*  1130 */   621,  621,  156,   43,  405,  621,    3,  286,  621,  113,
100801  /*  1140 */   415,  622,  111,  445,  411,  400,  557,  403,  545,   10,
100802  /*  1150 */   411,  408,  264,  110,  205,  436,  541,  566,  453,  414,
100803  /*  1160 */   621,  621,   63,  621,  435,  414,  411,  621,  601,   94,
100804  /*  1170 */   403,  621,  411,  337,  601,   86,  150,   40,   41,  534,
100805  /*  1180 */   566,  414,  242,  264,   42,  413,  412,  414,  600,  595,
100806  /*  1190 */   601,   85,  191,  333,  107,  451,  601,   84,  621,  539,
100807  /*  1200 */    40,   41,  420,  230,  411,  149,  316,   42,  413,  412,
100808  /*  1210 */   398,  127,  595,  315,  621,  399,  278,  625,  181,  414,
100809  /*  1220 */   593,  593,  593,  592,  591,   14,  450,  411,  601,   71,
100810  /*  1230 */   240,  621,   43,  405,  264,    3,  615,  180,  264,  415,
100811  /*  1240 */   622,  614,  414,  593,  593,  593,  592,  591,   14,  621,
100812  /*  1250 */   408,  601,   70,  621,  417,   33,  405,  613,    3,  411,
100813  /*  1260 */   264,  411,  415,  622,  418,  626,  178,  509,    8,  403,
100814  /*  1270 */   241,  416,  126,  408,  414,  621,  414,  449,  208,  566,
100815  /*  1280 */   240,  221,  621,  601,   83,  601,   82,  599,  297,  277,
100816  /*  1290 */   296,   30,  403,   31,  395,  264,  295,  397,  489,   40,
100817  /*  1300 */    41,  411,  566,  220,  621,  294,   42,  413,  412,  271,
100818  /*  1310 */   621,  595,  600,  621,   59,   60,  414,  269,  267,  623,
100819  /*  1320 */   622,   36,   40,   41,  621,  601,   81,  598,  235,   42,
100820  /*  1330 */   413,  412,  621,  621,  595,  265,  344,  411,  248,  556,
100821  /*  1340 */   173,  185,  593,  593,  593,  592,  591,   14,  218,   29,
100822  /*  1350 */   621,  543,  414,  305,  304,  303,  179,  301,  411,  566,
100823  /*  1360 */   454,  601,   80,  289,  335,  593,  593,  593,  592,  591,
100824  /*  1370 */    14,  411,  287,  414,  151,  392,  246,  260,  411,  196,
100825  /*  1380 */   195,  523,  601,   69,  411,  245,  414,  526,  537,  285,
100826  /*  1390 */   389,  595,  621,  414,  536,  601,   17,  362,  153,  414,
100827  /*  1400 */   466,  463,  601,   78,  154,  414,  462,  152,  601,   77,
100828  /*  1410 */   355,  255,  621,  455,  601,    9,  621,  386,  444,  517,
100829  /*  1420 */   247,  621,  593,  593,  593,  621,  621,  244,  621,  243,
100830  /*  1430 */   430,  518,  292,  621,  329,  621,  145,  393,  280,  513,
100831  /*  1440 */   291,  131,  621,  514,  621,  621,  311,  621,  259,  346,
100832  /*  1450 */   249,  621,  621,  229,  314,  621,  228,  512,  227,  240,
100833  /*  1460 */   494,  488,  310,  164,  487,  486,  373,  480,  163,  262,
100834  /*  1470 */   369,  371,  162,   26,  212,  478,  477,  161,  141,  363,
100835  /*  1480 */   467,  122,  339,  187,  119,  348,  347,  117,  116,  115,
100836  /*  1490 */   114,  112,  182,  457,  320,   22,  433,  432,  448,   19,
100837  /*  1500 */   609,  431,  428,   62,  193,  596,  573,  298,  555,  552,
100838  /*  1510 */   571,  404,  290,  380,  498,  510,  495,  306,  281,  499,
100839  /*  1520 */   250,    5,  497,  460,  345,  447,  569,  550,  238,  299,
100840  /*  1530 */   527,  525,  508,  961,  502,  501,  961,  401,  961,  211,
100841  /*  1540 */   490,  356,  256,  961,  483,  961,  961,  961,  961,  961,
100842  /*  1550 */   961,  961,  961,  961,  961,  961,  370,
100843 };
100844 static const YYCODETYPE yy_lookahead[] = {
100845  /*     0 */    19,  142,  143,  144,  145,   24,    1,   26,   77,   78,
100846  /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
100847  /*    20 */    89,   90,   91,   92,   15,   98,   26,   27,    7,    8,
100848  /*    30 */    49,   50,   77,   78,   79,   80,  109,   82,   83,   84,
100849  /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,   22,   68,
100850  /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
100851  /*    60 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
100852  /*    70 */    89,   90,   91,   92,   19,   94,  112,   19,  114,  115,
100853  /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
100854  /*    90 */    91,   92,   19,   22,   94,   95,   96,  150,  150,   99,
100855  /*   100 */   100,  101,   76,  150,   49,   50,  105,  106,  107,   54,
100856  /*   110 */   110,  158,  165,  165,  161,  162,   26,   27,  165,  113,
100857  /*   120 */    16,  174,  175,   68,   69,   70,   71,   72,   73,   74,
100858  /*   130 */    75,   76,   77,   78,   79,   80,  118,   82,   83,   84,
100859  /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   23,
100860  /*   150 */    92,   97,   98,   24,   96,   97,   98,   99,  100,  101,
100861  /*   160 */   102,   25,   97,  216,   60,   92,   62,  109,  221,   25,
100862  /*   170 */    97,   98,   99,  100,  101,  102,   86,   87,   49,   50,
100863  /*   180 */   118,  116,  109,   25,   94,   95,   32,   97,   88,   89,
100864  /*   190 */    90,   91,   92,  128,  104,   41,  106,   68,   69,   70,
100865  /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
100866  /*   210 */    11,   82,   83,   84,   85,   86,   87,   88,   89,   90,
100867  /*   220 */    91,   92,   19,   19,   86,   87,   88,   89,   90,   91,
100868  /*   230 */    92,   27,   96,  150,   66,   99,  100,  101,  112,  150,
100869  /*   240 */   114,  115,  138,  150,  161,  162,  110,  103,  165,  222,
100870  /*   250 */   223,  224,   49,   50,  165,   22,   57,   24,  165,  170,
100871  /*   260 */   171,  118,   94,  170,  171,   23,   98,   25,  185,  186,
100872  /*   270 */   243,   68,   69,   70,   71,   72,   73,   74,   75,   76,
100873  /*   280 */    77,   78,   79,   80,  126,   82,   83,   84,   85,   86,
100874  /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
100875  /*   300 */    88,   23,  172,  173,  105,  106,  107,  150,   22,   26,
100876  /*   310 */    27,  181,   26,   27,   22,  116,   26,   27,   26,  230,
100877  /*   320 */   231,  197,  165,  230,  231,  113,   49,   50,  204,  117,
100878  /*   330 */    96,  174,  175,   99,  100,  101,   22,   26,   27,  136,
100879  /*   340 */    26,   27,  118,   16,  110,   68,   69,   70,   71,   72,
100880  /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,  118,   82,
100881  /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
100882  /*   370 */    19,  214,  215,  150,   23,   23,  155,   94,   95,   22,
100883  /*   380 */    94,   95,  116,  160,   94,   95,   94,   60,  165,   62,
100884  /*   390 */   112,   26,  114,  115,  128,   23,   36,  174,  175,   88,
100885  /*   400 */    49,   50,   57,  120,   22,   94,   95,   23,   94,   95,
100886  /*   410 */   120,   51,   25,  136,  169,  170,  171,  194,   58,   68,
100887  /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
100888  /*   430 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
100889  /*   440 */    89,   90,   91,   92,   19,  150,   12,   12,   23,  228,
100890  /*   450 */   105,  106,  107,   23,  233,   25,  165,   19,  150,   94,
100891  /*   460 */   165,  116,   28,   28,  112,  174,  114,  115,  108,  174,
100892  /*   470 */   175,   26,   27,  165,   49,   50,  231,   11,   44,   44,
100893  /*   480 */    46,   46,  174,  175,  112,  160,  114,  115,   50,   22,
100894  /*   490 */    23,   57,   25,   68,   69,   70,   71,   72,   73,   74,
100895  /*   500 */    75,   76,   77,   78,   79,   80,  119,   82,   83,   84,
100896  /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  194,
100897  /*   520 */   225,   23,   23,  215,   19,   95,  105,  106,  107,  150,
100898  /*   530 */    23,  150,   27,   23,   67,   25,  150,  206,  207,   94,
100899  /*   540 */    95,  166,  104,  218,  165,   22,  165,  109,   49,   50,
100900  /*   550 */   120,  165,   25,  174,  175,  174,  175,   23,   21,  234,
100901  /*   560 */   174,  175,   22,   23,  239,   25,   25,   68,   69,   70,
100902  /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
100903  /*   580 */   205,   82,   83,   84,   85,   86,   87,   88,   89,   90,
100904  /*   590 */    91,   92,   19,   22,   23,  216,   23,  222,  223,  224,
100905  /*   600 */    63,  220,   35,  150,  150,  163,  220,   67,  166,  167,
100906  /*   610 */   168,  150,  169,  170,  171,  161,  162,   25,  165,  165,
100907  /*   620 */   150,  113,   49,   50,   25,  117,  165,  174,  175,   35,
100908  /*   630 */     7,    8,    9,  160,  160,  165,  120,  100,   67,  247,
100909  /*   640 */   248,   68,   69,   70,   71,   72,   73,   74,   75,   76,
100910  /*   650 */    77,   78,   79,   80,  193,   82,   83,   84,   85,   86,
100911  /*   660 */    87,   88,   89,   90,   91,   92,   19,  194,  194,  150,
100912  /*   670 */   135,   24,  137,   35,  231,  138,  150,  129,  130,  206,
100913  /*   680 */   207,   30,   27,  213,  165,   34,  118,   95,    0,    1,
100914  /*   690 */     2,  165,  218,  174,  175,   50,   49,   50,   22,   48,
100915  /*   700 */   174,  175,   22,   23,   23,  244,  222,  223,  224,  166,
100916  /*   710 */   167,  168,  120,  239,   23,   68,   69,   70,   71,   72,
100917  /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
100918  /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
100919  /*   740 */    19,  150,  173,  165,  181,  182,   24,   67,   26,  104,
100920  /*   750 */   181,  188,  174,  175,  150,   39,  165,  150,   52,  150,
100921  /*   760 */   150,  150,  150,  144,  145,  174,  175,  249,  250,  165,
100922  /*   770 */    49,   50,  165,   52,  165,  165,  165,  165,  174,  175,
100923  /*   780 */    29,  174,  175,  174,  175,  174,  175,  160,   22,   68,
100924  /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
100925  /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
100926  /*   810 */    89,   90,   91,   92,   19,  150,   94,  165,  150,  150,
100927  /*   820 */   160,  194,  150,  213,  160,   52,  174,  175,   23,   23,
100928  /*   830 */   165,   25,   22,  165,  165,  150,  150,  165,   52,  174,
100929  /*   840 */   175,   22,  174,  175,   49,   50,  174,  175,  190,  191,
100930  /*   850 */   165,  165,  240,   23,  194,   25,  187,  109,  194,  174,
100931  /*   860 */   175,  190,  191,   68,   69,   70,   71,   72,   73,   74,
100932  /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
100933  /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
100934  /*   890 */    22,  165,  150,   23,  150,   25,  150,  166,   91,   92,
100935  /*   900 */   174,  175,   22,  217,  165,  150,  102,  165,  150,  165,
100936  /*   910 */   150,  165,  150,  174,  175,   19,  174,  175,   49,   50,
100937  /*   920 */   165,   86,   87,  165,   23,  165,   25,  165,   24,  174,
100938  /*   930 */   175,  187,  174,  175,  174,  175,  205,   68,   69,   70,
100939  /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
100940  /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
100941  /*   960 */    91,   92,   19,  150,  150,  165,  150,  150,  166,   23,
100942  /*   970 */   150,   25,  160,   20,  174,  175,    1,    2,  165,  165,
100943  /*   980 */   104,  165,  165,   43,  150,  165,  240,  150,   49,   50,
100944  /*   990 */   174,  175,   49,   50,   23,   23,   25,   25,   53,  165,
100945  /*  1000 */   187,  187,  165,   23,  187,   25,  194,  205,  174,  175,
100946  /*  1010 */    71,   72,   69,   70,   71,   72,   73,   74,   75,   76,
100947  /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
100948  /*  1030 */    87,   88,   89,   90,   91,   92,   19,   98,  150,  165,
100949  /*  1040 */   150,  160,  150,   59,   25,   53,  104,   22,  174,  175,
100950  /*  1050 */   213,  138,    5,  165,    1,  165,  150,  165,  150,  150,
100951  /*  1060 */   240,  150,  174,  175,  174,  175,   49,   50,  118,  150,
100952  /*  1070 */    35,  165,   27,  165,  165,  194,  165,  108,  127,   76,
100953  /*  1080 */   174,  175,  174,  175,  165,  174,  175,   70,   71,   72,
100954  /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  166,   82,
100955  /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
100956  /*  1110 */    19,   20,  193,   22,  150,  150,  150,   26,   27,   76,
100957  /*  1120 */   150,   22,    1,  150,  119,  121,  217,   20,   37,  165,
100958  /*  1130 */   165,  165,   16,   19,   20,  165,   22,  205,  165,  119,
100959  /*  1140 */    26,   27,  108,  128,  150,  150,  150,   56,  150,   22,
100960  /*  1150 */   150,   37,  150,  127,  160,   23,  150,   66,  193,  165,
100961  /*  1160 */   165,  165,   16,  165,   23,  165,  150,  165,  174,  175,
100962  /*  1170 */    56,  165,  150,   65,  174,  175,   15,   86,   87,   88,
100963  /*  1180 */    66,  165,  140,  150,   93,   94,   95,  165,  194,   98,
100964  /*  1190 */   174,  175,   22,    3,  164,  193,  174,  175,  165,  150,
100965  /*  1200 */    86,   87,    4,  180,  150,  248,  251,   93,   94,   95,
100966  /*  1210 */   216,  180,   98,  251,  165,  221,  150,  149,    6,  165,
100967  /*  1220 */   129,  130,  131,  132,  133,  134,  193,  150,  174,  175,
100968  /*  1230 */   116,  165,   19,   20,  150,   22,  149,  151,  150,   26,
100969  /*  1240 */    27,  149,  165,  129,  130,  131,  132,  133,  134,  165,
100970  /*  1250 */    37,  174,  175,  165,  149,   19,   20,   13,   22,  150,
100971  /*  1260 */   150,  150,   26,   27,  146,  147,  151,  150,   25,   56,
100972  /*  1270 */   152,  159,  154,   37,  165,  165,  165,  193,  160,   66,
100973  /*  1280 */   116,  193,  165,  174,  175,  174,  175,  194,  199,  150,
100974  /*  1290 */   200,  126,   56,  124,  123,  150,  201,  122,  150,   86,
100975  /*  1300 */    87,  150,   66,  193,  165,  202,   93,   94,   95,  150,
100976  /*  1310 */   165,   98,  194,  165,  125,   22,  165,  150,  150,   26,
100977  /*  1320 */    27,  135,   86,   87,  165,  174,  175,  203,  226,   93,
100978  /*  1330 */    94,   95,  165,  165,   98,  150,  218,  150,  193,  157,
100979  /*  1340 */   118,  157,  129,  130,  131,  132,  133,  134,    5,  104,
100980  /*  1350 */   165,  211,  165,   10,   11,   12,   13,   14,  150,   66,
100981  /*  1360 */    17,  174,  175,  210,  246,  129,  130,  131,  132,  133,
100982  /*  1370 */   134,  150,  210,  165,   31,  121,   33,  150,  150,   86,
100983  /*  1380 */    87,  176,  174,  175,  150,   42,  165,   94,  211,  210,
100984  /*  1390 */   150,   98,  165,  165,  211,  174,  175,  150,   55,  165,
100985  /*  1400 */    57,  150,  174,  175,   61,  165,  150,   64,  174,  175,
100986  /*  1410 */   150,  150,  165,  150,  174,  175,  165,  104,  150,  184,
100987  /*  1420 */   150,  165,  129,  130,  131,  165,  165,  150,  165,  150,
100988  /*  1430 */   150,  176,  150,  165,   47,  165,  150,  150,  176,  103,
100989  /*  1440 */   150,   22,  165,  178,  165,  165,  179,  165,  105,  106,
100990  /*  1450 */   107,  165,  165,  229,  111,  165,   92,  176,  229,  116,
100991  /*  1460 */   184,  176,  179,  156,  176,  176,   18,  157,  156,  237,
100992  /*  1470 */    45,  157,  156,  135,  157,  157,  238,  156,   68,  157,
100993  /*  1480 */   189,  189,  139,  219,   22,  157,   18,  192,  192,  192,
100994  /*  1490 */   192,  189,  219,  199,  157,  242,   40,  157,  199,  242,
100995  /*  1500 */   153,  157,   38,  245,  196,  166,  232,  198,  177,  177,
100996  /*  1510 */   232,  227,  209,  178,  166,  182,  166,  148,  177,  177,
100997  /*  1520 */   209,  196,  177,  199,  209,  199,  166,  208,   92,  195,
100998  /*  1530 */   174,  174,  183,  252,  183,  183,  252,  191,  252,  235,
100999  /*  1540 */   186,  241,  241,  252,  186,  252,  252,  252,  252,  252,
101000  /*  1550 */   252,  252,  252,  252,  252,  252,  236,
101001 };
101002 #define YY_SHIFT_USE_DFLT (-74)
101003 #define YY_SHIFT_COUNT (418)
101004 #define YY_SHIFT_MIN   (-73)
101005 #define YY_SHIFT_MAX   (1468)
101006 static const short yy_shift_ofst[] = {
101007  /*     0 */   975, 1114, 1343, 1114, 1213, 1213,   90,   90,    0,  -19,
101008  /*    10 */  1213, 1213, 1213, 1213, 1213,  345,  445,  721, 1091, 1213,
101009  /*    20 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
101010  /*    30 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
101011  /*    40 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
101012  /*    50 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
101013  /*    60 */  1213,  199,  445,  445,  835,  835,  365, 1164,   55,  647,
101014  /*    70 */   573,  499,  425,  351,  277,  203,  129,  795,  795,  795,
101015  /*    80 */   795,  795,  795,  795,  795,  795,  795,  795,  795,  795,
101016  /*    90 */   795,  795,  795,  795,  795,  869,  795,  943, 1017, 1017,
101017  /*   100 */   -69,  -45,  -45,  -45,  -45,  -45,   -1,   58,  138,  100,
101018  /*   110 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
101019  /*   120 */   445,  445,  445,  445,  445,  445,  537,  438,  445,  445,
101020  /*   130 */   445,  445,  445,  365,  807, 1436,  -74,  -74,  -74, 1293,
101021  /*   140 */    73,  434,  434,  311,  314,  290,  283,  286,  540,  467,
101022  /*   150 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
101023  /*   160 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
101024  /*   170 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
101025  /*   180 */   445,  445,   65,  722,  722,  722,  688,  266, 1164, 1164,
101026  /*   190 */  1164,  -74,  -74,  -74,  136,  168,  168,  234,  360,  360,
101027  /*   200 */   360,  430,  372,  435,  352,  278,  126,  -36,  -36,  -36,
101028  /*   210 */   -36,  421,  651,  -36,  -36,  592,  292,  212,  623,  158,
101029  /*   220 */   204,  204,  505,  158,  505,  144,  365,  154,  365,  154,
101030  /*   230 */   645,  154,  204,  154,  154,  535,  548,  548,  365,  387,
101031  /*   240 */   508,  233, 1464, 1222, 1222, 1456, 1456, 1222, 1462, 1410,
101032  /*   250 */  1165, 1468, 1468, 1468, 1468, 1222, 1165, 1462, 1410, 1410,
101033  /*   260 */  1222, 1448, 1338, 1425, 1222, 1222, 1448, 1222, 1448, 1222,
101034  /*   270 */  1448, 1419, 1313, 1313, 1313, 1387, 1364, 1364, 1419, 1313,
101035  /*   280 */  1336, 1313, 1387, 1313, 1313, 1254, 1245, 1254, 1245, 1254,
101036  /*   290 */  1245, 1222, 1222, 1186, 1189, 1175, 1169, 1171, 1165, 1164,
101037  /*   300 */  1243, 1244, 1244, 1212, 1212, 1212, 1212,  -74,  -74,  -74,
101038  /*   310 */   -74,  -74,  -74,  939,  104,  680,  571,  327,    1,  980,
101039  /*   320 */    26,  972,  971,  946,  901,  870,  830,  806,   54,   21,
101040  /*   330 */   -73,  510,  242, 1198, 1190, 1170, 1042, 1161, 1108, 1146,
101041  /*   340 */  1141, 1132, 1015, 1127, 1026, 1034, 1020, 1107, 1004, 1116,
101042  /*   350 */  1121, 1005, 1099,  951, 1043, 1003,  969, 1045, 1035,  950,
101043  /*   360 */  1053, 1047, 1025,  942,  913,  992, 1019,  945,  984,  940,
101044  /*   370 */   876,  904,  953,  896,  748,  804,  880,  786,  868,  819,
101045  /*   380 */   805,  810,  773,  751,  766,  706,  716,  691,  681,  568,
101046  /*   390 */   655,  638,  676,  516,  541,  594,  599,  567,  541,  534,
101047  /*   400 */   507,  527,  498,  523,  466,  382,  409,  384,  357,    6,
101048  /*   410 */   240,  224,  143,   62,   18,   71,   39,    9,    5,
101049 };
101050 #define YY_REDUCE_USE_DFLT (-142)
101051 #define YY_REDUCE_COUNT (312)
101052 #define YY_REDUCE_MIN   (-141)
101053 #define YY_REDUCE_MAX   (1369)
101054 static const short yy_reduce_ofst[] = {
101055  /*     0 */  -141,  994, 1118,  223,  157,  -53,   93,   89,   83,  375,
101056  /*    10 */   386,  381,  379,  308,  295,  325,  -47,   27, 1240, 1234,
101057  /*    20 */  1228, 1221, 1208, 1187, 1151, 1111, 1109, 1077, 1054, 1022,
101058  /*    30 */  1016, 1000,  911,  908,  906,  890,  888,  874,  834,  816,
101059  /*    40 */   800,  760,  758,  755,  742,  739,  726,  685,  672,  668,
101060  /*    50 */   665,  652,  611,  609,  607,  604,  591,  578,  526,  519,
101061  /*    60 */   453,  474,  454,  461,  443,  245,  442,  473,  484,  484,
101062  /*    70 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
101063  /*    80 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
101064  /*    90 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
101065  /*   100 */   484,  484,  484,  484,  484,  484,  484,  130,  484,  484,
101066  /*   110 */  1145,  909, 1110, 1088, 1084, 1033, 1002,  965,  820,  837,
101067  /*   120 */   746,  686,  612,  817,  610,  919,  221,  563,  814,  813,
101068  /*   130 */   744,  669,  470,  543,  484,  484,  484,  484,  484,  291,
101069  /*   140 */   569,  671,  658,  970, 1290, 1287, 1286, 1282,  518,  518,
101070  /*   150 */  1280, 1279, 1277, 1270, 1268, 1263, 1261, 1260, 1256, 1251,
101071  /*   160 */  1247, 1227, 1185, 1168, 1167, 1159, 1148, 1139, 1117, 1066,
101072  /*   170 */  1049, 1006,  998,  996,  995,  973,  970,  966,  964,  892,
101073  /*   180 */   762,  -52,  881,  932,  802,  731,  619,  812,  664,  660,
101074  /*   190 */   627,  392,  331,  124, 1358, 1357, 1356, 1354, 1352, 1351,
101075  /*   200 */  1349, 1319, 1334, 1346, 1334, 1334, 1334, 1334, 1334, 1334,
101076  /*   210 */  1334, 1320, 1304, 1334, 1334, 1319, 1360, 1325, 1369, 1326,
101077  /*   220 */  1315, 1311, 1301, 1324, 1300, 1335, 1350, 1345, 1348, 1342,
101078  /*   230 */  1333, 1341, 1303, 1332, 1331, 1284, 1278, 1274, 1339, 1309,
101079  /*   240 */  1308, 1347, 1258, 1344, 1340, 1257, 1253, 1337, 1273, 1302,
101080  /*   250 */  1299, 1298, 1297, 1296, 1295, 1328, 1294, 1264, 1292, 1291,
101081  /*   260 */  1322, 1321, 1238, 1232, 1318, 1317, 1316, 1314, 1312, 1310,
101082  /*   270 */  1307, 1283, 1289, 1288, 1285, 1276, 1229, 1224, 1267, 1281,
101083  /*   280 */  1265, 1262, 1235, 1255, 1205, 1183, 1179, 1177, 1162, 1140,
101084  /*   290 */  1153, 1184, 1182, 1102, 1124, 1103, 1095, 1090, 1089, 1093,
101085  /*   300 */  1112, 1115, 1086, 1105, 1092, 1087, 1068,  962,  955,  957,
101086  /*   310 */  1031, 1023, 1030,
101087 };
101088 static const YYACTIONTYPE yy_default[] = {
101089  /*     0 */   635,  870,  959,  959,  959,  870,  899,  899,  959,  759,
101090  /*    10 */   959,  959,  959,  959,  868,  959,  959,  933,  959,  959,
101091  /*    20 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
101092  /*    30 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
101093  /*    40 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
101094  /*    50 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
101095  /*    60 */   959,  959,  959,  959,  899,  899,  674,  763,  794,  959,
101096  /*    70 */   959,  959,  959,  959,  959,  959,  959,  932,  934,  809,
101097  /*    80 */   808,  802,  801,  912,  774,  799,  792,  785,  796,  871,
101098  /*    90 */   864,  865,  863,  867,  872,  959,  795,  831,  848,  830,
101099  /*   100 */   842,  847,  854,  846,  843,  833,  832,  666,  834,  835,
101100  /*   110 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
101101  /*   120 */   959,  959,  959,  959,  959,  959,  661,  728,  959,  959,
101102  /*   130 */   959,  959,  959,  959,  836,  837,  851,  850,  849,  959,
101103  /*   140 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
101104  /*   150 */   959,  939,  937,  959,  883,  959,  959,  959,  959,  959,
101105  /*   160 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
101106  /*   170 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
101107  /*   180 */   959,  641,  959,  759,  759,  759,  635,  959,  959,  959,
101108  /*   190 */   959,  951,  763,  753,  719,  959,  959,  959,  959,  959,
101109  /*   200 */   959,  959,  959,  959,  959,  959,  959,  804,  742,  922,
101110  /*   210 */   924,  959,  905,  740,  663,  761,  676,  751,  643,  798,
101111  /*   220 */   776,  776,  917,  798,  917,  700,  959,  788,  959,  788,
101112  /*   230 */   697,  788,  776,  788,  788,  866,  959,  959,  959,  760,
101113  /*   240 */   751,  959,  944,  767,  767,  936,  936,  767,  810,  732,
101114  /*   250 */   798,  739,  739,  739,  739,  767,  798,  810,  732,  732,
101115  /*   260 */   767,  658,  911,  909,  767,  767,  658,  767,  658,  767,
101116  /*   270 */   658,  876,  730,  730,  730,  715,  880,  880,  876,  730,
101117  /*   280 */   700,  730,  715,  730,  730,  780,  775,  780,  775,  780,
101118  /*   290 */   775,  767,  767,  959,  793,  781,  791,  789,  798,  959,
101119  /*   300 */   718,  651,  651,  640,  640,  640,  640,  956,  956,  951,
101120  /*   310 */   702,  702,  684,  959,  959,  959,  959,  959,  959,  959,
101121  /*   320 */   885,  959,  959,  959,  959,  959,  959,  959,  959,  959,
101122  /*   330 */   959,  959,  959,  959,  636,  946,  959,  959,  943,  959,
101123  /*   340 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
101124  /*   350 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  915,
101125  /*   360 */   959,  959,  959,  959,  959,  959,  908,  907,  959,  959,
101126  /*   370 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
101127  /*   380 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
101128  /*   390 */   959,  959,  959,  959,  790,  959,  782,  959,  869,  959,
101129  /*   400 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  745,
101130  /*   410 */   819,  959,  818,  822,  817,  668,  959,  649,  959,  632,
101131  /*   420 */   637,  955,  958,  957,  954,  953,  952,  947,  945,  942,
101132  /*   430 */   941,  940,  938,  935,  931,  889,  887,  894,  893,  892,
101133  /*   440 */   891,  890,  888,  886,  884,  805,  803,  800,  797,  930,
101134  /*   450 */   882,  741,  738,  737,  657,  948,  914,  923,  921,  811,
101135  /*   460 */   920,  919,  918,  916,  913,  900,  807,  806,  733,  874,
101136  /*   470 */   873,  660,  904,  903,  902,  906,  910,  901,  769,  659,
101137  /*   480 */   656,  665,  722,  721,  729,  727,  726,  725,  724,  723,
101138  /*   490 */   720,  667,  675,  686,  714,  699,  698,  879,  881,  878,
101139  /*   500 */   877,  707,  706,  712,  711,  710,  709,  708,  705,  704,
101140  /*   510 */   703,  696,  695,  701,  694,  717,  716,  713,  693,  736,
101141  /*   520 */   735,  734,  731,  692,  691,  690,  822,  689,  688,  828,
101142  /*   530 */   827,  815,  858,  756,  755,  754,  766,  765,  778,  777,
101143  /*   540 */   813,  812,  779,  764,  758,  757,  773,  772,  771,  770,
101144  /*   550 */   762,  752,  784,  787,  786,  783,  860,  768,  857,  929,
101145  /*   560 */   928,  927,  926,  925,  862,  861,  829,  826,  679,  680,
101146  /*   570 */   898,  896,  897,  895,  682,  681,  678,  677,  859,  747,
101147  /*   580 */   746,  855,  852,  844,  840,  856,  853,  845,  841,  839,
101148  /*   590 */   838,  824,  823,  821,  820,  816,  825,  670,  748,  744,
101149  /*   600 */   743,  814,  750,  749,  687,  685,  683,  664,  662,  655,
101150  /*   610 */   653,  652,  654,  650,  648,  647,  646,  645,  644,  673,
101151  /*   620 */   672,  671,  669,  668,  642,  639,  638,  634,  633,  631,
101152 };
101153
101154 /* The next table maps tokens into fallback tokens.  If a construct
101155 ** like the following:
101156 ** 
101157 **      %fallback ID X Y Z.
101158 **
101159 ** appears in the grammar, then ID becomes a fallback token for X, Y,
101160 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
101161 ** but it does not parse, the type of the token is changed to ID and
101162 ** the parse is retried before an error is thrown.
101163 */
101164 #ifdef YYFALLBACK
101165 static const YYCODETYPE yyFallback[] = {
101166     0,  /*          $ => nothing */
101167     0,  /*       SEMI => nothing */
101168    26,  /*    EXPLAIN => ID */
101169    26,  /*      QUERY => ID */
101170    26,  /*       PLAN => ID */
101171    26,  /*      BEGIN => ID */
101172     0,  /* TRANSACTION => nothing */
101173    26,  /*   DEFERRED => ID */
101174    26,  /*  IMMEDIATE => ID */
101175    26,  /*  EXCLUSIVE => ID */
101176     0,  /*     COMMIT => nothing */
101177    26,  /*        END => ID */
101178    26,  /*   ROLLBACK => ID */
101179    26,  /*  SAVEPOINT => ID */
101180    26,  /*    RELEASE => ID */
101181     0,  /*         TO => nothing */
101182     0,  /*      TABLE => nothing */
101183     0,  /*     CREATE => nothing */
101184    26,  /*         IF => ID */
101185     0,  /*        NOT => nothing */
101186     0,  /*     EXISTS => nothing */
101187    26,  /*       TEMP => ID */
101188     0,  /*         LP => nothing */
101189     0,  /*         RP => nothing */
101190     0,  /*         AS => nothing */
101191     0,  /*      COMMA => nothing */
101192     0,  /*         ID => nothing */
101193     0,  /*    INDEXED => nothing */
101194    26,  /*      ABORT => ID */
101195    26,  /*     ACTION => ID */
101196    26,  /*      AFTER => ID */
101197    26,  /*    ANALYZE => ID */
101198    26,  /*        ASC => ID */
101199    26,  /*     ATTACH => ID */
101200    26,  /*     BEFORE => ID */
101201    26,  /*         BY => ID */
101202    26,  /*    CASCADE => ID */
101203    26,  /*       CAST => ID */
101204    26,  /*   COLUMNKW => ID */
101205    26,  /*   CONFLICT => ID */
101206    26,  /*   DATABASE => ID */
101207    26,  /*       DESC => ID */
101208    26,  /*     DETACH => ID */
101209    26,  /*       EACH => ID */
101210    26,  /*       FAIL => ID */
101211    26,  /*        FOR => ID */
101212    26,  /*     IGNORE => ID */
101213    26,  /*  INITIALLY => ID */
101214    26,  /*    INSTEAD => ID */
101215    26,  /*    LIKE_KW => ID */
101216    26,  /*      MATCH => ID */
101217    26,  /*         NO => ID */
101218    26,  /*        KEY => ID */
101219    26,  /*         OF => ID */
101220    26,  /*     OFFSET => ID */
101221    26,  /*     PRAGMA => ID */
101222    26,  /*      RAISE => ID */
101223    26,  /*    REPLACE => ID */
101224    26,  /*   RESTRICT => ID */
101225    26,  /*        ROW => ID */
101226    26,  /*    TRIGGER => ID */
101227    26,  /*     VACUUM => ID */
101228    26,  /*       VIEW => ID */
101229    26,  /*    VIRTUAL => ID */
101230    26,  /*    REINDEX => ID */
101231    26,  /*     RENAME => ID */
101232    26,  /*   CTIME_KW => ID */
101233 };
101234 #endif /* YYFALLBACK */
101235
101236 /* The following structure represents a single element of the
101237 ** parser's stack.  Information stored includes:
101238 **
101239 **   +  The state number for the parser at this level of the stack.
101240 **
101241 **   +  The value of the token stored at this level of the stack.
101242 **      (In other words, the "major" token.)
101243 **
101244 **   +  The semantic value stored at this level of the stack.  This is
101245 **      the information used by the action routines in the grammar.
101246 **      It is sometimes called the "minor" token.
101247 */
101248 struct yyStackEntry {
101249   YYACTIONTYPE stateno;  /* The state-number */
101250   YYCODETYPE major;      /* The major token value.  This is the code
101251                          ** number for the token at this stack level */
101252   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
101253                          ** is the value of the token  */
101254 };
101255 typedef struct yyStackEntry yyStackEntry;
101256
101257 /* The state of the parser is completely contained in an instance of
101258 ** the following structure */
101259 struct yyParser {
101260   int yyidx;                    /* Index of top element in stack */
101261 #ifdef YYTRACKMAXSTACKDEPTH
101262   int yyidxMax;                 /* Maximum value of yyidx */
101263 #endif
101264   int yyerrcnt;                 /* Shifts left before out of the error */
101265   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
101266 #if YYSTACKDEPTH<=0
101267   int yystksz;                  /* Current side of the stack */
101268   yyStackEntry *yystack;        /* The parser's stack */
101269 #else
101270   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
101271 #endif
101272 };
101273 typedef struct yyParser yyParser;
101274
101275 #ifndef NDEBUG
101276 static FILE *yyTraceFILE = 0;
101277 static char *yyTracePrompt = 0;
101278 #endif /* NDEBUG */
101279
101280 #ifndef NDEBUG
101281 /* 
101282 ** Turn parser tracing on by giving a stream to which to write the trace
101283 ** and a prompt to preface each trace message.  Tracing is turned off
101284 ** by making either argument NULL 
101285 **
101286 ** Inputs:
101287 ** <ul>
101288 ** <li> A FILE* to which trace output should be written.
101289 **      If NULL, then tracing is turned off.
101290 ** <li> A prefix string written at the beginning of every
101291 **      line of trace output.  If NULL, then tracing is
101292 **      turned off.
101293 ** </ul>
101294 **
101295 ** Outputs:
101296 ** None.
101297 */
101298 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
101299   yyTraceFILE = TraceFILE;
101300   yyTracePrompt = zTracePrompt;
101301   if( yyTraceFILE==0 ) yyTracePrompt = 0;
101302   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
101303 }
101304 #endif /* NDEBUG */
101305
101306 #ifndef NDEBUG
101307 /* For tracing shifts, the names of all terminals and nonterminals
101308 ** are required.  The following table supplies these names */
101309 static const char *const yyTokenName[] = { 
101310   "$",             "SEMI",          "EXPLAIN",       "QUERY",       
101311   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
101312   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
101313   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",          
101314   "TABLE",         "CREATE",        "IF",            "NOT",         
101315   "EXISTS",        "TEMP",          "LP",            "RP",          
101316   "AS",            "COMMA",         "ID",            "INDEXED",     
101317   "ABORT",         "ACTION",        "AFTER",         "ANALYZE",     
101318   "ASC",           "ATTACH",        "BEFORE",        "BY",          
101319   "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",    
101320   "DATABASE",      "DESC",          "DETACH",        "EACH",        
101321   "FAIL",          "FOR",           "IGNORE",        "INITIALLY",   
101322   "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",          
101323   "KEY",           "OF",            "OFFSET",        "PRAGMA",      
101324   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",         
101325   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",     
101326   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",         
101327   "OR",            "AND",           "IS",            "BETWEEN",     
101328   "IN",            "ISNULL",        "NOTNULL",       "NE",          
101329   "EQ",            "GT",            "LE",            "LT",          
101330   "GE",            "ESCAPE",        "BITAND",        "BITOR",       
101331   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",       
101332   "STAR",          "SLASH",         "REM",           "CONCAT",      
101333   "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",     
101334   "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",     
101335   "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",    
101336   "ON",            "INSERT",        "DELETE",        "UPDATE",      
101337   "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",        
101338   "UNION",         "ALL",           "EXCEPT",        "INTERSECT",   
101339   "SELECT",        "DISTINCT",      "DOT",           "FROM",        
101340   "JOIN",          "USING",         "ORDER",         "GROUP",       
101341   "HAVING",        "LIMIT",         "WHERE",         "INTO",        
101342   "VALUES",        "INTEGER",       "FLOAT",         "BLOB",        
101343   "REGISTER",      "VARIABLE",      "CASE",          "WHEN",        
101344   "THEN",          "ELSE",          "INDEX",         "ALTER",       
101345   "ADD",           "error",         "input",         "cmdlist",     
101346   "ecmd",          "explain",       "cmdx",          "cmd",         
101347   "transtype",     "trans_opt",     "nm",            "savepoint_opt",
101348   "create_table",  "create_table_args",  "createkw",      "temp",        
101349   "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
101350   "select",        "column",        "columnid",      "type",        
101351   "carglist",      "id",            "ids",           "typetoken",   
101352   "typename",      "signed",        "plus_num",      "minus_num",   
101353   "carg",          "ccons",         "term",          "expr",        
101354   "onconf",        "sortorder",     "autoinc",       "idxlist_opt", 
101355   "refargs",       "defer_subclause",  "refarg",        "refact",      
101356   "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",     
101357   "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",   
101358   "ifexists",      "fullname",      "oneselect",     "multiselect_op",
101359   "distinct",      "selcollist",    "from",          "where_opt",   
101360   "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",   
101361   "sclp",          "as",            "seltablist",    "stl_prefix",  
101362   "joinop",        "indexed_opt",   "on_opt",        "using_opt",   
101363   "joinop2",       "inscollist",    "sortlist",      "sortitem",    
101364   "nexprlist",     "setlist",       "insert_cmd",    "inscollist_opt",
101365   "itemlist",      "exprlist",      "likeop",        "between_op",  
101366   "in_op",         "case_operand",  "case_exprlist",  "case_else",   
101367   "uniqueflag",    "collate",       "nmnum",         "plus_opt",    
101368   "number",        "trigger_decl",  "trigger_cmd_list",  "trigger_time",
101369   "trigger_event",  "foreach_clause",  "when_clause",   "trigger_cmd", 
101370   "trnm",          "tridxby",       "database_kw_opt",  "key_opt",     
101371   "add_column_fullname",  "kwcolumn_opt",  "create_vtab",   "vtabarglist", 
101372   "vtabarg",       "vtabargtoken",  "lp",            "anylist",     
101373 };
101374 #endif /* NDEBUG */
101375
101376 #ifndef NDEBUG
101377 /* For tracing reduce actions, the names of all rules are required.
101378 */
101379 static const char *const yyRuleName[] = {
101380  /*   0 */ "input ::= cmdlist",
101381  /*   1 */ "cmdlist ::= cmdlist ecmd",
101382  /*   2 */ "cmdlist ::= ecmd",
101383  /*   3 */ "ecmd ::= SEMI",
101384  /*   4 */ "ecmd ::= explain cmdx SEMI",
101385  /*   5 */ "explain ::=",
101386  /*   6 */ "explain ::= EXPLAIN",
101387  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
101388  /*   8 */ "cmdx ::= cmd",
101389  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
101390  /*  10 */ "trans_opt ::=",
101391  /*  11 */ "trans_opt ::= TRANSACTION",
101392  /*  12 */ "trans_opt ::= TRANSACTION nm",
101393  /*  13 */ "transtype ::=",
101394  /*  14 */ "transtype ::= DEFERRED",
101395  /*  15 */ "transtype ::= IMMEDIATE",
101396  /*  16 */ "transtype ::= EXCLUSIVE",
101397  /*  17 */ "cmd ::= COMMIT trans_opt",
101398  /*  18 */ "cmd ::= END trans_opt",
101399  /*  19 */ "cmd ::= ROLLBACK trans_opt",
101400  /*  20 */ "savepoint_opt ::= SAVEPOINT",
101401  /*  21 */ "savepoint_opt ::=",
101402  /*  22 */ "cmd ::= SAVEPOINT nm",
101403  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
101404  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
101405  /*  25 */ "cmd ::= create_table create_table_args",
101406  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
101407  /*  27 */ "createkw ::= CREATE",
101408  /*  28 */ "ifnotexists ::=",
101409  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
101410  /*  30 */ "temp ::= TEMP",
101411  /*  31 */ "temp ::=",
101412  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
101413  /*  33 */ "create_table_args ::= AS select",
101414  /*  34 */ "columnlist ::= columnlist COMMA column",
101415  /*  35 */ "columnlist ::= column",
101416  /*  36 */ "column ::= columnid type carglist",
101417  /*  37 */ "columnid ::= nm",
101418  /*  38 */ "id ::= ID",
101419  /*  39 */ "id ::= INDEXED",
101420  /*  40 */ "ids ::= ID|STRING",
101421  /*  41 */ "nm ::= id",
101422  /*  42 */ "nm ::= STRING",
101423  /*  43 */ "nm ::= JOIN_KW",
101424  /*  44 */ "type ::=",
101425  /*  45 */ "type ::= typetoken",
101426  /*  46 */ "typetoken ::= typename",
101427  /*  47 */ "typetoken ::= typename LP signed RP",
101428  /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
101429  /*  49 */ "typename ::= ids",
101430  /*  50 */ "typename ::= typename ids",
101431  /*  51 */ "signed ::= plus_num",
101432  /*  52 */ "signed ::= minus_num",
101433  /*  53 */ "carglist ::= carglist carg",
101434  /*  54 */ "carglist ::=",
101435  /*  55 */ "carg ::= CONSTRAINT nm ccons",
101436  /*  56 */ "carg ::= ccons",
101437  /*  57 */ "ccons ::= DEFAULT term",
101438  /*  58 */ "ccons ::= DEFAULT LP expr RP",
101439  /*  59 */ "ccons ::= DEFAULT PLUS term",
101440  /*  60 */ "ccons ::= DEFAULT MINUS term",
101441  /*  61 */ "ccons ::= DEFAULT id",
101442  /*  62 */ "ccons ::= NULL onconf",
101443  /*  63 */ "ccons ::= NOT NULL onconf",
101444  /*  64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
101445  /*  65 */ "ccons ::= UNIQUE onconf",
101446  /*  66 */ "ccons ::= CHECK LP expr RP",
101447  /*  67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
101448  /*  68 */ "ccons ::= defer_subclause",
101449  /*  69 */ "ccons ::= COLLATE ids",
101450  /*  70 */ "autoinc ::=",
101451  /*  71 */ "autoinc ::= AUTOINCR",
101452  /*  72 */ "refargs ::=",
101453  /*  73 */ "refargs ::= refargs refarg",
101454  /*  74 */ "refarg ::= MATCH nm",
101455  /*  75 */ "refarg ::= ON INSERT refact",
101456  /*  76 */ "refarg ::= ON DELETE refact",
101457  /*  77 */ "refarg ::= ON UPDATE refact",
101458  /*  78 */ "refact ::= SET NULL",
101459  /*  79 */ "refact ::= SET DEFAULT",
101460  /*  80 */ "refact ::= CASCADE",
101461  /*  81 */ "refact ::= RESTRICT",
101462  /*  82 */ "refact ::= NO ACTION",
101463  /*  83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
101464  /*  84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
101465  /*  85 */ "init_deferred_pred_opt ::=",
101466  /*  86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
101467  /*  87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
101468  /*  88 */ "conslist_opt ::=",
101469  /*  89 */ "conslist_opt ::= COMMA conslist",
101470  /*  90 */ "conslist ::= conslist COMMA tcons",
101471  /*  91 */ "conslist ::= conslist tcons",
101472  /*  92 */ "conslist ::= tcons",
101473  /*  93 */ "tcons ::= CONSTRAINT nm",
101474  /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
101475  /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
101476  /*  96 */ "tcons ::= CHECK LP expr RP onconf",
101477  /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
101478  /*  98 */ "defer_subclause_opt ::=",
101479  /*  99 */ "defer_subclause_opt ::= defer_subclause",
101480  /* 100 */ "onconf ::=",
101481  /* 101 */ "onconf ::= ON CONFLICT resolvetype",
101482  /* 102 */ "orconf ::=",
101483  /* 103 */ "orconf ::= OR resolvetype",
101484  /* 104 */ "resolvetype ::= raisetype",
101485  /* 105 */ "resolvetype ::= IGNORE",
101486  /* 106 */ "resolvetype ::= REPLACE",
101487  /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
101488  /* 108 */ "ifexists ::= IF EXISTS",
101489  /* 109 */ "ifexists ::=",
101490  /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
101491  /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
101492  /* 112 */ "cmd ::= select",
101493  /* 113 */ "select ::= oneselect",
101494  /* 114 */ "select ::= select multiselect_op oneselect",
101495  /* 115 */ "multiselect_op ::= UNION",
101496  /* 116 */ "multiselect_op ::= UNION ALL",
101497  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
101498  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
101499  /* 119 */ "distinct ::= DISTINCT",
101500  /* 120 */ "distinct ::= ALL",
101501  /* 121 */ "distinct ::=",
101502  /* 122 */ "sclp ::= selcollist COMMA",
101503  /* 123 */ "sclp ::=",
101504  /* 124 */ "selcollist ::= sclp expr as",
101505  /* 125 */ "selcollist ::= sclp STAR",
101506  /* 126 */ "selcollist ::= sclp nm DOT STAR",
101507  /* 127 */ "as ::= AS nm",
101508  /* 128 */ "as ::= ids",
101509  /* 129 */ "as ::=",
101510  /* 130 */ "from ::=",
101511  /* 131 */ "from ::= FROM seltablist",
101512  /* 132 */ "stl_prefix ::= seltablist joinop",
101513  /* 133 */ "stl_prefix ::=",
101514  /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
101515  /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
101516  /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
101517  /* 137 */ "dbnm ::=",
101518  /* 138 */ "dbnm ::= DOT nm",
101519  /* 139 */ "fullname ::= nm dbnm",
101520  /* 140 */ "joinop ::= COMMA|JOIN",
101521  /* 141 */ "joinop ::= JOIN_KW JOIN",
101522  /* 142 */ "joinop ::= JOIN_KW nm JOIN",
101523  /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
101524  /* 144 */ "on_opt ::= ON expr",
101525  /* 145 */ "on_opt ::=",
101526  /* 146 */ "indexed_opt ::=",
101527  /* 147 */ "indexed_opt ::= INDEXED BY nm",
101528  /* 148 */ "indexed_opt ::= NOT INDEXED",
101529  /* 149 */ "using_opt ::= USING LP inscollist RP",
101530  /* 150 */ "using_opt ::=",
101531  /* 151 */ "orderby_opt ::=",
101532  /* 152 */ "orderby_opt ::= ORDER BY sortlist",
101533  /* 153 */ "sortlist ::= sortlist COMMA sortitem sortorder",
101534  /* 154 */ "sortlist ::= sortitem sortorder",
101535  /* 155 */ "sortitem ::= expr",
101536  /* 156 */ "sortorder ::= ASC",
101537  /* 157 */ "sortorder ::= DESC",
101538  /* 158 */ "sortorder ::=",
101539  /* 159 */ "groupby_opt ::=",
101540  /* 160 */ "groupby_opt ::= GROUP BY nexprlist",
101541  /* 161 */ "having_opt ::=",
101542  /* 162 */ "having_opt ::= HAVING expr",
101543  /* 163 */ "limit_opt ::=",
101544  /* 164 */ "limit_opt ::= LIMIT expr",
101545  /* 165 */ "limit_opt ::= LIMIT expr OFFSET expr",
101546  /* 166 */ "limit_opt ::= LIMIT expr COMMA expr",
101547  /* 167 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
101548  /* 168 */ "where_opt ::=",
101549  /* 169 */ "where_opt ::= WHERE expr",
101550  /* 170 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
101551  /* 171 */ "setlist ::= setlist COMMA nm EQ expr",
101552  /* 172 */ "setlist ::= nm EQ expr",
101553  /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
101554  /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
101555  /* 175 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
101556  /* 176 */ "insert_cmd ::= INSERT orconf",
101557  /* 177 */ "insert_cmd ::= REPLACE",
101558  /* 178 */ "itemlist ::= itemlist COMMA expr",
101559  /* 179 */ "itemlist ::= expr",
101560  /* 180 */ "inscollist_opt ::=",
101561  /* 181 */ "inscollist_opt ::= LP inscollist RP",
101562  /* 182 */ "inscollist ::= inscollist COMMA nm",
101563  /* 183 */ "inscollist ::= nm",
101564  /* 184 */ "expr ::= term",
101565  /* 185 */ "expr ::= LP expr RP",
101566  /* 186 */ "term ::= NULL",
101567  /* 187 */ "expr ::= id",
101568  /* 188 */ "expr ::= JOIN_KW",
101569  /* 189 */ "expr ::= nm DOT nm",
101570  /* 190 */ "expr ::= nm DOT nm DOT nm",
101571  /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
101572  /* 192 */ "term ::= STRING",
101573  /* 193 */ "expr ::= REGISTER",
101574  /* 194 */ "expr ::= VARIABLE",
101575  /* 195 */ "expr ::= expr COLLATE ids",
101576  /* 196 */ "expr ::= CAST LP expr AS typetoken RP",
101577  /* 197 */ "expr ::= ID LP distinct exprlist RP",
101578  /* 198 */ "expr ::= ID LP STAR RP",
101579  /* 199 */ "term ::= CTIME_KW",
101580  /* 200 */ "expr ::= expr AND expr",
101581  /* 201 */ "expr ::= expr OR expr",
101582  /* 202 */ "expr ::= expr LT|GT|GE|LE expr",
101583  /* 203 */ "expr ::= expr EQ|NE expr",
101584  /* 204 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
101585  /* 205 */ "expr ::= expr PLUS|MINUS expr",
101586  /* 206 */ "expr ::= expr STAR|SLASH|REM expr",
101587  /* 207 */ "expr ::= expr CONCAT expr",
101588  /* 208 */ "likeop ::= LIKE_KW",
101589  /* 209 */ "likeop ::= NOT LIKE_KW",
101590  /* 210 */ "likeop ::= MATCH",
101591  /* 211 */ "likeop ::= NOT MATCH",
101592  /* 212 */ "expr ::= expr likeop expr",
101593  /* 213 */ "expr ::= expr likeop expr ESCAPE expr",
101594  /* 214 */ "expr ::= expr ISNULL|NOTNULL",
101595  /* 215 */ "expr ::= expr NOT NULL",
101596  /* 216 */ "expr ::= expr IS expr",
101597  /* 217 */ "expr ::= expr IS NOT expr",
101598  /* 218 */ "expr ::= NOT expr",
101599  /* 219 */ "expr ::= BITNOT expr",
101600  /* 220 */ "expr ::= MINUS expr",
101601  /* 221 */ "expr ::= PLUS expr",
101602  /* 222 */ "between_op ::= BETWEEN",
101603  /* 223 */ "between_op ::= NOT BETWEEN",
101604  /* 224 */ "expr ::= expr between_op expr AND expr",
101605  /* 225 */ "in_op ::= IN",
101606  /* 226 */ "in_op ::= NOT IN",
101607  /* 227 */ "expr ::= expr in_op LP exprlist RP",
101608  /* 228 */ "expr ::= LP select RP",
101609  /* 229 */ "expr ::= expr in_op LP select RP",
101610  /* 230 */ "expr ::= expr in_op nm dbnm",
101611  /* 231 */ "expr ::= EXISTS LP select RP",
101612  /* 232 */ "expr ::= CASE case_operand case_exprlist case_else END",
101613  /* 233 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
101614  /* 234 */ "case_exprlist ::= WHEN expr THEN expr",
101615  /* 235 */ "case_else ::= ELSE expr",
101616  /* 236 */ "case_else ::=",
101617  /* 237 */ "case_operand ::= expr",
101618  /* 238 */ "case_operand ::=",
101619  /* 239 */ "exprlist ::= nexprlist",
101620  /* 240 */ "exprlist ::=",
101621  /* 241 */ "nexprlist ::= nexprlist COMMA expr",
101622  /* 242 */ "nexprlist ::= expr",
101623  /* 243 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
101624  /* 244 */ "uniqueflag ::= UNIQUE",
101625  /* 245 */ "uniqueflag ::=",
101626  /* 246 */ "idxlist_opt ::=",
101627  /* 247 */ "idxlist_opt ::= LP idxlist RP",
101628  /* 248 */ "idxlist ::= idxlist COMMA nm collate sortorder",
101629  /* 249 */ "idxlist ::= nm collate sortorder",
101630  /* 250 */ "collate ::=",
101631  /* 251 */ "collate ::= COLLATE ids",
101632  /* 252 */ "cmd ::= DROP INDEX ifexists fullname",
101633  /* 253 */ "cmd ::= VACUUM",
101634  /* 254 */ "cmd ::= VACUUM nm",
101635  /* 255 */ "cmd ::= PRAGMA nm dbnm",
101636  /* 256 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
101637  /* 257 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
101638  /* 258 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
101639  /* 259 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
101640  /* 260 */ "nmnum ::= plus_num",
101641  /* 261 */ "nmnum ::= nm",
101642  /* 262 */ "nmnum ::= ON",
101643  /* 263 */ "nmnum ::= DELETE",
101644  /* 264 */ "nmnum ::= DEFAULT",
101645  /* 265 */ "plus_num ::= plus_opt number",
101646  /* 266 */ "minus_num ::= MINUS number",
101647  /* 267 */ "number ::= INTEGER|FLOAT",
101648  /* 268 */ "plus_opt ::= PLUS",
101649  /* 269 */ "plus_opt ::=",
101650  /* 270 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
101651  /* 271 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
101652  /* 272 */ "trigger_time ::= BEFORE",
101653  /* 273 */ "trigger_time ::= AFTER",
101654  /* 274 */ "trigger_time ::= INSTEAD OF",
101655  /* 275 */ "trigger_time ::=",
101656  /* 276 */ "trigger_event ::= DELETE|INSERT",
101657  /* 277 */ "trigger_event ::= UPDATE",
101658  /* 278 */ "trigger_event ::= UPDATE OF inscollist",
101659  /* 279 */ "foreach_clause ::=",
101660  /* 280 */ "foreach_clause ::= FOR EACH ROW",
101661  /* 281 */ "when_clause ::=",
101662  /* 282 */ "when_clause ::= WHEN expr",
101663  /* 283 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
101664  /* 284 */ "trigger_cmd_list ::= trigger_cmd SEMI",
101665  /* 285 */ "trnm ::= nm",
101666  /* 286 */ "trnm ::= nm DOT nm",
101667  /* 287 */ "tridxby ::=",
101668  /* 288 */ "tridxby ::= INDEXED BY nm",
101669  /* 289 */ "tridxby ::= NOT INDEXED",
101670  /* 290 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
101671  /* 291 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
101672  /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
101673  /* 293 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
101674  /* 294 */ "trigger_cmd ::= select",
101675  /* 295 */ "expr ::= RAISE LP IGNORE RP",
101676  /* 296 */ "expr ::= RAISE LP raisetype COMMA nm RP",
101677  /* 297 */ "raisetype ::= ROLLBACK",
101678  /* 298 */ "raisetype ::= ABORT",
101679  /* 299 */ "raisetype ::= FAIL",
101680  /* 300 */ "cmd ::= DROP TRIGGER ifexists fullname",
101681  /* 301 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
101682  /* 302 */ "cmd ::= DETACH database_kw_opt expr",
101683  /* 303 */ "key_opt ::=",
101684  /* 304 */ "key_opt ::= KEY expr",
101685  /* 305 */ "database_kw_opt ::= DATABASE",
101686  /* 306 */ "database_kw_opt ::=",
101687  /* 307 */ "cmd ::= REINDEX",
101688  /* 308 */ "cmd ::= REINDEX nm dbnm",
101689  /* 309 */ "cmd ::= ANALYZE",
101690  /* 310 */ "cmd ::= ANALYZE nm dbnm",
101691  /* 311 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
101692  /* 312 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
101693  /* 313 */ "add_column_fullname ::= fullname",
101694  /* 314 */ "kwcolumn_opt ::=",
101695  /* 315 */ "kwcolumn_opt ::= COLUMNKW",
101696  /* 316 */ "cmd ::= create_vtab",
101697  /* 317 */ "cmd ::= create_vtab LP vtabarglist RP",
101698  /* 318 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
101699  /* 319 */ "vtabarglist ::= vtabarg",
101700  /* 320 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
101701  /* 321 */ "vtabarg ::=",
101702  /* 322 */ "vtabarg ::= vtabarg vtabargtoken",
101703  /* 323 */ "vtabargtoken ::= ANY",
101704  /* 324 */ "vtabargtoken ::= lp anylist RP",
101705  /* 325 */ "lp ::= LP",
101706  /* 326 */ "anylist ::=",
101707  /* 327 */ "anylist ::= anylist LP anylist RP",
101708  /* 328 */ "anylist ::= anylist ANY",
101709 };
101710 #endif /* NDEBUG */
101711
101712
101713 #if YYSTACKDEPTH<=0
101714 /*
101715 ** Try to increase the size of the parser stack.
101716 */
101717 static void yyGrowStack(yyParser *p){
101718   int newSize;
101719   yyStackEntry *pNew;
101720
101721   newSize = p->yystksz*2 + 100;
101722   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
101723   if( pNew ){
101724     p->yystack = pNew;
101725     p->yystksz = newSize;
101726 #ifndef NDEBUG
101727     if( yyTraceFILE ){
101728       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
101729               yyTracePrompt, p->yystksz);
101730     }
101731 #endif
101732   }
101733 }
101734 #endif
101735
101736 /* 
101737 ** This function allocates a new parser.
101738 ** The only argument is a pointer to a function which works like
101739 ** malloc.
101740 **
101741 ** Inputs:
101742 ** A pointer to the function used to allocate memory.
101743 **
101744 ** Outputs:
101745 ** A pointer to a parser.  This pointer is used in subsequent calls
101746 ** to sqlite3Parser and sqlite3ParserFree.
101747 */
101748 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
101749   yyParser *pParser;
101750   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
101751   if( pParser ){
101752     pParser->yyidx = -1;
101753 #ifdef YYTRACKMAXSTACKDEPTH
101754     pParser->yyidxMax = 0;
101755 #endif
101756 #if YYSTACKDEPTH<=0
101757     pParser->yystack = NULL;
101758     pParser->yystksz = 0;
101759     yyGrowStack(pParser);
101760 #endif
101761   }
101762   return pParser;
101763 }
101764
101765 /* The following function deletes the value associated with a
101766 ** symbol.  The symbol can be either a terminal or nonterminal.
101767 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
101768 ** the value.
101769 */
101770 static void yy_destructor(
101771   yyParser *yypParser,    /* The parser */
101772   YYCODETYPE yymajor,     /* Type code for object to destroy */
101773   YYMINORTYPE *yypminor   /* The object to be destroyed */
101774 ){
101775   sqlite3ParserARG_FETCH;
101776   switch( yymajor ){
101777     /* Here is inserted the actions which take place when a
101778     ** terminal or non-terminal is destroyed.  This can happen
101779     ** when the symbol is popped from the stack during a
101780     ** reduce or during error processing or when a parser is 
101781     ** being destroyed before it is finished parsing.
101782     **
101783     ** Note: during a reduce, the only symbols destroyed are those
101784     ** which appear on the RHS of the rule, but which are not used
101785     ** inside the C code.
101786     */
101787     case 160: /* select */
101788     case 194: /* oneselect */
101789 {
101790 sqlite3SelectDelete(pParse->db, (yypminor->yy387));
101791 }
101792       break;
101793     case 174: /* term */
101794     case 175: /* expr */
101795 {
101796 sqlite3ExprDelete(pParse->db, (yypminor->yy118).pExpr);
101797 }
101798       break;
101799     case 179: /* idxlist_opt */
101800     case 187: /* idxlist */
101801     case 197: /* selcollist */
101802     case 200: /* groupby_opt */
101803     case 202: /* orderby_opt */
101804     case 204: /* sclp */
101805     case 214: /* sortlist */
101806     case 216: /* nexprlist */
101807     case 217: /* setlist */
101808     case 220: /* itemlist */
101809     case 221: /* exprlist */
101810     case 226: /* case_exprlist */
101811 {
101812 sqlite3ExprListDelete(pParse->db, (yypminor->yy322));
101813 }
101814       break;
101815     case 193: /* fullname */
101816     case 198: /* from */
101817     case 206: /* seltablist */
101818     case 207: /* stl_prefix */
101819 {
101820 sqlite3SrcListDelete(pParse->db, (yypminor->yy259));
101821 }
101822       break;
101823     case 199: /* where_opt */
101824     case 201: /* having_opt */
101825     case 210: /* on_opt */
101826     case 215: /* sortitem */
101827     case 225: /* case_operand */
101828     case 227: /* case_else */
101829     case 238: /* when_clause */
101830     case 243: /* key_opt */
101831 {
101832 sqlite3ExprDelete(pParse->db, (yypminor->yy314));
101833 }
101834       break;
101835     case 211: /* using_opt */
101836     case 213: /* inscollist */
101837     case 219: /* inscollist_opt */
101838 {
101839 sqlite3IdListDelete(pParse->db, (yypminor->yy384));
101840 }
101841       break;
101842     case 234: /* trigger_cmd_list */
101843     case 239: /* trigger_cmd */
101844 {
101845 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy203));
101846 }
101847       break;
101848     case 236: /* trigger_event */
101849 {
101850 sqlite3IdListDelete(pParse->db, (yypminor->yy90).b);
101851 }
101852       break;
101853     default:  break;   /* If no destructor action specified: do nothing */
101854   }
101855 }
101856
101857 /*
101858 ** Pop the parser's stack once.
101859 **
101860 ** If there is a destructor routine associated with the token which
101861 ** is popped from the stack, then call it.
101862 **
101863 ** Return the major token number for the symbol popped.
101864 */
101865 static int yy_pop_parser_stack(yyParser *pParser){
101866   YYCODETYPE yymajor;
101867   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
101868
101869   /* There is no mechanism by which the parser stack can be popped below
101870   ** empty in SQLite.  */
101871   if( NEVER(pParser->yyidx<0) ) return 0;
101872 #ifndef NDEBUG
101873   if( yyTraceFILE && pParser->yyidx>=0 ){
101874     fprintf(yyTraceFILE,"%sPopping %s\n",
101875       yyTracePrompt,
101876       yyTokenName[yytos->major]);
101877   }
101878 #endif
101879   yymajor = yytos->major;
101880   yy_destructor(pParser, yymajor, &yytos->minor);
101881   pParser->yyidx--;
101882   return yymajor;
101883 }
101884
101885 /* 
101886 ** Deallocate and destroy a parser.  Destructors are all called for
101887 ** all stack elements before shutting the parser down.
101888 **
101889 ** Inputs:
101890 ** <ul>
101891 ** <li>  A pointer to the parser.  This should be a pointer
101892 **       obtained from sqlite3ParserAlloc.
101893 ** <li>  A pointer to a function used to reclaim memory obtained
101894 **       from malloc.
101895 ** </ul>
101896 */
101897 SQLITE_PRIVATE void sqlite3ParserFree(
101898   void *p,                    /* The parser to be deleted */
101899   void (*freeProc)(void*)     /* Function used to reclaim memory */
101900 ){
101901   yyParser *pParser = (yyParser*)p;
101902   /* In SQLite, we never try to destroy a parser that was not successfully
101903   ** created in the first place. */
101904   if( NEVER(pParser==0) ) return;
101905   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
101906 #if YYSTACKDEPTH<=0
101907   free(pParser->yystack);
101908 #endif
101909   (*freeProc)((void*)pParser);
101910 }
101911
101912 /*
101913 ** Return the peak depth of the stack for a parser.
101914 */
101915 #ifdef YYTRACKMAXSTACKDEPTH
101916 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
101917   yyParser *pParser = (yyParser*)p;
101918   return pParser->yyidxMax;
101919 }
101920 #endif
101921
101922 /*
101923 ** Find the appropriate action for a parser given the terminal
101924 ** look-ahead token iLookAhead.
101925 **
101926 ** If the look-ahead token is YYNOCODE, then check to see if the action is
101927 ** independent of the look-ahead.  If it is, return the action, otherwise
101928 ** return YY_NO_ACTION.
101929 */
101930 static int yy_find_shift_action(
101931   yyParser *pParser,        /* The parser */
101932   YYCODETYPE iLookAhead     /* The look-ahead token */
101933 ){
101934   int i;
101935   int stateno = pParser->yystack[pParser->yyidx].stateno;
101936  
101937   if( stateno>YY_SHIFT_COUNT
101938    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
101939     return yy_default[stateno];
101940   }
101941   assert( iLookAhead!=YYNOCODE );
101942   i += iLookAhead;
101943   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
101944     if( iLookAhead>0 ){
101945 #ifdef YYFALLBACK
101946       YYCODETYPE iFallback;            /* Fallback token */
101947       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
101948              && (iFallback = yyFallback[iLookAhead])!=0 ){
101949 #ifndef NDEBUG
101950         if( yyTraceFILE ){
101951           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
101952              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
101953         }
101954 #endif
101955         return yy_find_shift_action(pParser, iFallback);
101956       }
101957 #endif
101958 #ifdef YYWILDCARD
101959       {
101960         int j = i - iLookAhead + YYWILDCARD;
101961         if( 
101962 #if YY_SHIFT_MIN+YYWILDCARD<0
101963           j>=0 &&
101964 #endif
101965 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
101966           j<YY_ACTTAB_COUNT &&
101967 #endif
101968           yy_lookahead[j]==YYWILDCARD
101969         ){
101970 #ifndef NDEBUG
101971           if( yyTraceFILE ){
101972             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
101973                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
101974           }
101975 #endif /* NDEBUG */
101976           return yy_action[j];
101977         }
101978       }
101979 #endif /* YYWILDCARD */
101980     }
101981     return yy_default[stateno];
101982   }else{
101983     return yy_action[i];
101984   }
101985 }
101986
101987 /*
101988 ** Find the appropriate action for a parser given the non-terminal
101989 ** look-ahead token iLookAhead.
101990 **
101991 ** If the look-ahead token is YYNOCODE, then check to see if the action is
101992 ** independent of the look-ahead.  If it is, return the action, otherwise
101993 ** return YY_NO_ACTION.
101994 */
101995 static int yy_find_reduce_action(
101996   int stateno,              /* Current state number */
101997   YYCODETYPE iLookAhead     /* The look-ahead token */
101998 ){
101999   int i;
102000 #ifdef YYERRORSYMBOL
102001   if( stateno>YY_REDUCE_COUNT ){
102002     return yy_default[stateno];
102003   }
102004 #else
102005   assert( stateno<=YY_REDUCE_COUNT );
102006 #endif
102007   i = yy_reduce_ofst[stateno];
102008   assert( i!=YY_REDUCE_USE_DFLT );
102009   assert( iLookAhead!=YYNOCODE );
102010   i += iLookAhead;
102011 #ifdef YYERRORSYMBOL
102012   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
102013     return yy_default[stateno];
102014   }
102015 #else
102016   assert( i>=0 && i<YY_ACTTAB_COUNT );
102017   assert( yy_lookahead[i]==iLookAhead );
102018 #endif
102019   return yy_action[i];
102020 }
102021
102022 /*
102023 ** The following routine is called if the stack overflows.
102024 */
102025 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
102026    sqlite3ParserARG_FETCH;
102027    yypParser->yyidx--;
102028 #ifndef NDEBUG
102029    if( yyTraceFILE ){
102030      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
102031    }
102032 #endif
102033    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
102034    /* Here code is inserted which will execute if the parser
102035    ** stack every overflows */
102036
102037   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
102038   sqlite3ErrorMsg(pParse, "parser stack overflow");
102039   pParse->parseError = 1;
102040    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
102041 }
102042
102043 /*
102044 ** Perform a shift action.
102045 */
102046 static void yy_shift(
102047   yyParser *yypParser,          /* The parser to be shifted */
102048   int yyNewState,               /* The new state to shift in */
102049   int yyMajor,                  /* The major token to shift in */
102050   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
102051 ){
102052   yyStackEntry *yytos;
102053   yypParser->yyidx++;
102054 #ifdef YYTRACKMAXSTACKDEPTH
102055   if( yypParser->yyidx>yypParser->yyidxMax ){
102056     yypParser->yyidxMax = yypParser->yyidx;
102057   }
102058 #endif
102059 #if YYSTACKDEPTH>0 
102060   if( yypParser->yyidx>=YYSTACKDEPTH ){
102061     yyStackOverflow(yypParser, yypMinor);
102062     return;
102063   }
102064 #else
102065   if( yypParser->yyidx>=yypParser->yystksz ){
102066     yyGrowStack(yypParser);
102067     if( yypParser->yyidx>=yypParser->yystksz ){
102068       yyStackOverflow(yypParser, yypMinor);
102069       return;
102070     }
102071   }
102072 #endif
102073   yytos = &yypParser->yystack[yypParser->yyidx];
102074   yytos->stateno = (YYACTIONTYPE)yyNewState;
102075   yytos->major = (YYCODETYPE)yyMajor;
102076   yytos->minor = *yypMinor;
102077 #ifndef NDEBUG
102078   if( yyTraceFILE && yypParser->yyidx>0 ){
102079     int i;
102080     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
102081     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
102082     for(i=1; i<=yypParser->yyidx; i++)
102083       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
102084     fprintf(yyTraceFILE,"\n");
102085   }
102086 #endif
102087 }
102088
102089 /* The following table contains information about every rule that
102090 ** is used during the reduce.
102091 */
102092 static const struct {
102093   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
102094   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
102095 } yyRuleInfo[] = {
102096   { 142, 1 },
102097   { 143, 2 },
102098   { 143, 1 },
102099   { 144, 1 },
102100   { 144, 3 },
102101   { 145, 0 },
102102   { 145, 1 },
102103   { 145, 3 },
102104   { 146, 1 },
102105   { 147, 3 },
102106   { 149, 0 },
102107   { 149, 1 },
102108   { 149, 2 },
102109   { 148, 0 },
102110   { 148, 1 },
102111   { 148, 1 },
102112   { 148, 1 },
102113   { 147, 2 },
102114   { 147, 2 },
102115   { 147, 2 },
102116   { 151, 1 },
102117   { 151, 0 },
102118   { 147, 2 },
102119   { 147, 3 },
102120   { 147, 5 },
102121   { 147, 2 },
102122   { 152, 6 },
102123   { 154, 1 },
102124   { 156, 0 },
102125   { 156, 3 },
102126   { 155, 1 },
102127   { 155, 0 },
102128   { 153, 4 },
102129   { 153, 2 },
102130   { 158, 3 },
102131   { 158, 1 },
102132   { 161, 3 },
102133   { 162, 1 },
102134   { 165, 1 },
102135   { 165, 1 },
102136   { 166, 1 },
102137   { 150, 1 },
102138   { 150, 1 },
102139   { 150, 1 },
102140   { 163, 0 },
102141   { 163, 1 },
102142   { 167, 1 },
102143   { 167, 4 },
102144   { 167, 6 },
102145   { 168, 1 },
102146   { 168, 2 },
102147   { 169, 1 },
102148   { 169, 1 },
102149   { 164, 2 },
102150   { 164, 0 },
102151   { 172, 3 },
102152   { 172, 1 },
102153   { 173, 2 },
102154   { 173, 4 },
102155   { 173, 3 },
102156   { 173, 3 },
102157   { 173, 2 },
102158   { 173, 2 },
102159   { 173, 3 },
102160   { 173, 5 },
102161   { 173, 2 },
102162   { 173, 4 },
102163   { 173, 4 },
102164   { 173, 1 },
102165   { 173, 2 },
102166   { 178, 0 },
102167   { 178, 1 },
102168   { 180, 0 },
102169   { 180, 2 },
102170   { 182, 2 },
102171   { 182, 3 },
102172   { 182, 3 },
102173   { 182, 3 },
102174   { 183, 2 },
102175   { 183, 2 },
102176   { 183, 1 },
102177   { 183, 1 },
102178   { 183, 2 },
102179   { 181, 3 },
102180   { 181, 2 },
102181   { 184, 0 },
102182   { 184, 2 },
102183   { 184, 2 },
102184   { 159, 0 },
102185   { 159, 2 },
102186   { 185, 3 },
102187   { 185, 2 },
102188   { 185, 1 },
102189   { 186, 2 },
102190   { 186, 7 },
102191   { 186, 5 },
102192   { 186, 5 },
102193   { 186, 10 },
102194   { 188, 0 },
102195   { 188, 1 },
102196   { 176, 0 },
102197   { 176, 3 },
102198   { 189, 0 },
102199   { 189, 2 },
102200   { 190, 1 },
102201   { 190, 1 },
102202   { 190, 1 },
102203   { 147, 4 },
102204   { 192, 2 },
102205   { 192, 0 },
102206   { 147, 8 },
102207   { 147, 4 },
102208   { 147, 1 },
102209   { 160, 1 },
102210   { 160, 3 },
102211   { 195, 1 },
102212   { 195, 2 },
102213   { 195, 1 },
102214   { 194, 9 },
102215   { 196, 1 },
102216   { 196, 1 },
102217   { 196, 0 },
102218   { 204, 2 },
102219   { 204, 0 },
102220   { 197, 3 },
102221   { 197, 2 },
102222   { 197, 4 },
102223   { 205, 2 },
102224   { 205, 1 },
102225   { 205, 0 },
102226   { 198, 0 },
102227   { 198, 2 },
102228   { 207, 2 },
102229   { 207, 0 },
102230   { 206, 7 },
102231   { 206, 7 },
102232   { 206, 7 },
102233   { 157, 0 },
102234   { 157, 2 },
102235   { 193, 2 },
102236   { 208, 1 },
102237   { 208, 2 },
102238   { 208, 3 },
102239   { 208, 4 },
102240   { 210, 2 },
102241   { 210, 0 },
102242   { 209, 0 },
102243   { 209, 3 },
102244   { 209, 2 },
102245   { 211, 4 },
102246   { 211, 0 },
102247   { 202, 0 },
102248   { 202, 3 },
102249   { 214, 4 },
102250   { 214, 2 },
102251   { 215, 1 },
102252   { 177, 1 },
102253   { 177, 1 },
102254   { 177, 0 },
102255   { 200, 0 },
102256   { 200, 3 },
102257   { 201, 0 },
102258   { 201, 2 },
102259   { 203, 0 },
102260   { 203, 2 },
102261   { 203, 4 },
102262   { 203, 4 },
102263   { 147, 5 },
102264   { 199, 0 },
102265   { 199, 2 },
102266   { 147, 7 },
102267   { 217, 5 },
102268   { 217, 3 },
102269   { 147, 8 },
102270   { 147, 5 },
102271   { 147, 6 },
102272   { 218, 2 },
102273   { 218, 1 },
102274   { 220, 3 },
102275   { 220, 1 },
102276   { 219, 0 },
102277   { 219, 3 },
102278   { 213, 3 },
102279   { 213, 1 },
102280   { 175, 1 },
102281   { 175, 3 },
102282   { 174, 1 },
102283   { 175, 1 },
102284   { 175, 1 },
102285   { 175, 3 },
102286   { 175, 5 },
102287   { 174, 1 },
102288   { 174, 1 },
102289   { 175, 1 },
102290   { 175, 1 },
102291   { 175, 3 },
102292   { 175, 6 },
102293   { 175, 5 },
102294   { 175, 4 },
102295   { 174, 1 },
102296   { 175, 3 },
102297   { 175, 3 },
102298   { 175, 3 },
102299   { 175, 3 },
102300   { 175, 3 },
102301   { 175, 3 },
102302   { 175, 3 },
102303   { 175, 3 },
102304   { 222, 1 },
102305   { 222, 2 },
102306   { 222, 1 },
102307   { 222, 2 },
102308   { 175, 3 },
102309   { 175, 5 },
102310   { 175, 2 },
102311   { 175, 3 },
102312   { 175, 3 },
102313   { 175, 4 },
102314   { 175, 2 },
102315   { 175, 2 },
102316   { 175, 2 },
102317   { 175, 2 },
102318   { 223, 1 },
102319   { 223, 2 },
102320   { 175, 5 },
102321   { 224, 1 },
102322   { 224, 2 },
102323   { 175, 5 },
102324   { 175, 3 },
102325   { 175, 5 },
102326   { 175, 4 },
102327   { 175, 4 },
102328   { 175, 5 },
102329   { 226, 5 },
102330   { 226, 4 },
102331   { 227, 2 },
102332   { 227, 0 },
102333   { 225, 1 },
102334   { 225, 0 },
102335   { 221, 1 },
102336   { 221, 0 },
102337   { 216, 3 },
102338   { 216, 1 },
102339   { 147, 11 },
102340   { 228, 1 },
102341   { 228, 0 },
102342   { 179, 0 },
102343   { 179, 3 },
102344   { 187, 5 },
102345   { 187, 3 },
102346   { 229, 0 },
102347   { 229, 2 },
102348   { 147, 4 },
102349   { 147, 1 },
102350   { 147, 2 },
102351   { 147, 3 },
102352   { 147, 5 },
102353   { 147, 6 },
102354   { 147, 5 },
102355   { 147, 6 },
102356   { 230, 1 },
102357   { 230, 1 },
102358   { 230, 1 },
102359   { 230, 1 },
102360   { 230, 1 },
102361   { 170, 2 },
102362   { 171, 2 },
102363   { 232, 1 },
102364   { 231, 1 },
102365   { 231, 0 },
102366   { 147, 5 },
102367   { 233, 11 },
102368   { 235, 1 },
102369   { 235, 1 },
102370   { 235, 2 },
102371   { 235, 0 },
102372   { 236, 1 },
102373   { 236, 1 },
102374   { 236, 3 },
102375   { 237, 0 },
102376   { 237, 3 },
102377   { 238, 0 },
102378   { 238, 2 },
102379   { 234, 3 },
102380   { 234, 2 },
102381   { 240, 1 },
102382   { 240, 3 },
102383   { 241, 0 },
102384   { 241, 3 },
102385   { 241, 2 },
102386   { 239, 7 },
102387   { 239, 8 },
102388   { 239, 5 },
102389   { 239, 5 },
102390   { 239, 1 },
102391   { 175, 4 },
102392   { 175, 6 },
102393   { 191, 1 },
102394   { 191, 1 },
102395   { 191, 1 },
102396   { 147, 4 },
102397   { 147, 6 },
102398   { 147, 3 },
102399   { 243, 0 },
102400   { 243, 2 },
102401   { 242, 1 },
102402   { 242, 0 },
102403   { 147, 1 },
102404   { 147, 3 },
102405   { 147, 1 },
102406   { 147, 3 },
102407   { 147, 6 },
102408   { 147, 6 },
102409   { 244, 1 },
102410   { 245, 0 },
102411   { 245, 1 },
102412   { 147, 1 },
102413   { 147, 4 },
102414   { 246, 7 },
102415   { 247, 1 },
102416   { 247, 3 },
102417   { 248, 0 },
102418   { 248, 2 },
102419   { 249, 1 },
102420   { 249, 3 },
102421   { 250, 1 },
102422   { 251, 0 },
102423   { 251, 4 },
102424   { 251, 2 },
102425 };
102426
102427 static void yy_accept(yyParser*);  /* Forward Declaration */
102428
102429 /*
102430 ** Perform a reduce action and the shift that must immediately
102431 ** follow the reduce.
102432 */
102433 static void yy_reduce(
102434   yyParser *yypParser,         /* The parser */
102435   int yyruleno                 /* Number of the rule by which to reduce */
102436 ){
102437   int yygoto;                     /* The next state */
102438   int yyact;                      /* The next action */
102439   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
102440   yyStackEntry *yymsp;            /* The top of the parser's stack */
102441   int yysize;                     /* Amount to pop the stack */
102442   sqlite3ParserARG_FETCH;
102443   yymsp = &yypParser->yystack[yypParser->yyidx];
102444 #ifndef NDEBUG
102445   if( yyTraceFILE && yyruleno>=0 
102446         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
102447     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
102448       yyRuleName[yyruleno]);
102449   }
102450 #endif /* NDEBUG */
102451
102452   /* Silence complaints from purify about yygotominor being uninitialized
102453   ** in some cases when it is copied into the stack after the following
102454   ** switch.  yygotominor is uninitialized when a rule reduces that does
102455   ** not set the value of its left-hand side nonterminal.  Leaving the
102456   ** value of the nonterminal uninitialized is utterly harmless as long
102457   ** as the value is never used.  So really the only thing this code
102458   ** accomplishes is to quieten purify.  
102459   **
102460   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
102461   ** without this code, their parser segfaults.  I'm not sure what there
102462   ** parser is doing to make this happen.  This is the second bug report
102463   ** from wireshark this week.  Clearly they are stressing Lemon in ways
102464   ** that it has not been previously stressed...  (SQLite ticket #2172)
102465   */
102466   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
102467   yygotominor = yyzerominor;
102468
102469
102470   switch( yyruleno ){
102471   /* Beginning here are the reduction cases.  A typical example
102472   ** follows:
102473   **   case 0:
102474   **  #line <lineno> <grammarfile>
102475   **     { ... }           // User supplied code
102476   **  #line <lineno> <thisfile>
102477   **     break;
102478   */
102479       case 5: /* explain ::= */
102480 { sqlite3BeginParse(pParse, 0); }
102481         break;
102482       case 6: /* explain ::= EXPLAIN */
102483 { sqlite3BeginParse(pParse, 1); }
102484         break;
102485       case 7: /* explain ::= EXPLAIN QUERY PLAN */
102486 { sqlite3BeginParse(pParse, 2); }
102487         break;
102488       case 8: /* cmdx ::= cmd */
102489 { sqlite3FinishCoding(pParse); }
102490         break;
102491       case 9: /* cmd ::= BEGIN transtype trans_opt */
102492 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy4);}
102493         break;
102494       case 13: /* transtype ::= */
102495 {yygotominor.yy4 = TK_DEFERRED;}
102496         break;
102497       case 14: /* transtype ::= DEFERRED */
102498       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
102499       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
102500       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
102501       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
102502 {yygotominor.yy4 = yymsp[0].major;}
102503         break;
102504       case 17: /* cmd ::= COMMIT trans_opt */
102505       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
102506 {sqlite3CommitTransaction(pParse);}
102507         break;
102508       case 19: /* cmd ::= ROLLBACK trans_opt */
102509 {sqlite3RollbackTransaction(pParse);}
102510         break;
102511       case 22: /* cmd ::= SAVEPOINT nm */
102512 {
102513   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
102514 }
102515         break;
102516       case 23: /* cmd ::= RELEASE savepoint_opt nm */
102517 {
102518   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
102519 }
102520         break;
102521       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
102522 {
102523   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
102524 }
102525         break;
102526       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
102527 {
102528    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy4,0,0,yymsp[-2].minor.yy4);
102529 }
102530         break;
102531       case 27: /* createkw ::= CREATE */
102532 {
102533   pParse->db->lookaside.bEnabled = 0;
102534   yygotominor.yy0 = yymsp[0].minor.yy0;
102535 }
102536         break;
102537       case 28: /* ifnotexists ::= */
102538       case 31: /* temp ::= */ yytestcase(yyruleno==31);
102539       case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
102540       case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
102541       case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
102542       case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
102543       case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
102544       case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
102545       case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
102546       case 121: /* distinct ::= */ yytestcase(yyruleno==121);
102547       case 222: /* between_op ::= BETWEEN */ yytestcase(yyruleno==222);
102548       case 225: /* in_op ::= IN */ yytestcase(yyruleno==225);
102549 {yygotominor.yy4 = 0;}
102550         break;
102551       case 29: /* ifnotexists ::= IF NOT EXISTS */
102552       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
102553       case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
102554       case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
102555       case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
102556       case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
102557       case 223: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==223);
102558       case 226: /* in_op ::= NOT IN */ yytestcase(yyruleno==226);
102559 {yygotominor.yy4 = 1;}
102560         break;
102561       case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
102562 {
102563   sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
102564 }
102565         break;
102566       case 33: /* create_table_args ::= AS select */
102567 {
102568   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy387);
102569   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
102570 }
102571         break;
102572       case 36: /* column ::= columnid type carglist */
102573 {
102574   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
102575   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
102576 }
102577         break;
102578       case 37: /* columnid ::= nm */
102579 {
102580   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
102581   yygotominor.yy0 = yymsp[0].minor.yy0;
102582 }
102583         break;
102584       case 38: /* id ::= ID */
102585       case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
102586       case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
102587       case 41: /* nm ::= id */ yytestcase(yyruleno==41);
102588       case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
102589       case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
102590       case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
102591       case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
102592       case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
102593       case 128: /* as ::= ids */ yytestcase(yyruleno==128);
102594       case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
102595       case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
102596       case 251: /* collate ::= COLLATE ids */ yytestcase(yyruleno==251);
102597       case 260: /* nmnum ::= plus_num */ yytestcase(yyruleno==260);
102598       case 261: /* nmnum ::= nm */ yytestcase(yyruleno==261);
102599       case 262: /* nmnum ::= ON */ yytestcase(yyruleno==262);
102600       case 263: /* nmnum ::= DELETE */ yytestcase(yyruleno==263);
102601       case 264: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==264);
102602       case 265: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==265);
102603       case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
102604       case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
102605       case 285: /* trnm ::= nm */ yytestcase(yyruleno==285);
102606 {yygotominor.yy0 = yymsp[0].minor.yy0;}
102607         break;
102608       case 45: /* type ::= typetoken */
102609 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
102610         break;
102611       case 47: /* typetoken ::= typename LP signed RP */
102612 {
102613   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
102614   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
102615 }
102616         break;
102617       case 48: /* typetoken ::= typename LP signed COMMA signed RP */
102618 {
102619   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
102620   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
102621 }
102622         break;
102623       case 50: /* typename ::= typename ids */
102624 {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);}
102625         break;
102626       case 57: /* ccons ::= DEFAULT term */
102627       case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
102628 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy118);}
102629         break;
102630       case 58: /* ccons ::= DEFAULT LP expr RP */
102631 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy118);}
102632         break;
102633       case 60: /* ccons ::= DEFAULT MINUS term */
102634 {
102635   ExprSpan v;
102636   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy118.pExpr, 0, 0);
102637   v.zStart = yymsp[-1].minor.yy0.z;
102638   v.zEnd = yymsp[0].minor.yy118.zEnd;
102639   sqlite3AddDefaultValue(pParse,&v);
102640 }
102641         break;
102642       case 61: /* ccons ::= DEFAULT id */
102643 {
102644   ExprSpan v;
102645   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
102646   sqlite3AddDefaultValue(pParse,&v);
102647 }
102648         break;
102649       case 63: /* ccons ::= NOT NULL onconf */
102650 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy4);}
102651         break;
102652       case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
102653 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy4,yymsp[0].minor.yy4,yymsp[-2].minor.yy4);}
102654         break;
102655       case 65: /* ccons ::= UNIQUE onconf */
102656 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy4,0,0,0,0);}
102657         break;
102658       case 66: /* ccons ::= CHECK LP expr RP */
102659 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy118.pExpr);}
102660         break;
102661       case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
102662 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy322,yymsp[0].minor.yy4);}
102663         break;
102664       case 68: /* ccons ::= defer_subclause */
102665 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy4);}
102666         break;
102667       case 69: /* ccons ::= COLLATE ids */
102668 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
102669         break;
102670       case 72: /* refargs ::= */
102671 { yygotominor.yy4 = OE_None*0x0101; /* EV: R-19803-45884 */}
102672         break;
102673       case 73: /* refargs ::= refargs refarg */
102674 { yygotominor.yy4 = (yymsp[-1].minor.yy4 & ~yymsp[0].minor.yy215.mask) | yymsp[0].minor.yy215.value; }
102675         break;
102676       case 74: /* refarg ::= MATCH nm */
102677       case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
102678 { yygotominor.yy215.value = 0;     yygotominor.yy215.mask = 0x000000; }
102679         break;
102680       case 76: /* refarg ::= ON DELETE refact */
102681 { yygotominor.yy215.value = yymsp[0].minor.yy4;     yygotominor.yy215.mask = 0x0000ff; }
102682         break;
102683       case 77: /* refarg ::= ON UPDATE refact */
102684 { yygotominor.yy215.value = yymsp[0].minor.yy4<<8;  yygotominor.yy215.mask = 0x00ff00; }
102685         break;
102686       case 78: /* refact ::= SET NULL */
102687 { yygotominor.yy4 = OE_SetNull;  /* EV: R-33326-45252 */}
102688         break;
102689       case 79: /* refact ::= SET DEFAULT */
102690 { yygotominor.yy4 = OE_SetDflt;  /* EV: R-33326-45252 */}
102691         break;
102692       case 80: /* refact ::= CASCADE */
102693 { yygotominor.yy4 = OE_Cascade;  /* EV: R-33326-45252 */}
102694         break;
102695       case 81: /* refact ::= RESTRICT */
102696 { yygotominor.yy4 = OE_Restrict; /* EV: R-33326-45252 */}
102697         break;
102698       case 82: /* refact ::= NO ACTION */
102699 { yygotominor.yy4 = OE_None;     /* EV: R-33326-45252 */}
102700         break;
102701       case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
102702       case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
102703       case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
102704       case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
102705 {yygotominor.yy4 = yymsp[0].minor.yy4;}
102706         break;
102707       case 88: /* conslist_opt ::= */
102708 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
102709         break;
102710       case 89: /* conslist_opt ::= COMMA conslist */
102711 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
102712         break;
102713       case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
102714 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy322,yymsp[0].minor.yy4,yymsp[-2].minor.yy4,0);}
102715         break;
102716       case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
102717 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy322,yymsp[0].minor.yy4,0,0,0,0);}
102718         break;
102719       case 96: /* tcons ::= CHECK LP expr RP onconf */
102720 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy118.pExpr);}
102721         break;
102722       case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
102723 {
102724     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy322, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[-1].minor.yy4);
102725     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy4);
102726 }
102727         break;
102728       case 100: /* onconf ::= */
102729 {yygotominor.yy4 = OE_Default;}
102730         break;
102731       case 102: /* orconf ::= */
102732 {yygotominor.yy210 = OE_Default;}
102733         break;
102734       case 103: /* orconf ::= OR resolvetype */
102735 {yygotominor.yy210 = (u8)yymsp[0].minor.yy4;}
102736         break;
102737       case 105: /* resolvetype ::= IGNORE */
102738 {yygotominor.yy4 = OE_Ignore;}
102739         break;
102740       case 106: /* resolvetype ::= REPLACE */
102741 {yygotominor.yy4 = OE_Replace;}
102742         break;
102743       case 107: /* cmd ::= DROP TABLE ifexists fullname */
102744 {
102745   sqlite3DropTable(pParse, yymsp[0].minor.yy259, 0, yymsp[-1].minor.yy4);
102746 }
102747         break;
102748       case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
102749 {
102750   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);
102751 }
102752         break;
102753       case 111: /* cmd ::= DROP VIEW ifexists fullname */
102754 {
102755   sqlite3DropTable(pParse, yymsp[0].minor.yy259, 1, yymsp[-1].minor.yy4);
102756 }
102757         break;
102758       case 112: /* cmd ::= select */
102759 {
102760   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
102761   sqlite3Select(pParse, yymsp[0].minor.yy387, &dest);
102762   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
102763 }
102764         break;
102765       case 113: /* select ::= oneselect */
102766 {yygotominor.yy387 = yymsp[0].minor.yy387;}
102767         break;
102768       case 114: /* select ::= select multiselect_op oneselect */
102769 {
102770   if( yymsp[0].minor.yy387 ){
102771     yymsp[0].minor.yy387->op = (u8)yymsp[-1].minor.yy4;
102772     yymsp[0].minor.yy387->pPrior = yymsp[-2].minor.yy387;
102773   }else{
102774     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy387);
102775   }
102776   yygotominor.yy387 = yymsp[0].minor.yy387;
102777 }
102778         break;
102779       case 116: /* multiselect_op ::= UNION ALL */
102780 {yygotominor.yy4 = TK_ALL;}
102781         break;
102782       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
102783 {
102784   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);
102785 }
102786         break;
102787       case 122: /* sclp ::= selcollist COMMA */
102788       case 247: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==247);
102789 {yygotominor.yy322 = yymsp[-1].minor.yy322;}
102790         break;
102791       case 123: /* sclp ::= */
102792       case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
102793       case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
102794       case 240: /* exprlist ::= */ yytestcase(yyruleno==240);
102795       case 246: /* idxlist_opt ::= */ yytestcase(yyruleno==246);
102796 {yygotominor.yy322 = 0;}
102797         break;
102798       case 124: /* selcollist ::= sclp expr as */
102799 {
102800    yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy322, yymsp[-1].minor.yy118.pExpr);
102801    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[0].minor.yy0, 1);
102802    sqlite3ExprListSetSpan(pParse,yygotominor.yy322,&yymsp[-1].minor.yy118);
102803 }
102804         break;
102805       case 125: /* selcollist ::= sclp STAR */
102806 {
102807   Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
102808   yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy322, p);
102809 }
102810         break;
102811       case 126: /* selcollist ::= sclp nm DOT STAR */
102812 {
102813   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
102814   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
102815   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
102816   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322, pDot);
102817 }
102818         break;
102819       case 129: /* as ::= */
102820 {yygotominor.yy0.n = 0;}
102821         break;
102822       case 130: /* from ::= */
102823 {yygotominor.yy259 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy259));}
102824         break;
102825       case 131: /* from ::= FROM seltablist */
102826 {
102827   yygotominor.yy259 = yymsp[0].minor.yy259;
102828   sqlite3SrcListShiftJoinType(yygotominor.yy259);
102829 }
102830         break;
102831       case 132: /* stl_prefix ::= seltablist joinop */
102832 {
102833    yygotominor.yy259 = yymsp[-1].minor.yy259;
102834    if( ALWAYS(yygotominor.yy259 && yygotominor.yy259->nSrc>0) ) yygotominor.yy259->a[yygotominor.yy259->nSrc-1].jointype = (u8)yymsp[0].minor.yy4;
102835 }
102836         break;
102837       case 133: /* stl_prefix ::= */
102838 {yygotominor.yy259 = 0;}
102839         break;
102840       case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
102841 {
102842   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);
102843   sqlite3SrcListIndexedBy(pParse, yygotominor.yy259, &yymsp[-2].minor.yy0);
102844 }
102845         break;
102846       case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
102847 {
102848     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);
102849   }
102850         break;
102851       case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
102852 {
102853     if( yymsp[-6].minor.yy259==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy314==0 && yymsp[0].minor.yy384==0 ){
102854       yygotominor.yy259 = yymsp[-4].minor.yy259;
102855     }else{
102856       Select *pSubquery;
102857       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy259);
102858       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy259,0,0,0,0,0,0,0);
102859       yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
102860     }
102861   }
102862         break;
102863       case 137: /* dbnm ::= */
102864       case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
102865 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
102866         break;
102867       case 139: /* fullname ::= nm dbnm */
102868 {yygotominor.yy259 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
102869         break;
102870       case 140: /* joinop ::= COMMA|JOIN */
102871 { yygotominor.yy4 = JT_INNER; }
102872         break;
102873       case 141: /* joinop ::= JOIN_KW JOIN */
102874 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
102875         break;
102876       case 142: /* joinop ::= JOIN_KW nm JOIN */
102877 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
102878         break;
102879       case 143: /* joinop ::= JOIN_KW nm nm JOIN */
102880 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
102881         break;
102882       case 144: /* on_opt ::= ON expr */
102883       case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
102884       case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
102885       case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
102886       case 235: /* case_else ::= ELSE expr */ yytestcase(yyruleno==235);
102887       case 237: /* case_operand ::= expr */ yytestcase(yyruleno==237);
102888 {yygotominor.yy314 = yymsp[0].minor.yy118.pExpr;}
102889         break;
102890       case 145: /* on_opt ::= */
102891       case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
102892       case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
102893       case 236: /* case_else ::= */ yytestcase(yyruleno==236);
102894       case 238: /* case_operand ::= */ yytestcase(yyruleno==238);
102895 {yygotominor.yy314 = 0;}
102896         break;
102897       case 148: /* indexed_opt ::= NOT INDEXED */
102898 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
102899         break;
102900       case 149: /* using_opt ::= USING LP inscollist RP */
102901       case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
102902 {yygotominor.yy384 = yymsp[-1].minor.yy384;}
102903         break;
102904       case 150: /* using_opt ::= */
102905       case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
102906 {yygotominor.yy384 = 0;}
102907         break;
102908       case 152: /* orderby_opt ::= ORDER BY sortlist */
102909       case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
102910       case 239: /* exprlist ::= nexprlist */ yytestcase(yyruleno==239);
102911 {yygotominor.yy322 = yymsp[0].minor.yy322;}
102912         break;
102913       case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
102914 {
102915   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322,yymsp[-1].minor.yy314);
102916   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
102917 }
102918         break;
102919       case 154: /* sortlist ::= sortitem sortorder */
102920 {
102921   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy314);
102922   if( yygotominor.yy322 && ALWAYS(yygotominor.yy322->a) ) yygotominor.yy322->a[0].sortOrder = (u8)yymsp[0].minor.yy4;
102923 }
102924         break;
102925       case 156: /* sortorder ::= ASC */
102926       case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
102927 {yygotominor.yy4 = SQLITE_SO_ASC;}
102928         break;
102929       case 157: /* sortorder ::= DESC */
102930 {yygotominor.yy4 = SQLITE_SO_DESC;}
102931         break;
102932       case 163: /* limit_opt ::= */
102933 {yygotominor.yy292.pLimit = 0; yygotominor.yy292.pOffset = 0;}
102934         break;
102935       case 164: /* limit_opt ::= LIMIT expr */
102936 {yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr; yygotominor.yy292.pOffset = 0;}
102937         break;
102938       case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
102939 {yygotominor.yy292.pLimit = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pOffset = yymsp[0].minor.yy118.pExpr;}
102940         break;
102941       case 166: /* limit_opt ::= LIMIT expr COMMA expr */
102942 {yygotominor.yy292.pOffset = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr;}
102943         break;
102944       case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
102945 {
102946   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy259, &yymsp[-1].minor.yy0);
102947   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy259,yymsp[0].minor.yy314);
102948 }
102949         break;
102950       case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
102951 {
102952   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy259, &yymsp[-3].minor.yy0);
102953   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy322,"set list"); 
102954   sqlite3Update(pParse,yymsp[-4].minor.yy259,yymsp[-1].minor.yy322,yymsp[0].minor.yy314,yymsp[-5].minor.yy210);
102955 }
102956         break;
102957       case 171: /* setlist ::= setlist COMMA nm EQ expr */
102958 {
102959   yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[0].minor.yy118.pExpr);
102960   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
102961 }
102962         break;
102963       case 172: /* setlist ::= nm EQ expr */
102964 {
102965   yygotominor.yy322 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy118.pExpr);
102966   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
102967 }
102968         break;
102969       case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
102970 {sqlite3Insert(pParse, yymsp[-5].minor.yy259, yymsp[-1].minor.yy322, 0, yymsp[-4].minor.yy384, yymsp[-7].minor.yy210);}
102971         break;
102972       case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
102973 {sqlite3Insert(pParse, yymsp[-2].minor.yy259, 0, yymsp[0].minor.yy387, yymsp[-1].minor.yy384, yymsp[-4].minor.yy210);}
102974         break;
102975       case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
102976 {sqlite3Insert(pParse, yymsp[-3].minor.yy259, 0, 0, yymsp[-2].minor.yy384, yymsp[-5].minor.yy210);}
102977         break;
102978       case 176: /* insert_cmd ::= INSERT orconf */
102979 {yygotominor.yy210 = yymsp[0].minor.yy210;}
102980         break;
102981       case 177: /* insert_cmd ::= REPLACE */
102982 {yygotominor.yy210 = OE_Replace;}
102983         break;
102984       case 178: /* itemlist ::= itemlist COMMA expr */
102985       case 241: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==241);
102986 {yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy118.pExpr);}
102987         break;
102988       case 179: /* itemlist ::= expr */
102989       case 242: /* nexprlist ::= expr */ yytestcase(yyruleno==242);
102990 {yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy118.pExpr);}
102991         break;
102992       case 182: /* inscollist ::= inscollist COMMA nm */
102993 {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy384,&yymsp[0].minor.yy0);}
102994         break;
102995       case 183: /* inscollist ::= nm */
102996 {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
102997         break;
102998       case 184: /* expr ::= term */
102999 {yygotominor.yy118 = yymsp[0].minor.yy118;}
103000         break;
103001       case 185: /* expr ::= LP expr RP */
103002 {yygotominor.yy118.pExpr = yymsp[-1].minor.yy118.pExpr; spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
103003         break;
103004       case 186: /* term ::= NULL */
103005       case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
103006       case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
103007 {spanExpr(&yygotominor.yy118, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
103008         break;
103009       case 187: /* expr ::= id */
103010       case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
103011 {spanExpr(&yygotominor.yy118, pParse, TK_ID, &yymsp[0].minor.yy0);}
103012         break;
103013       case 189: /* expr ::= nm DOT nm */
103014 {
103015   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
103016   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
103017   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
103018   spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
103019 }
103020         break;
103021       case 190: /* expr ::= nm DOT nm DOT nm */
103022 {
103023   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
103024   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
103025   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
103026   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
103027   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
103028   spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
103029 }
103030         break;
103031       case 193: /* expr ::= REGISTER */
103032 {
103033   /* When doing a nested parse, one can include terms in an expression
103034   ** that look like this:   #1 #2 ...  These terms refer to registers
103035   ** in the virtual machine.  #N is the N-th register. */
103036   if( pParse->nested==0 ){
103037     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
103038     yygotominor.yy118.pExpr = 0;
103039   }else{
103040     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
103041     if( yygotominor.yy118.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy118.pExpr->iTable);
103042   }
103043   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
103044 }
103045         break;
103046       case 194: /* expr ::= VARIABLE */
103047 {
103048   spanExpr(&yygotominor.yy118, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
103049   sqlite3ExprAssignVarNumber(pParse, yygotominor.yy118.pExpr);
103050   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
103051 }
103052         break;
103053       case 195: /* expr ::= expr COLLATE ids */
103054 {
103055   yygotominor.yy118.pExpr = sqlite3ExprSetCollByToken(pParse, yymsp[-2].minor.yy118.pExpr, &yymsp[0].minor.yy0);
103056   yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
103057   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
103058 }
103059         break;
103060       case 196: /* expr ::= CAST LP expr AS typetoken RP */
103061 {
103062   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy118.pExpr, 0, &yymsp[-1].minor.yy0);
103063   spanSet(&yygotominor.yy118,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
103064 }
103065         break;
103066       case 197: /* expr ::= ID LP distinct exprlist RP */
103067 {
103068   if( yymsp[-1].minor.yy322 && yymsp[-1].minor.yy322->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
103069     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
103070   }
103071   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0);
103072   spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
103073   if( yymsp[-2].minor.yy4 && yygotominor.yy118.pExpr ){
103074     yygotominor.yy118.pExpr->flags |= EP_Distinct;
103075   }
103076 }
103077         break;
103078       case 198: /* expr ::= ID LP STAR RP */
103079 {
103080   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
103081   spanSet(&yygotominor.yy118,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
103082 }
103083         break;
103084       case 199: /* term ::= CTIME_KW */
103085 {
103086   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
103087   ** treated as functions that return constants */
103088   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
103089   if( yygotominor.yy118.pExpr ){
103090     yygotominor.yy118.pExpr->op = TK_CONST_FUNC;  
103091   }
103092   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
103093 }
103094         break;
103095       case 200: /* expr ::= expr AND expr */
103096       case 201: /* expr ::= expr OR expr */ yytestcase(yyruleno==201);
103097       case 202: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==202);
103098       case 203: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==203);
103099       case 204: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==204);
103100       case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
103101       case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
103102       case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
103103 {spanBinaryExpr(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);}
103104         break;
103105       case 208: /* likeop ::= LIKE_KW */
103106       case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
103107 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 0;}
103108         break;
103109       case 209: /* likeop ::= NOT LIKE_KW */
103110       case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
103111 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 1;}
103112         break;
103113       case 212: /* expr ::= expr likeop expr */
103114 {
103115   ExprList *pList;
103116   pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy118.pExpr);
103117   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy118.pExpr);
103118   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy342.eOperator);
103119   if( yymsp[-1].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
103120   yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
103121   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
103122   if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
103123 }
103124         break;
103125       case 213: /* expr ::= expr likeop expr ESCAPE expr */
103126 {
103127   ExprList *pList;
103128   pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
103129   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy118.pExpr);
103130   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
103131   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy342.eOperator);
103132   if( yymsp[-3].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
103133   yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
103134   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
103135   if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
103136 }
103137         break;
103138       case 214: /* expr ::= expr ISNULL|NOTNULL */
103139 {spanUnaryPostfix(&yygotominor.yy118,pParse,yymsp[0].major,&yymsp[-1].minor.yy118,&yymsp[0].minor.yy0);}
103140         break;
103141       case 215: /* expr ::= expr NOT NULL */
103142 {spanUnaryPostfix(&yygotominor.yy118,pParse,TK_NOTNULL,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy0);}
103143         break;
103144       case 216: /* expr ::= expr IS expr */
103145 {
103146   spanBinaryExpr(&yygotominor.yy118,pParse,TK_IS,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);
103147   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_ISNULL);
103148 }
103149         break;
103150       case 217: /* expr ::= expr IS NOT expr */
103151 {
103152   spanBinaryExpr(&yygotominor.yy118,pParse,TK_ISNOT,&yymsp[-3].minor.yy118,&yymsp[0].minor.yy118);
103153   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_NOTNULL);
103154 }
103155         break;
103156       case 218: /* expr ::= NOT expr */
103157       case 219: /* expr ::= BITNOT expr */ yytestcase(yyruleno==219);
103158 {spanUnaryPrefix(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
103159         break;
103160       case 220: /* expr ::= MINUS expr */
103161 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UMINUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
103162         break;
103163       case 221: /* expr ::= PLUS expr */
103164 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UPLUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
103165         break;
103166       case 224: /* expr ::= expr between_op expr AND expr */
103167 {
103168   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
103169   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
103170   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy118.pExpr, 0, 0);
103171   if( yygotominor.yy118.pExpr ){
103172     yygotominor.yy118.pExpr->x.pList = pList;
103173   }else{
103174     sqlite3ExprListDelete(pParse->db, pList);
103175   } 
103176   if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
103177   yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
103178   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
103179 }
103180         break;
103181       case 227: /* expr ::= expr in_op LP exprlist RP */
103182 {
103183     if( yymsp[-1].minor.yy322==0 ){
103184       /* Expressions of the form
103185       **
103186       **      expr1 IN ()
103187       **      expr1 NOT IN ()
103188       **
103189       ** simplify to constants 0 (false) and 1 (true), respectively,
103190       ** regardless of the value of expr1.
103191       */
103192       yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy4]);
103193       sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy118.pExpr);
103194     }else{
103195       yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
103196       if( yygotominor.yy118.pExpr ){
103197         yygotominor.yy118.pExpr->x.pList = yymsp[-1].minor.yy322;
103198         sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
103199       }else{
103200         sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
103201       }
103202       if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
103203     }
103204     yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
103205     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
103206   }
103207         break;
103208       case 228: /* expr ::= LP select RP */
103209 {
103210     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
103211     if( yygotominor.yy118.pExpr ){
103212       yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
103213       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
103214       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
103215     }else{
103216       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
103217     }
103218     yygotominor.yy118.zStart = yymsp[-2].minor.yy0.z;
103219     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
103220   }
103221         break;
103222       case 229: /* expr ::= expr in_op LP select RP */
103223 {
103224     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
103225     if( yygotominor.yy118.pExpr ){
103226       yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
103227       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
103228       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
103229     }else{
103230       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
103231     }
103232     if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
103233     yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
103234     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
103235   }
103236         break;
103237       case 230: /* expr ::= expr in_op nm dbnm */
103238 {
103239     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
103240     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy118.pExpr, 0, 0);
103241     if( yygotominor.yy118.pExpr ){
103242       yygotominor.yy118.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
103243       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
103244       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
103245     }else{
103246       sqlite3SrcListDelete(pParse->db, pSrc);
103247     }
103248     if( yymsp[-2].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
103249     yygotominor.yy118.zStart = yymsp[-3].minor.yy118.zStart;
103250     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];
103251   }
103252         break;
103253       case 231: /* expr ::= EXISTS LP select RP */
103254 {
103255     Expr *p = yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
103256     if( p ){
103257       p->x.pSelect = yymsp[-1].minor.yy387;
103258       ExprSetProperty(p, EP_xIsSelect);
103259       sqlite3ExprSetHeight(pParse, p);
103260     }else{
103261       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
103262     }
103263     yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
103264     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
103265   }
103266         break;
103267       case 232: /* expr ::= CASE case_operand case_exprlist case_else END */
103268 {
103269   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy314, yymsp[-1].minor.yy314, 0);
103270   if( yygotominor.yy118.pExpr ){
103271     yygotominor.yy118.pExpr->x.pList = yymsp[-2].minor.yy322;
103272     sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
103273   }else{
103274     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy322);
103275   }
103276   yygotominor.yy118.zStart = yymsp[-4].minor.yy0.z;
103277   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
103278 }
103279         break;
103280       case 233: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
103281 {
103282   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy118.pExpr);
103283   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
103284 }
103285         break;
103286       case 234: /* case_exprlist ::= WHEN expr THEN expr */
103287 {
103288   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
103289   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
103290 }
103291         break;
103292       case 243: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
103293 {
103294   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, 
103295                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy322, yymsp[-9].minor.yy4,
103296                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy4);
103297 }
103298         break;
103299       case 244: /* uniqueflag ::= UNIQUE */
103300       case 298: /* raisetype ::= ABORT */ yytestcase(yyruleno==298);
103301 {yygotominor.yy4 = OE_Abort;}
103302         break;
103303       case 245: /* uniqueflag ::= */
103304 {yygotominor.yy4 = OE_None;}
103305         break;
103306       case 248: /* idxlist ::= idxlist COMMA nm collate sortorder */
103307 {
103308   Expr *p = 0;
103309   if( yymsp[-1].minor.yy0.n>0 ){
103310     p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
103311     sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
103312   }
103313   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, p);
103314   sqlite3ExprListSetName(pParse,yygotominor.yy322,&yymsp[-2].minor.yy0,1);
103315   sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
103316   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
103317 }
103318         break;
103319       case 249: /* idxlist ::= nm collate sortorder */
103320 {
103321   Expr *p = 0;
103322   if( yymsp[-1].minor.yy0.n>0 ){
103323     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
103324     sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
103325   }
103326   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, p);
103327   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
103328   sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
103329   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
103330 }
103331         break;
103332       case 250: /* collate ::= */
103333 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
103334         break;
103335       case 252: /* cmd ::= DROP INDEX ifexists fullname */
103336 {sqlite3DropIndex(pParse, yymsp[0].minor.yy259, yymsp[-1].minor.yy4);}
103337         break;
103338       case 253: /* cmd ::= VACUUM */
103339       case 254: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==254);
103340 {sqlite3Vacuum(pParse);}
103341         break;
103342       case 255: /* cmd ::= PRAGMA nm dbnm */
103343 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
103344         break;
103345       case 256: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
103346 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
103347         break;
103348       case 257: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
103349 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
103350         break;
103351       case 258: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
103352 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
103353         break;
103354       case 259: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
103355 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
103356         break;
103357       case 270: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
103358 {
103359   Token all;
103360   all.z = yymsp[-3].minor.yy0.z;
103361   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
103362   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy203, &all);
103363 }
103364         break;
103365       case 271: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
103366 {
103367   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);
103368   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
103369 }
103370         break;
103371       case 272: /* trigger_time ::= BEFORE */
103372       case 275: /* trigger_time ::= */ yytestcase(yyruleno==275);
103373 { yygotominor.yy4 = TK_BEFORE; }
103374         break;
103375       case 273: /* trigger_time ::= AFTER */
103376 { yygotominor.yy4 = TK_AFTER;  }
103377         break;
103378       case 274: /* trigger_time ::= INSTEAD OF */
103379 { yygotominor.yy4 = TK_INSTEAD;}
103380         break;
103381       case 276: /* trigger_event ::= DELETE|INSERT */
103382       case 277: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==277);
103383 {yygotominor.yy90.a = yymsp[0].major; yygotominor.yy90.b = 0;}
103384         break;
103385       case 278: /* trigger_event ::= UPDATE OF inscollist */
103386 {yygotominor.yy90.a = TK_UPDATE; yygotominor.yy90.b = yymsp[0].minor.yy384;}
103387         break;
103388       case 281: /* when_clause ::= */
103389       case 303: /* key_opt ::= */ yytestcase(yyruleno==303);
103390 { yygotominor.yy314 = 0; }
103391         break;
103392       case 282: /* when_clause ::= WHEN expr */
103393       case 304: /* key_opt ::= KEY expr */ yytestcase(yyruleno==304);
103394 { yygotominor.yy314 = yymsp[0].minor.yy118.pExpr; }
103395         break;
103396       case 283: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
103397 {
103398   assert( yymsp[-2].minor.yy203!=0 );
103399   yymsp[-2].minor.yy203->pLast->pNext = yymsp[-1].minor.yy203;
103400   yymsp[-2].minor.yy203->pLast = yymsp[-1].minor.yy203;
103401   yygotominor.yy203 = yymsp[-2].minor.yy203;
103402 }
103403         break;
103404       case 284: /* trigger_cmd_list ::= trigger_cmd SEMI */
103405
103406   assert( yymsp[-1].minor.yy203!=0 );
103407   yymsp[-1].minor.yy203->pLast = yymsp[-1].minor.yy203;
103408   yygotominor.yy203 = yymsp[-1].minor.yy203;
103409 }
103410         break;
103411       case 286: /* trnm ::= nm DOT nm */
103412 {
103413   yygotominor.yy0 = yymsp[0].minor.yy0;
103414   sqlite3ErrorMsg(pParse, 
103415         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
103416         "statements within triggers");
103417 }
103418         break;
103419       case 288: /* tridxby ::= INDEXED BY nm */
103420 {
103421   sqlite3ErrorMsg(pParse,
103422         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
103423         "within triggers");
103424 }
103425         break;
103426       case 289: /* tridxby ::= NOT INDEXED */
103427 {
103428   sqlite3ErrorMsg(pParse,
103429         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
103430         "within triggers");
103431 }
103432         break;
103433       case 290: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
103434 { yygotominor.yy203 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy322, yymsp[0].minor.yy314, yymsp[-5].minor.yy210); }
103435         break;
103436       case 291: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
103437 {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy384, yymsp[-1].minor.yy322, 0, yymsp[-7].minor.yy210);}
103438         break;
103439       case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
103440 {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy384, 0, yymsp[0].minor.yy387, yymsp[-4].minor.yy210);}
103441         break;
103442       case 293: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
103443 {yygotominor.yy203 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy314);}
103444         break;
103445       case 294: /* trigger_cmd ::= select */
103446 {yygotominor.yy203 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy387); }
103447         break;
103448       case 295: /* expr ::= RAISE LP IGNORE RP */
103449 {
103450   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
103451   if( yygotominor.yy118.pExpr ){
103452     yygotominor.yy118.pExpr->affinity = OE_Ignore;
103453   }
103454   yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
103455   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
103456 }
103457         break;
103458       case 296: /* expr ::= RAISE LP raisetype COMMA nm RP */
103459 {
103460   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
103461   if( yygotominor.yy118.pExpr ) {
103462     yygotominor.yy118.pExpr->affinity = (char)yymsp[-3].minor.yy4;
103463   }
103464   yygotominor.yy118.zStart = yymsp[-5].minor.yy0.z;
103465   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
103466 }
103467         break;
103468       case 297: /* raisetype ::= ROLLBACK */
103469 {yygotominor.yy4 = OE_Rollback;}
103470         break;
103471       case 299: /* raisetype ::= FAIL */
103472 {yygotominor.yy4 = OE_Fail;}
103473         break;
103474       case 300: /* cmd ::= DROP TRIGGER ifexists fullname */
103475 {
103476   sqlite3DropTrigger(pParse,yymsp[0].minor.yy259,yymsp[-1].minor.yy4);
103477 }
103478         break;
103479       case 301: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
103480 {
103481   sqlite3Attach(pParse, yymsp[-3].minor.yy118.pExpr, yymsp[-1].minor.yy118.pExpr, yymsp[0].minor.yy314);
103482 }
103483         break;
103484       case 302: /* cmd ::= DETACH database_kw_opt expr */
103485 {
103486   sqlite3Detach(pParse, yymsp[0].minor.yy118.pExpr);
103487 }
103488         break;
103489       case 307: /* cmd ::= REINDEX */
103490 {sqlite3Reindex(pParse, 0, 0);}
103491         break;
103492       case 308: /* cmd ::= REINDEX nm dbnm */
103493 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
103494         break;
103495       case 309: /* cmd ::= ANALYZE */
103496 {sqlite3Analyze(pParse, 0, 0);}
103497         break;
103498       case 310: /* cmd ::= ANALYZE nm dbnm */
103499 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
103500         break;
103501       case 311: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
103502 {
103503   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy259,&yymsp[0].minor.yy0);
103504 }
103505         break;
103506       case 312: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
103507 {
103508   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
103509 }
103510         break;
103511       case 313: /* add_column_fullname ::= fullname */
103512 {
103513   pParse->db->lookaside.bEnabled = 0;
103514   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy259);
103515 }
103516         break;
103517       case 316: /* cmd ::= create_vtab */
103518 {sqlite3VtabFinishParse(pParse,0);}
103519         break;
103520       case 317: /* cmd ::= create_vtab LP vtabarglist RP */
103521 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
103522         break;
103523       case 318: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
103524 {
103525     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
103526 }
103527         break;
103528       case 321: /* vtabarg ::= */
103529 {sqlite3VtabArgInit(pParse);}
103530         break;
103531       case 323: /* vtabargtoken ::= ANY */
103532       case 324: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==324);
103533       case 325: /* lp ::= LP */ yytestcase(yyruleno==325);
103534 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
103535         break;
103536       default:
103537       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
103538       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
103539       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
103540       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
103541       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
103542       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
103543       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
103544       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
103545       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
103546       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
103547       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
103548       /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
103549       /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
103550       /* (44) type ::= */ yytestcase(yyruleno==44);
103551       /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
103552       /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
103553       /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
103554       /* (54) carglist ::= */ yytestcase(yyruleno==54);
103555       /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
103556       /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
103557       /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
103558       /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
103559       /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
103560       /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
103561       /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
103562       /* (268) plus_opt ::= PLUS */ yytestcase(yyruleno==268);
103563       /* (269) plus_opt ::= */ yytestcase(yyruleno==269);
103564       /* (279) foreach_clause ::= */ yytestcase(yyruleno==279);
103565       /* (280) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==280);
103566       /* (287) tridxby ::= */ yytestcase(yyruleno==287);
103567       /* (305) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==305);
103568       /* (306) database_kw_opt ::= */ yytestcase(yyruleno==306);
103569       /* (314) kwcolumn_opt ::= */ yytestcase(yyruleno==314);
103570       /* (315) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==315);
103571       /* (319) vtabarglist ::= vtabarg */ yytestcase(yyruleno==319);
103572       /* (320) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==320);
103573       /* (322) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==322);
103574       /* (326) anylist ::= */ yytestcase(yyruleno==326);
103575       /* (327) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==327);
103576       /* (328) anylist ::= anylist ANY */ yytestcase(yyruleno==328);
103577         break;
103578   };
103579   yygoto = yyRuleInfo[yyruleno].lhs;
103580   yysize = yyRuleInfo[yyruleno].nrhs;
103581   yypParser->yyidx -= yysize;
103582   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
103583   if( yyact < YYNSTATE ){
103584 #ifdef NDEBUG
103585     /* If we are not debugging and the reduce action popped at least
103586     ** one element off the stack, then we can push the new element back
103587     ** onto the stack here, and skip the stack overflow test in yy_shift().
103588     ** That gives a significant speed improvement. */
103589     if( yysize ){
103590       yypParser->yyidx++;
103591       yymsp -= yysize-1;
103592       yymsp->stateno = (YYACTIONTYPE)yyact;
103593       yymsp->major = (YYCODETYPE)yygoto;
103594       yymsp->minor = yygotominor;
103595     }else
103596 #endif
103597     {
103598       yy_shift(yypParser,yyact,yygoto,&yygotominor);
103599     }
103600   }else{
103601     assert( yyact == YYNSTATE + YYNRULE + 1 );
103602     yy_accept(yypParser);
103603   }
103604 }
103605
103606 /*
103607 ** The following code executes when the parse fails
103608 */
103609 #ifndef YYNOERRORRECOVERY
103610 static void yy_parse_failed(
103611   yyParser *yypParser           /* The parser */
103612 ){
103613   sqlite3ParserARG_FETCH;
103614 #ifndef NDEBUG
103615   if( yyTraceFILE ){
103616     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
103617   }
103618 #endif
103619   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
103620   /* Here code is inserted which will be executed whenever the
103621   ** parser fails */
103622   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
103623 }
103624 #endif /* YYNOERRORRECOVERY */
103625
103626 /*
103627 ** The following code executes when a syntax error first occurs.
103628 */
103629 static void yy_syntax_error(
103630   yyParser *yypParser,           /* The parser */
103631   int yymajor,                   /* The major type of the error token */
103632   YYMINORTYPE yyminor            /* The minor type of the error token */
103633 ){
103634   sqlite3ParserARG_FETCH;
103635 #define TOKEN (yyminor.yy0)
103636
103637   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
103638   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
103639   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
103640   pParse->parseError = 1;
103641   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
103642 }
103643
103644 /*
103645 ** The following is executed when the parser accepts
103646 */
103647 static void yy_accept(
103648   yyParser *yypParser           /* The parser */
103649 ){
103650   sqlite3ParserARG_FETCH;
103651 #ifndef NDEBUG
103652   if( yyTraceFILE ){
103653     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
103654   }
103655 #endif
103656   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
103657   /* Here code is inserted which will be executed whenever the
103658   ** parser accepts */
103659   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
103660 }
103661
103662 /* The main parser program.
103663 ** The first argument is a pointer to a structure obtained from
103664 ** "sqlite3ParserAlloc" which describes the current state of the parser.
103665 ** The second argument is the major token number.  The third is
103666 ** the minor token.  The fourth optional argument is whatever the
103667 ** user wants (and specified in the grammar) and is available for
103668 ** use by the action routines.
103669 **
103670 ** Inputs:
103671 ** <ul>
103672 ** <li> A pointer to the parser (an opaque structure.)
103673 ** <li> The major token number.
103674 ** <li> The minor token number.
103675 ** <li> An option argument of a grammar-specified type.
103676 ** </ul>
103677 **
103678 ** Outputs:
103679 ** None.
103680 */
103681 SQLITE_PRIVATE void sqlite3Parser(
103682   void *yyp,                   /* The parser */
103683   int yymajor,                 /* The major token code number */
103684   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
103685   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
103686 ){
103687   YYMINORTYPE yyminorunion;
103688   int yyact;            /* The parser action. */
103689   int yyendofinput;     /* True if we are at the end of input */
103690 #ifdef YYERRORSYMBOL
103691   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
103692 #endif
103693   yyParser *yypParser;  /* The parser */
103694
103695   /* (re)initialize the parser, if necessary */
103696   yypParser = (yyParser*)yyp;
103697   if( yypParser->yyidx<0 ){
103698 #if YYSTACKDEPTH<=0
103699     if( yypParser->yystksz <=0 ){
103700       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
103701       yyminorunion = yyzerominor;
103702       yyStackOverflow(yypParser, &yyminorunion);
103703       return;
103704     }
103705 #endif
103706     yypParser->yyidx = 0;
103707     yypParser->yyerrcnt = -1;
103708     yypParser->yystack[0].stateno = 0;
103709     yypParser->yystack[0].major = 0;
103710   }
103711   yyminorunion.yy0 = yyminor;
103712   yyendofinput = (yymajor==0);
103713   sqlite3ParserARG_STORE;
103714
103715 #ifndef NDEBUG
103716   if( yyTraceFILE ){
103717     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
103718   }
103719 #endif
103720
103721   do{
103722     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
103723     if( yyact<YYNSTATE ){
103724       assert( !yyendofinput );  /* Impossible to shift the $ token */
103725       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
103726       yypParser->yyerrcnt--;
103727       yymajor = YYNOCODE;
103728     }else if( yyact < YYNSTATE + YYNRULE ){
103729       yy_reduce(yypParser,yyact-YYNSTATE);
103730     }else{
103731       assert( yyact == YY_ERROR_ACTION );
103732 #ifdef YYERRORSYMBOL
103733       int yymx;
103734 #endif
103735 #ifndef NDEBUG
103736       if( yyTraceFILE ){
103737         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
103738       }
103739 #endif
103740 #ifdef YYERRORSYMBOL
103741       /* A syntax error has occurred.
103742       ** The response to an error depends upon whether or not the
103743       ** grammar defines an error token "ERROR".  
103744       **
103745       ** This is what we do if the grammar does define ERROR:
103746       **
103747       **  * Call the %syntax_error function.
103748       **
103749       **  * Begin popping the stack until we enter a state where
103750       **    it is legal to shift the error symbol, then shift
103751       **    the error symbol.
103752       **
103753       **  * Set the error count to three.
103754       **
103755       **  * Begin accepting and shifting new tokens.  No new error
103756       **    processing will occur until three tokens have been
103757       **    shifted successfully.
103758       **
103759       */
103760       if( yypParser->yyerrcnt<0 ){
103761         yy_syntax_error(yypParser,yymajor,yyminorunion);
103762       }
103763       yymx = yypParser->yystack[yypParser->yyidx].major;
103764       if( yymx==YYERRORSYMBOL || yyerrorhit ){
103765 #ifndef NDEBUG
103766         if( yyTraceFILE ){
103767           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
103768              yyTracePrompt,yyTokenName[yymajor]);
103769         }
103770 #endif
103771         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
103772         yymajor = YYNOCODE;
103773       }else{
103774          while(
103775           yypParser->yyidx >= 0 &&
103776           yymx != YYERRORSYMBOL &&
103777           (yyact = yy_find_reduce_action(
103778                         yypParser->yystack[yypParser->yyidx].stateno,
103779                         YYERRORSYMBOL)) >= YYNSTATE
103780         ){
103781           yy_pop_parser_stack(yypParser);
103782         }
103783         if( yypParser->yyidx < 0 || yymajor==0 ){
103784           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
103785           yy_parse_failed(yypParser);
103786           yymajor = YYNOCODE;
103787         }else if( yymx!=YYERRORSYMBOL ){
103788           YYMINORTYPE u2;
103789           u2.YYERRSYMDT = 0;
103790           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
103791         }
103792       }
103793       yypParser->yyerrcnt = 3;
103794       yyerrorhit = 1;
103795 #elif defined(YYNOERRORRECOVERY)
103796       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
103797       ** do any kind of error recovery.  Instead, simply invoke the syntax
103798       ** error routine and continue going as if nothing had happened.
103799       **
103800       ** Applications can set this macro (for example inside %include) if
103801       ** they intend to abandon the parse upon the first syntax error seen.
103802       */
103803       yy_syntax_error(yypParser,yymajor,yyminorunion);
103804       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
103805       yymajor = YYNOCODE;
103806       
103807 #else  /* YYERRORSYMBOL is not defined */
103808       /* This is what we do if the grammar does not define ERROR:
103809       **
103810       **  * Report an error message, and throw away the input token.
103811       **
103812       **  * If the input token is $, then fail the parse.
103813       **
103814       ** As before, subsequent error messages are suppressed until
103815       ** three input tokens have been successfully shifted.
103816       */
103817       if( yypParser->yyerrcnt<=0 ){
103818         yy_syntax_error(yypParser,yymajor,yyminorunion);
103819       }
103820       yypParser->yyerrcnt = 3;
103821       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
103822       if( yyendofinput ){
103823         yy_parse_failed(yypParser);
103824       }
103825       yymajor = YYNOCODE;
103826 #endif
103827     }
103828   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
103829   return;
103830 }
103831
103832 /************** End of parse.c ***********************************************/
103833 /************** Begin file tokenize.c ****************************************/
103834 /*
103835 ** 2001 September 15
103836 **
103837 ** The author disclaims copyright to this source code.  In place of
103838 ** a legal notice, here is a blessing:
103839 **
103840 **    May you do good and not evil.
103841 **    May you find forgiveness for yourself and forgive others.
103842 **    May you share freely, never taking more than you give.
103843 **
103844 *************************************************************************
103845 ** An tokenizer for SQL
103846 **
103847 ** This file contains C code that splits an SQL input string up into
103848 ** individual tokens and sends those tokens one-by-one over to the
103849 ** parser for analysis.
103850 */
103851
103852 /*
103853 ** The charMap() macro maps alphabetic characters into their
103854 ** lower-case ASCII equivalent.  On ASCII machines, this is just
103855 ** an upper-to-lower case map.  On EBCDIC machines we also need
103856 ** to adjust the encoding.  Only alphabetic characters and underscores
103857 ** need to be translated.
103858 */
103859 #ifdef SQLITE_ASCII
103860 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
103861 #endif
103862 #ifdef SQLITE_EBCDIC
103863 # define charMap(X) ebcdicToAscii[(unsigned char)X]
103864 const unsigned char ebcdicToAscii[] = {
103865 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
103866    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
103867    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
103868    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
103869    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
103870    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
103871    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
103872    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
103873    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
103874    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
103875    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
103876    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
103877    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
103878    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
103879    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
103880    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
103881    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
103882 };
103883 #endif
103884
103885 /*
103886 ** The sqlite3KeywordCode function looks up an identifier to determine if
103887 ** it is a keyword.  If it is a keyword, the token code of that keyword is 
103888 ** returned.  If the input is not a keyword, TK_ID is returned.
103889 **
103890 ** The implementation of this routine was generated by a program,
103891 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
103892 ** The output of the mkkeywordhash.c program is written into a file
103893 ** named keywordhash.h and then included into this source file by
103894 ** the #include below.
103895 */
103896 /************** Include keywordhash.h in the middle of tokenize.c ************/
103897 /************** Begin file keywordhash.h *************************************/
103898 /***** This file contains automatically generated code ******
103899 **
103900 ** The code in this file has been automatically generated by
103901 **
103902 **   sqlite/tool/mkkeywordhash.c
103903 **
103904 ** The code in this file implements a function that determines whether
103905 ** or not a given identifier is really an SQL keyword.  The same thing
103906 ** might be implemented more directly using a hand-written hash table.
103907 ** But by using this automatically generated code, the size of the code
103908 ** is substantially reduced.  This is important for embedded applications
103909 ** on platforms with limited memory.
103910 */
103911 /* Hash score: 175 */
103912 static int keywordCode(const char *z, int n){
103913   /* zText[] encodes 811 bytes of keywords in 541 bytes */
103914   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
103915   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
103916   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
103917   /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
103918   /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
103919   /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
103920   /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
103921   /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
103922   /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
103923   /*   INITIALLY                                                          */
103924   static const char zText[540] = {
103925     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
103926     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
103927     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
103928     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
103929     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
103930     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
103931     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
103932     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
103933     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
103934     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
103935     'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
103936     'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
103937     'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
103938     'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
103939     'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
103940     'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
103941     'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
103942     'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
103943     'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
103944     'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
103945     'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
103946     'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
103947     'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
103948     'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
103949     'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
103950     'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
103951     'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
103952     'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
103953     'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
103954     'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
103955   };
103956   static const unsigned char aHash[127] = {
103957       72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
103958       42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
103959      118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
103960        0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
103961        0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
103962       92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
103963       96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
103964       39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
103965       58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
103966       29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
103967   };
103968   static const unsigned char aNext[121] = {
103969        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
103970        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
103971        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
103972        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
103973        0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
103974       62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
103975       61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
103976        0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
103977      103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
103978       35,  64,   0,   0,
103979   };
103980   static const unsigned char aLen[121] = {
103981        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
103982        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
103983       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
103984        4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
103985        5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
103986        7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
103987        7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
103988        6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
103989        4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
103990        6,   4,   9,   3,
103991   };
103992   static const unsigned short int aOffset[121] = {
103993        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
103994       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
103995       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
103996      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
103997      203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
103998      248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
103999      326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
104000      387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
104001      462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
104002      521, 527, 531, 536,
104003   };
104004   static const unsigned char aCode[121] = {
104005     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
104006     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    
104007     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    
104008     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      
104009     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       
104010     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,    
104011     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,  
104012     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,       
104013     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,       
104014     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,     
104015     TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,    
104016     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       
104017     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       
104018     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  
104019     TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    
104020     TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      
104021     TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    
104022     TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         
104023     TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    
104024     TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   
104025     TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    
104026     TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      
104027     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        
104028     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  
104029     TK_ALL,        
104030   };
104031   int h, i;
104032   if( n<2 ) return TK_ID;
104033   h = ((charMap(z[0])*4) ^
104034       (charMap(z[n-1])*3) ^
104035       n) % 127;
104036   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
104037     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
104038       testcase( i==0 ); /* REINDEX */
104039       testcase( i==1 ); /* INDEXED */
104040       testcase( i==2 ); /* INDEX */
104041       testcase( i==3 ); /* DESC */
104042       testcase( i==4 ); /* ESCAPE */
104043       testcase( i==5 ); /* EACH */
104044       testcase( i==6 ); /* CHECK */
104045       testcase( i==7 ); /* KEY */
104046       testcase( i==8 ); /* BEFORE */
104047       testcase( i==9 ); /* FOREIGN */
104048       testcase( i==10 ); /* FOR */
104049       testcase( i==11 ); /* IGNORE */
104050       testcase( i==12 ); /* REGEXP */
104051       testcase( i==13 ); /* EXPLAIN */
104052       testcase( i==14 ); /* INSTEAD */
104053       testcase( i==15 ); /* ADD */
104054       testcase( i==16 ); /* DATABASE */
104055       testcase( i==17 ); /* AS */
104056       testcase( i==18 ); /* SELECT */
104057       testcase( i==19 ); /* TABLE */
104058       testcase( i==20 ); /* LEFT */
104059       testcase( i==21 ); /* THEN */
104060       testcase( i==22 ); /* END */
104061       testcase( i==23 ); /* DEFERRABLE */
104062       testcase( i==24 ); /* ELSE */
104063       testcase( i==25 ); /* EXCEPT */
104064       testcase( i==26 ); /* TRANSACTION */
104065       testcase( i==27 ); /* ACTION */
104066       testcase( i==28 ); /* ON */
104067       testcase( i==29 ); /* NATURAL */
104068       testcase( i==30 ); /* ALTER */
104069       testcase( i==31 ); /* RAISE */
104070       testcase( i==32 ); /* EXCLUSIVE */
104071       testcase( i==33 ); /* EXISTS */
104072       testcase( i==34 ); /* SAVEPOINT */
104073       testcase( i==35 ); /* INTERSECT */
104074       testcase( i==36 ); /* TRIGGER */
104075       testcase( i==37 ); /* REFERENCES */
104076       testcase( i==38 ); /* CONSTRAINT */
104077       testcase( i==39 ); /* INTO */
104078       testcase( i==40 ); /* OFFSET */
104079       testcase( i==41 ); /* OF */
104080       testcase( i==42 ); /* SET */
104081       testcase( i==43 ); /* TEMPORARY */
104082       testcase( i==44 ); /* TEMP */
104083       testcase( i==45 ); /* OR */
104084       testcase( i==46 ); /* UNIQUE */
104085       testcase( i==47 ); /* QUERY */
104086       testcase( i==48 ); /* ATTACH */
104087       testcase( i==49 ); /* HAVING */
104088       testcase( i==50 ); /* GROUP */
104089       testcase( i==51 ); /* UPDATE */
104090       testcase( i==52 ); /* BEGIN */
104091       testcase( i==53 ); /* INNER */
104092       testcase( i==54 ); /* RELEASE */
104093       testcase( i==55 ); /* BETWEEN */
104094       testcase( i==56 ); /* NOTNULL */
104095       testcase( i==57 ); /* NOT */
104096       testcase( i==58 ); /* NO */
104097       testcase( i==59 ); /* NULL */
104098       testcase( i==60 ); /* LIKE */
104099       testcase( i==61 ); /* CASCADE */
104100       testcase( i==62 ); /* ASC */
104101       testcase( i==63 ); /* DELETE */
104102       testcase( i==64 ); /* CASE */
104103       testcase( i==65 ); /* COLLATE */
104104       testcase( i==66 ); /* CREATE */
104105       testcase( i==67 ); /* CURRENT_DATE */
104106       testcase( i==68 ); /* DETACH */
104107       testcase( i==69 ); /* IMMEDIATE */
104108       testcase( i==70 ); /* JOIN */
104109       testcase( i==71 ); /* INSERT */
104110       testcase( i==72 ); /* MATCH */
104111       testcase( i==73 ); /* PLAN */
104112       testcase( i==74 ); /* ANALYZE */
104113       testcase( i==75 ); /* PRAGMA */
104114       testcase( i==76 ); /* ABORT */
104115       testcase( i==77 ); /* VALUES */
104116       testcase( i==78 ); /* VIRTUAL */
104117       testcase( i==79 ); /* LIMIT */
104118       testcase( i==80 ); /* WHEN */
104119       testcase( i==81 ); /* WHERE */
104120       testcase( i==82 ); /* RENAME */
104121       testcase( i==83 ); /* AFTER */
104122       testcase( i==84 ); /* REPLACE */
104123       testcase( i==85 ); /* AND */
104124       testcase( i==86 ); /* DEFAULT */
104125       testcase( i==87 ); /* AUTOINCREMENT */
104126       testcase( i==88 ); /* TO */
104127       testcase( i==89 ); /* IN */
104128       testcase( i==90 ); /* CAST */
104129       testcase( i==91 ); /* COLUMN */
104130       testcase( i==92 ); /* COMMIT */
104131       testcase( i==93 ); /* CONFLICT */
104132       testcase( i==94 ); /* CROSS */
104133       testcase( i==95 ); /* CURRENT_TIMESTAMP */
104134       testcase( i==96 ); /* CURRENT_TIME */
104135       testcase( i==97 ); /* PRIMARY */
104136       testcase( i==98 ); /* DEFERRED */
104137       testcase( i==99 ); /* DISTINCT */
104138       testcase( i==100 ); /* IS */
104139       testcase( i==101 ); /* DROP */
104140       testcase( i==102 ); /* FAIL */
104141       testcase( i==103 ); /* FROM */
104142       testcase( i==104 ); /* FULL */
104143       testcase( i==105 ); /* GLOB */
104144       testcase( i==106 ); /* BY */
104145       testcase( i==107 ); /* IF */
104146       testcase( i==108 ); /* ISNULL */
104147       testcase( i==109 ); /* ORDER */
104148       testcase( i==110 ); /* RESTRICT */
104149       testcase( i==111 ); /* OUTER */
104150       testcase( i==112 ); /* RIGHT */
104151       testcase( i==113 ); /* ROLLBACK */
104152       testcase( i==114 ); /* ROW */
104153       testcase( i==115 ); /* UNION */
104154       testcase( i==116 ); /* USING */
104155       testcase( i==117 ); /* VACUUM */
104156       testcase( i==118 ); /* VIEW */
104157       testcase( i==119 ); /* INITIALLY */
104158       testcase( i==120 ); /* ALL */
104159       return aCode[i];
104160     }
104161   }
104162   return TK_ID;
104163 }
104164 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
104165   return keywordCode((char*)z, n);
104166 }
104167 #define SQLITE_N_KEYWORD 121
104168
104169 /************** End of keywordhash.h *****************************************/
104170 /************** Continuing where we left off in tokenize.c *******************/
104171
104172
104173 /*
104174 ** If X is a character that can be used in an identifier then
104175 ** IdChar(X) will be true.  Otherwise it is false.
104176 **
104177 ** For ASCII, any character with the high-order bit set is
104178 ** allowed in an identifier.  For 7-bit characters, 
104179 ** sqlite3IsIdChar[X] must be 1.
104180 **
104181 ** For EBCDIC, the rules are more complex but have the same
104182 ** end result.
104183 **
104184 ** Ticket #1066.  the SQL standard does not allow '$' in the
104185 ** middle of identfiers.  But many SQL implementations do. 
104186 ** SQLite will allow '$' in identifiers for compatibility.
104187 ** But the feature is undocumented.
104188 */
104189 #ifdef SQLITE_ASCII
104190 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
104191 #endif
104192 #ifdef SQLITE_EBCDIC
104193 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
104194 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
104195     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
104196     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
104197     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
104198     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
104199     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
104200     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
104201     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
104202     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
104203     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
104204     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
104205     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
104206     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
104207 };
104208 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
104209 #endif
104210
104211
104212 /*
104213 ** Return the length of the token that begins at z[0]. 
104214 ** Store the token type in *tokenType before returning.
104215 */
104216 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
104217   int i, c;
104218   switch( *z ){
104219     case ' ': case '\t': case '\n': case '\f': case '\r': {
104220       testcase( z[0]==' ' );
104221       testcase( z[0]=='\t' );
104222       testcase( z[0]=='\n' );
104223       testcase( z[0]=='\f' );
104224       testcase( z[0]=='\r' );
104225       for(i=1; sqlite3Isspace(z[i]); i++){}
104226       *tokenType = TK_SPACE;
104227       return i;
104228     }
104229     case '-': {
104230       if( z[1]=='-' ){
104231         /* IMP: R-15891-05542 -- syntax diagram for comments */
104232         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
104233         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
104234         return i;
104235       }
104236       *tokenType = TK_MINUS;
104237       return 1;
104238     }
104239     case '(': {
104240       *tokenType = TK_LP;
104241       return 1;
104242     }
104243     case ')': {
104244       *tokenType = TK_RP;
104245       return 1;
104246     }
104247     case ';': {
104248       *tokenType = TK_SEMI;
104249       return 1;
104250     }
104251     case '+': {
104252       *tokenType = TK_PLUS;
104253       return 1;
104254     }
104255     case '*': {
104256       *tokenType = TK_STAR;
104257       return 1;
104258     }
104259     case '/': {
104260       if( z[1]!='*' || z[2]==0 ){
104261         *tokenType = TK_SLASH;
104262         return 1;
104263       }
104264       /* IMP: R-15891-05542 -- syntax diagram for comments */
104265       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
104266       if( c ) i++;
104267       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
104268       return i;
104269     }
104270     case '%': {
104271       *tokenType = TK_REM;
104272       return 1;
104273     }
104274     case '=': {
104275       *tokenType = TK_EQ;
104276       return 1 + (z[1]=='=');
104277     }
104278     case '<': {
104279       if( (c=z[1])=='=' ){
104280         *tokenType = TK_LE;
104281         return 2;
104282       }else if( c=='>' ){
104283         *tokenType = TK_NE;
104284         return 2;
104285       }else if( c=='<' ){
104286         *tokenType = TK_LSHIFT;
104287         return 2;
104288       }else{
104289         *tokenType = TK_LT;
104290         return 1;
104291       }
104292     }
104293     case '>': {
104294       if( (c=z[1])=='=' ){
104295         *tokenType = TK_GE;
104296         return 2;
104297       }else if( c=='>' ){
104298         *tokenType = TK_RSHIFT;
104299         return 2;
104300       }else{
104301         *tokenType = TK_GT;
104302         return 1;
104303       }
104304     }
104305     case '!': {
104306       if( z[1]!='=' ){
104307         *tokenType = TK_ILLEGAL;
104308         return 2;
104309       }else{
104310         *tokenType = TK_NE;
104311         return 2;
104312       }
104313     }
104314     case '|': {
104315       if( z[1]!='|' ){
104316         *tokenType = TK_BITOR;
104317         return 1;
104318       }else{
104319         *tokenType = TK_CONCAT;
104320         return 2;
104321       }
104322     }
104323     case ',': {
104324       *tokenType = TK_COMMA;
104325       return 1;
104326     }
104327     case '&': {
104328       *tokenType = TK_BITAND;
104329       return 1;
104330     }
104331     case '~': {
104332       *tokenType = TK_BITNOT;
104333       return 1;
104334     }
104335     case '`':
104336     case '\'':
104337     case '"': {
104338       int delim = z[0];
104339       testcase( delim=='`' );
104340       testcase( delim=='\'' );
104341       testcase( delim=='"' );
104342       for(i=1; (c=z[i])!=0; i++){
104343         if( c==delim ){
104344           if( z[i+1]==delim ){
104345             i++;
104346           }else{
104347             break;
104348           }
104349         }
104350       }
104351       if( c=='\'' ){
104352         *tokenType = TK_STRING;
104353         return i+1;
104354       }else if( c!=0 ){
104355         *tokenType = TK_ID;
104356         return i+1;
104357       }else{
104358         *tokenType = TK_ILLEGAL;
104359         return i;
104360       }
104361     }
104362     case '.': {
104363 #ifndef SQLITE_OMIT_FLOATING_POINT
104364       if( !sqlite3Isdigit(z[1]) )
104365 #endif
104366       {
104367         *tokenType = TK_DOT;
104368         return 1;
104369       }
104370       /* If the next character is a digit, this is a floating point
104371       ** number that begins with ".".  Fall thru into the next case */
104372     }
104373     case '0': case '1': case '2': case '3': case '4':
104374     case '5': case '6': case '7': case '8': case '9': {
104375       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
104376       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
104377       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
104378       testcase( z[0]=='9' );
104379       *tokenType = TK_INTEGER;
104380       for(i=0; sqlite3Isdigit(z[i]); i++){}
104381 #ifndef SQLITE_OMIT_FLOATING_POINT
104382       if( z[i]=='.' ){
104383         i++;
104384         while( sqlite3Isdigit(z[i]) ){ i++; }
104385         *tokenType = TK_FLOAT;
104386       }
104387       if( (z[i]=='e' || z[i]=='E') &&
104388            ( sqlite3Isdigit(z[i+1]) 
104389             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
104390            )
104391       ){
104392         i += 2;
104393         while( sqlite3Isdigit(z[i]) ){ i++; }
104394         *tokenType = TK_FLOAT;
104395       }
104396 #endif
104397       while( IdChar(z[i]) ){
104398         *tokenType = TK_ILLEGAL;
104399         i++;
104400       }
104401       return i;
104402     }
104403     case '[': {
104404       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
104405       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
104406       return i;
104407     }
104408     case '?': {
104409       *tokenType = TK_VARIABLE;
104410       for(i=1; sqlite3Isdigit(z[i]); i++){}
104411       return i;
104412     }
104413     case '#': {
104414       for(i=1; sqlite3Isdigit(z[i]); i++){}
104415       if( i>1 ){
104416         /* Parameters of the form #NNN (where NNN is a number) are used
104417         ** internally by sqlite3NestedParse.  */
104418         *tokenType = TK_REGISTER;
104419         return i;
104420       }
104421       /* Fall through into the next case if the '#' is not followed by
104422       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
104423     }
104424 #ifndef SQLITE_OMIT_TCL_VARIABLE
104425     case '$':
104426 #endif
104427     case '@':  /* For compatibility with MS SQL Server */
104428     case ':': {
104429       int n = 0;
104430       testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
104431       *tokenType = TK_VARIABLE;
104432       for(i=1; (c=z[i])!=0; i++){
104433         if( IdChar(c) ){
104434           n++;
104435 #ifndef SQLITE_OMIT_TCL_VARIABLE
104436         }else if( c=='(' && n>0 ){
104437           do{
104438             i++;
104439           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
104440           if( c==')' ){
104441             i++;
104442           }else{
104443             *tokenType = TK_ILLEGAL;
104444           }
104445           break;
104446         }else if( c==':' && z[i+1]==':' ){
104447           i++;
104448 #endif
104449         }else{
104450           break;
104451         }
104452       }
104453       if( n==0 ) *tokenType = TK_ILLEGAL;
104454       return i;
104455     }
104456 #ifndef SQLITE_OMIT_BLOB_LITERAL
104457     case 'x': case 'X': {
104458       testcase( z[0]=='x' ); testcase( z[0]=='X' );
104459       if( z[1]=='\'' ){
104460         *tokenType = TK_BLOB;
104461         for(i=2; (c=z[i])!=0 && c!='\''; i++){
104462           if( !sqlite3Isxdigit(c) ){
104463             *tokenType = TK_ILLEGAL;
104464           }
104465         }
104466         if( i%2 || !c ) *tokenType = TK_ILLEGAL;
104467         if( c ) i++;
104468         return i;
104469       }
104470       /* Otherwise fall through to the next case */
104471     }
104472 #endif
104473     default: {
104474       if( !IdChar(*z) ){
104475         break;
104476       }
104477       for(i=1; IdChar(z[i]); i++){}
104478       *tokenType = keywordCode((char*)z, i);
104479       return i;
104480     }
104481   }
104482   *tokenType = TK_ILLEGAL;
104483   return 1;
104484 }
104485
104486 /*
104487 ** Run the parser on the given SQL string.  The parser structure is
104488 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
104489 ** then an and attempt is made to write an error message into 
104490 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
104491 ** error message.
104492 */
104493 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
104494   int nErr = 0;                   /* Number of errors encountered */
104495   int i;                          /* Loop counter */
104496   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
104497   int tokenType;                  /* type of the next token */
104498   int lastTokenParsed = -1;       /* type of the previous token */
104499   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
104500   sqlite3 *db = pParse->db;       /* The database connection */
104501   int mxSqlLen;                   /* Max length of an SQL string */
104502
104503
104504   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
104505   if( db->activeVdbeCnt==0 ){
104506     db->u1.isInterrupted = 0;
104507   }
104508   pParse->rc = SQLITE_OK;
104509   pParse->zTail = zSql;
104510   i = 0;
104511   assert( pzErrMsg!=0 );
104512   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
104513   if( pEngine==0 ){
104514     db->mallocFailed = 1;
104515     return SQLITE_NOMEM;
104516   }
104517   assert( pParse->pNewTable==0 );
104518   assert( pParse->pNewTrigger==0 );
104519   assert( pParse->nVar==0 );
104520   assert( pParse->nVarExpr==0 );
104521   assert( pParse->nVarExprAlloc==0 );
104522   assert( pParse->apVarExpr==0 );
104523   enableLookaside = db->lookaside.bEnabled;
104524   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
104525   while( !db->mallocFailed && zSql[i]!=0 ){
104526     assert( i>=0 );
104527     pParse->sLastToken.z = &zSql[i];
104528     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
104529     i += pParse->sLastToken.n;
104530     if( i>mxSqlLen ){
104531       pParse->rc = SQLITE_TOOBIG;
104532       break;
104533     }
104534     switch( tokenType ){
104535       case TK_SPACE: {
104536         if( db->u1.isInterrupted ){
104537           sqlite3ErrorMsg(pParse, "interrupt");
104538           pParse->rc = SQLITE_INTERRUPT;
104539           goto abort_parse;
104540         }
104541         break;
104542       }
104543       case TK_ILLEGAL: {
104544         sqlite3DbFree(db, *pzErrMsg);
104545         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
104546                         &pParse->sLastToken);
104547         nErr++;
104548         goto abort_parse;
104549       }
104550       case TK_SEMI: {
104551         pParse->zTail = &zSql[i];
104552         /* Fall thru into the default case */
104553       }
104554       default: {
104555         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
104556         lastTokenParsed = tokenType;
104557         if( pParse->rc!=SQLITE_OK ){
104558           goto abort_parse;
104559         }
104560         break;
104561       }
104562     }
104563   }
104564 abort_parse:
104565   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
104566     if( lastTokenParsed!=TK_SEMI ){
104567       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
104568       pParse->zTail = &zSql[i];
104569     }
104570     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
104571   }
104572 #ifdef YYTRACKMAXSTACKDEPTH
104573   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
104574       sqlite3ParserStackPeak(pEngine)
104575   );
104576 #endif /* YYDEBUG */
104577   sqlite3ParserFree(pEngine, sqlite3_free);
104578   db->lookaside.bEnabled = enableLookaside;
104579   if( db->mallocFailed ){
104580     pParse->rc = SQLITE_NOMEM;
104581   }
104582   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
104583     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
104584   }
104585   assert( pzErrMsg!=0 );
104586   if( pParse->zErrMsg ){
104587     *pzErrMsg = pParse->zErrMsg;
104588     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
104589     pParse->zErrMsg = 0;
104590     nErr++;
104591   }
104592   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
104593     sqlite3VdbeDelete(pParse->pVdbe);
104594     pParse->pVdbe = 0;
104595   }
104596 #ifndef SQLITE_OMIT_SHARED_CACHE
104597   if( pParse->nested==0 ){
104598     sqlite3DbFree(db, pParse->aTableLock);
104599     pParse->aTableLock = 0;
104600     pParse->nTableLock = 0;
104601   }
104602 #endif
104603 #ifndef SQLITE_OMIT_VIRTUALTABLE
104604   sqlite3_free(pParse->apVtabLock);
104605 #endif
104606
104607   if( !IN_DECLARE_VTAB ){
104608     /* If the pParse->declareVtab flag is set, do not delete any table 
104609     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
104610     ** will take responsibility for freeing the Table structure.
104611     */
104612     sqlite3DeleteTable(db, pParse->pNewTable);
104613   }
104614
104615   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
104616   sqlite3DbFree(db, pParse->apVarExpr);
104617   sqlite3DbFree(db, pParse->aAlias);
104618   while( pParse->pAinc ){
104619     AutoincInfo *p = pParse->pAinc;
104620     pParse->pAinc = p->pNext;
104621     sqlite3DbFree(db, p);
104622   }
104623   while( pParse->pZombieTab ){
104624     Table *p = pParse->pZombieTab;
104625     pParse->pZombieTab = p->pNextZombie;
104626     sqlite3DeleteTable(db, p);
104627   }
104628   if( nErr>0 && pParse->rc==SQLITE_OK ){
104629     pParse->rc = SQLITE_ERROR;
104630   }
104631   return nErr;
104632 }
104633
104634 /************** End of tokenize.c ********************************************/
104635 /************** Begin file complete.c ****************************************/
104636 /*
104637 ** 2001 September 15
104638 **
104639 ** The author disclaims copyright to this source code.  In place of
104640 ** a legal notice, here is a blessing:
104641 **
104642 **    May you do good and not evil.
104643 **    May you find forgiveness for yourself and forgive others.
104644 **    May you share freely, never taking more than you give.
104645 **
104646 *************************************************************************
104647 ** An tokenizer for SQL
104648 **
104649 ** This file contains C code that implements the sqlite3_complete() API.
104650 ** This code used to be part of the tokenizer.c source file.  But by
104651 ** separating it out, the code will be automatically omitted from
104652 ** static links that do not use it.
104653 */
104654 #ifndef SQLITE_OMIT_COMPLETE
104655
104656 /*
104657 ** This is defined in tokenize.c.  We just have to import the definition.
104658 */
104659 #ifndef SQLITE_AMALGAMATION
104660 #ifdef SQLITE_ASCII
104661 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
104662 #endif
104663 #ifdef SQLITE_EBCDIC
104664 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
104665 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
104666 #endif
104667 #endif /* SQLITE_AMALGAMATION */
104668
104669
104670 /*
104671 ** Token types used by the sqlite3_complete() routine.  See the header
104672 ** comments on that procedure for additional information.
104673 */
104674 #define tkSEMI    0
104675 #define tkWS      1
104676 #define tkOTHER   2
104677 #ifndef SQLITE_OMIT_TRIGGER
104678 #define tkEXPLAIN 3
104679 #define tkCREATE  4
104680 #define tkTEMP    5
104681 #define tkTRIGGER 6
104682 #define tkEND     7
104683 #endif
104684
104685 /*
104686 ** Return TRUE if the given SQL string ends in a semicolon.
104687 **
104688 ** Special handling is require for CREATE TRIGGER statements.
104689 ** Whenever the CREATE TRIGGER keywords are seen, the statement
104690 ** must end with ";END;".
104691 **
104692 ** This implementation uses a state machine with 8 states:
104693 **
104694 **   (0) INVALID   We have not yet seen a non-whitespace character.
104695 **
104696 **   (1) START     At the beginning or end of an SQL statement.  This routine
104697 **                 returns 1 if it ends in the START state and 0 if it ends
104698 **                 in any other state.
104699 **
104700 **   (2) NORMAL    We are in the middle of statement which ends with a single
104701 **                 semicolon.
104702 **
104703 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
104704 **                 a statement.
104705 **
104706 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
104707 **                 statement, possibly preceeded by EXPLAIN and/or followed by
104708 **                 TEMP or TEMPORARY
104709 **
104710 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
104711 **                 ended by a semicolon, the keyword END, and another semicolon.
104712 **
104713 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
104714 **                 the end of a trigger definition.
104715 **
104716 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
104717 **                 of a trigger difinition.
104718 **
104719 ** Transitions between states above are determined by tokens extracted
104720 ** from the input.  The following tokens are significant:
104721 **
104722 **   (0) tkSEMI      A semicolon.
104723 **   (1) tkWS        Whitespace.
104724 **   (2) tkOTHER     Any other SQL token.
104725 **   (3) tkEXPLAIN   The "explain" keyword.
104726 **   (4) tkCREATE    The "create" keyword.
104727 **   (5) tkTEMP      The "temp" or "temporary" keyword.
104728 **   (6) tkTRIGGER   The "trigger" keyword.
104729 **   (7) tkEND       The "end" keyword.
104730 **
104731 ** Whitespace never causes a state transition and is always ignored.
104732 ** This means that a SQL string of all whitespace is invalid.
104733 **
104734 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
104735 ** to recognize the end of a trigger can be omitted.  All we have to do
104736 ** is look for a semicolon that is not part of an string or comment.
104737 */
104738 SQLITE_API int sqlite3_complete(const char *zSql){
104739   u8 state = 0;   /* Current state, using numbers defined in header comment */
104740   u8 token;       /* Value of the next token */
104741
104742 #ifndef SQLITE_OMIT_TRIGGER
104743   /* A complex statement machine used to detect the end of a CREATE TRIGGER
104744   ** statement.  This is the normal case.
104745   */
104746   static const u8 trans[8][8] = {
104747                      /* Token:                                                */
104748      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
104749      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
104750      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
104751      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
104752      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
104753      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
104754      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
104755      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
104756      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
104757   };
104758 #else
104759   /* If triggers are not supported by this compile then the statement machine
104760   ** used to detect the end of a statement is much simplier
104761   */
104762   static const u8 trans[3][3] = {
104763                      /* Token:           */
104764      /* State:       **  SEMI  WS  OTHER */
104765      /* 0 INVALID: */ {    1,  0,     2, },
104766      /* 1   START: */ {    1,  1,     2, },
104767      /* 2  NORMAL: */ {    1,  2,     2, },
104768   };
104769 #endif /* SQLITE_OMIT_TRIGGER */
104770
104771   while( *zSql ){
104772     switch( *zSql ){
104773       case ';': {  /* A semicolon */
104774         token = tkSEMI;
104775         break;
104776       }
104777       case ' ':
104778       case '\r':
104779       case '\t':
104780       case '\n':
104781       case '\f': {  /* White space is ignored */
104782         token = tkWS;
104783         break;
104784       }
104785       case '/': {   /* C-style comments */
104786         if( zSql[1]!='*' ){
104787           token = tkOTHER;
104788           break;
104789         }
104790         zSql += 2;
104791         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
104792         if( zSql[0]==0 ) return 0;
104793         zSql++;
104794         token = tkWS;
104795         break;
104796       }
104797       case '-': {   /* SQL-style comments from "--" to end of line */
104798         if( zSql[1]!='-' ){
104799           token = tkOTHER;
104800           break;
104801         }
104802         while( *zSql && *zSql!='\n' ){ zSql++; }
104803         if( *zSql==0 ) return state==1;
104804         token = tkWS;
104805         break;
104806       }
104807       case '[': {   /* Microsoft-style identifiers in [...] */
104808         zSql++;
104809         while( *zSql && *zSql!=']' ){ zSql++; }
104810         if( *zSql==0 ) return 0;
104811         token = tkOTHER;
104812         break;
104813       }
104814       case '`':     /* Grave-accent quoted symbols used by MySQL */
104815       case '"':     /* single- and double-quoted strings */
104816       case '\'': {
104817         int c = *zSql;
104818         zSql++;
104819         while( *zSql && *zSql!=c ){ zSql++; }
104820         if( *zSql==0 ) return 0;
104821         token = tkOTHER;
104822         break;
104823       }
104824       default: {
104825 #ifdef SQLITE_EBCDIC
104826         unsigned char c;
104827 #endif
104828         if( IdChar((u8)*zSql) ){
104829           /* Keywords and unquoted identifiers */
104830           int nId;
104831           for(nId=1; IdChar(zSql[nId]); nId++){}
104832 #ifdef SQLITE_OMIT_TRIGGER
104833           token = tkOTHER;
104834 #else
104835           switch( *zSql ){
104836             case 'c': case 'C': {
104837               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
104838                 token = tkCREATE;
104839               }else{
104840                 token = tkOTHER;
104841               }
104842               break;
104843             }
104844             case 't': case 'T': {
104845               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
104846                 token = tkTRIGGER;
104847               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
104848                 token = tkTEMP;
104849               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
104850                 token = tkTEMP;
104851               }else{
104852                 token = tkOTHER;
104853               }
104854               break;
104855             }
104856             case 'e':  case 'E': {
104857               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
104858                 token = tkEND;
104859               }else
104860 #ifndef SQLITE_OMIT_EXPLAIN
104861               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
104862                 token = tkEXPLAIN;
104863               }else
104864 #endif
104865               {
104866                 token = tkOTHER;
104867               }
104868               break;
104869             }
104870             default: {
104871               token = tkOTHER;
104872               break;
104873             }
104874           }
104875 #endif /* SQLITE_OMIT_TRIGGER */
104876           zSql += nId-1;
104877         }else{
104878           /* Operators and special symbols */
104879           token = tkOTHER;
104880         }
104881         break;
104882       }
104883     }
104884     state = trans[state][token];
104885     zSql++;
104886   }
104887   return state==1;
104888 }
104889
104890 #ifndef SQLITE_OMIT_UTF16
104891 /*
104892 ** This routine is the same as the sqlite3_complete() routine described
104893 ** above, except that the parameter is required to be UTF-16 encoded, not
104894 ** UTF-8.
104895 */
104896 SQLITE_API int sqlite3_complete16(const void *zSql){
104897   sqlite3_value *pVal;
104898   char const *zSql8;
104899   int rc = SQLITE_NOMEM;
104900
104901 #ifndef SQLITE_OMIT_AUTOINIT
104902   rc = sqlite3_initialize();
104903   if( rc ) return rc;
104904 #endif
104905   pVal = sqlite3ValueNew(0);
104906   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
104907   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
104908   if( zSql8 ){
104909     rc = sqlite3_complete(zSql8);
104910   }else{
104911     rc = SQLITE_NOMEM;
104912   }
104913   sqlite3ValueFree(pVal);
104914   return sqlite3ApiExit(0, rc);
104915 }
104916 #endif /* SQLITE_OMIT_UTF16 */
104917 #endif /* SQLITE_OMIT_COMPLETE */
104918
104919 /************** End of complete.c ********************************************/
104920 /************** Begin file main.c ********************************************/
104921 /*
104922 ** 2001 September 15
104923 **
104924 ** The author disclaims copyright to this source code.  In place of
104925 ** a legal notice, here is a blessing:
104926 **
104927 **    May you do good and not evil.
104928 **    May you find forgiveness for yourself and forgive others.
104929 **    May you share freely, never taking more than you give.
104930 **
104931 *************************************************************************
104932 ** Main file for the SQLite library.  The routines in this file
104933 ** implement the programmer interface to the library.  Routines in
104934 ** other files are for internal use by SQLite and should not be
104935 ** accessed by users of the library.
104936 */
104937
104938 #ifdef SQLITE_ENABLE_FTS3
104939 /************** Include fts3.h in the middle of main.c ***********************/
104940 /************** Begin file fts3.h ********************************************/
104941 /*
104942 ** 2006 Oct 10
104943 **
104944 ** The author disclaims copyright to this source code.  In place of
104945 ** a legal notice, here is a blessing:
104946 **
104947 **    May you do good and not evil.
104948 **    May you find forgiveness for yourself and forgive others.
104949 **    May you share freely, never taking more than you give.
104950 **
104951 ******************************************************************************
104952 **
104953 ** This header file is used by programs that want to link against the
104954 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
104955 */
104956
104957 #if 0
104958 extern "C" {
104959 #endif  /* __cplusplus */
104960
104961 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
104962
104963 #if 0
104964 }  /* extern "C" */
104965 #endif  /* __cplusplus */
104966
104967 /************** End of fts3.h ************************************************/
104968 /************** Continuing where we left off in main.c ***********************/
104969 #endif
104970 #ifdef SQLITE_ENABLE_RTREE
104971 /************** Include rtree.h in the middle of main.c **********************/
104972 /************** Begin file rtree.h *******************************************/
104973 /*
104974 ** 2008 May 26
104975 **
104976 ** The author disclaims copyright to this source code.  In place of
104977 ** a legal notice, here is a blessing:
104978 **
104979 **    May you do good and not evil.
104980 **    May you find forgiveness for yourself and forgive others.
104981 **    May you share freely, never taking more than you give.
104982 **
104983 ******************************************************************************
104984 **
104985 ** This header file is used by programs that want to link against the
104986 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
104987 */
104988
104989 #if 0
104990 extern "C" {
104991 #endif  /* __cplusplus */
104992
104993 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
104994
104995 #if 0
104996 }  /* extern "C" */
104997 #endif  /* __cplusplus */
104998
104999 /************** End of rtree.h ***********************************************/
105000 /************** Continuing where we left off in main.c ***********************/
105001 #endif
105002 #ifdef SQLITE_ENABLE_ICU
105003 /************** Include sqliteicu.h in the middle of main.c ******************/
105004 /************** Begin file sqliteicu.h ***************************************/
105005 /*
105006 ** 2008 May 26
105007 **
105008 ** The author disclaims copyright to this source code.  In place of
105009 ** a legal notice, here is a blessing:
105010 **
105011 **    May you do good and not evil.
105012 **    May you find forgiveness for yourself and forgive others.
105013 **    May you share freely, never taking more than you give.
105014 **
105015 ******************************************************************************
105016 **
105017 ** This header file is used by programs that want to link against the
105018 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
105019 */
105020
105021 #if 0
105022 extern "C" {
105023 #endif  /* __cplusplus */
105024
105025 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
105026
105027 #if 0
105028 }  /* extern "C" */
105029 #endif  /* __cplusplus */
105030
105031
105032 /************** End of sqliteicu.h *******************************************/
105033 /************** Continuing where we left off in main.c ***********************/
105034 #endif
105035
105036 #ifndef SQLITE_AMALGAMATION
105037 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
105038 ** contains the text of SQLITE_VERSION macro. 
105039 */
105040 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
105041 #endif
105042
105043 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
105044 ** a pointer to the to the sqlite3_version[] string constant. 
105045 */
105046 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
105047
105048 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
105049 ** pointer to a string constant whose value is the same as the
105050 ** SQLITE_SOURCE_ID C preprocessor macro. 
105051 */
105052 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
105053
105054 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
105055 ** returns an integer equal to SQLITE_VERSION_NUMBER.
105056 */
105057 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
105058
105059 /* IMPLEMENTATION-OF: R-54823-41343 The sqlite3_threadsafe() function returns
105060 ** zero if and only if SQLite was compiled mutexing code omitted due to
105061 ** the SQLITE_THREADSAFE compile-time option being set to 0.
105062 */
105063 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
105064
105065 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
105066 /*
105067 ** If the following function pointer is not NULL and if
105068 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
105069 ** I/O active are written using this function.  These messages
105070 ** are intended for debugging activity only.
105071 */
105072 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
105073 #endif
105074
105075 /*
105076 ** If the following global variable points to a string which is the
105077 ** name of a directory, then that directory will be used to store
105078 ** temporary files.
105079 **
105080 ** See also the "PRAGMA temp_store_directory" SQL command.
105081 */
105082 SQLITE_API char *sqlite3_temp_directory = 0;
105083
105084 /*
105085 ** Initialize SQLite.  
105086 **
105087 ** This routine must be called to initialize the memory allocation,
105088 ** VFS, and mutex subsystems prior to doing any serious work with
105089 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
105090 ** this routine will be called automatically by key routines such as
105091 ** sqlite3_open().  
105092 **
105093 ** This routine is a no-op except on its very first call for the process,
105094 ** or for the first call after a call to sqlite3_shutdown.
105095 **
105096 ** The first thread to call this routine runs the initialization to
105097 ** completion.  If subsequent threads call this routine before the first
105098 ** thread has finished the initialization process, then the subsequent
105099 ** threads must block until the first thread finishes with the initialization.
105100 **
105101 ** The first thread might call this routine recursively.  Recursive
105102 ** calls to this routine should not block, of course.  Otherwise the
105103 ** initialization process would never complete.
105104 **
105105 ** Let X be the first thread to enter this routine.  Let Y be some other
105106 ** thread.  Then while the initial invocation of this routine by X is
105107 ** incomplete, it is required that:
105108 **
105109 **    *  Calls to this routine from Y must block until the outer-most
105110 **       call by X completes.
105111 **
105112 **    *  Recursive calls to this routine from thread X return immediately
105113 **       without blocking.
105114 */
105115 SQLITE_API int sqlite3_initialize(void){
105116   sqlite3_mutex *pMaster;                      /* The main static mutex */
105117   int rc;                                      /* Result code */
105118
105119 #ifdef SQLITE_OMIT_WSD
105120   rc = sqlite3_wsd_init(4096, 24);
105121   if( rc!=SQLITE_OK ){
105122     return rc;
105123   }
105124 #endif
105125
105126   /* If SQLite is already completely initialized, then this call
105127   ** to sqlite3_initialize() should be a no-op.  But the initialization
105128   ** must be complete.  So isInit must not be set until the very end
105129   ** of this routine.
105130   */
105131   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
105132
105133   /* Make sure the mutex subsystem is initialized.  If unable to 
105134   ** initialize the mutex subsystem, return early with the error.
105135   ** If the system is so sick that we are unable to allocate a mutex,
105136   ** there is not much SQLite is going to be able to do.
105137   **
105138   ** The mutex subsystem must take care of serializing its own
105139   ** initialization.
105140   */
105141   rc = sqlite3MutexInit();
105142   if( rc ) return rc;
105143
105144   /* Initialize the malloc() system and the recursive pInitMutex mutex.
105145   ** This operation is protected by the STATIC_MASTER mutex.  Note that
105146   ** MutexAlloc() is called for a static mutex prior to initializing the
105147   ** malloc subsystem - this implies that the allocation of a static
105148   ** mutex must not require support from the malloc subsystem.
105149   */
105150   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
105151   sqlite3_mutex_enter(pMaster);
105152   sqlite3GlobalConfig.isMutexInit = 1;
105153   if( !sqlite3GlobalConfig.isMallocInit ){
105154     rc = sqlite3MallocInit();
105155   }
105156   if( rc==SQLITE_OK ){
105157     sqlite3GlobalConfig.isMallocInit = 1;
105158     if( !sqlite3GlobalConfig.pInitMutex ){
105159       sqlite3GlobalConfig.pInitMutex =
105160            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
105161       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
105162         rc = SQLITE_NOMEM;
105163       }
105164     }
105165   }
105166   if( rc==SQLITE_OK ){
105167     sqlite3GlobalConfig.nRefInitMutex++;
105168   }
105169   sqlite3_mutex_leave(pMaster);
105170
105171   /* If rc is not SQLITE_OK at this point, then either the malloc
105172   ** subsystem could not be initialized or the system failed to allocate
105173   ** the pInitMutex mutex. Return an error in either case.  */
105174   if( rc!=SQLITE_OK ){
105175     return rc;
105176   }
105177
105178   /* Do the rest of the initialization under the recursive mutex so
105179   ** that we will be able to handle recursive calls into
105180   ** sqlite3_initialize().  The recursive calls normally come through
105181   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
105182   ** recursive calls might also be possible.
105183   **
105184   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
105185   ** to the xInit method, so the xInit method need not be threadsafe.
105186   **
105187   ** The following mutex is what serializes access to the appdef pcache xInit
105188   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
105189   ** call to sqlite3PcacheInitialize().
105190   */
105191   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
105192   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
105193     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
105194     sqlite3GlobalConfig.inProgress = 1;
105195     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
105196     sqlite3RegisterGlobalFunctions();
105197     if( sqlite3GlobalConfig.isPCacheInit==0 ){
105198       rc = sqlite3PcacheInitialize();
105199     }
105200     if( rc==SQLITE_OK ){
105201       sqlite3GlobalConfig.isPCacheInit = 1;
105202       rc = sqlite3OsInit();
105203     }
105204     if( rc==SQLITE_OK ){
105205       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
105206           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
105207       sqlite3GlobalConfig.isInit = 1;
105208     }
105209     sqlite3GlobalConfig.inProgress = 0;
105210   }
105211   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
105212
105213   /* Go back under the static mutex and clean up the recursive
105214   ** mutex to prevent a resource leak.
105215   */
105216   sqlite3_mutex_enter(pMaster);
105217   sqlite3GlobalConfig.nRefInitMutex--;
105218   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
105219     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
105220     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
105221     sqlite3GlobalConfig.pInitMutex = 0;
105222   }
105223   sqlite3_mutex_leave(pMaster);
105224
105225   /* The following is just a sanity check to make sure SQLite has
105226   ** been compiled correctly.  It is important to run this code, but
105227   ** we don't want to run it too often and soak up CPU cycles for no
105228   ** reason.  So we run it once during initialization.
105229   */
105230 #ifndef NDEBUG
105231 #ifndef SQLITE_OMIT_FLOATING_POINT
105232   /* This section of code's only "output" is via assert() statements. */
105233   if ( rc==SQLITE_OK ){
105234     u64 x = (((u64)1)<<63)-1;
105235     double y;
105236     assert(sizeof(x)==8);
105237     assert(sizeof(x)==sizeof(y));
105238     memcpy(&y, &x, 8);
105239     assert( sqlite3IsNaN(y) );
105240   }
105241 #endif
105242 #endif
105243
105244   return rc;
105245 }
105246
105247 /*
105248 ** Undo the effects of sqlite3_initialize().  Must not be called while
105249 ** there are outstanding database connections or memory allocations or
105250 ** while any part of SQLite is otherwise in use in any thread.  This
105251 ** routine is not threadsafe.  But it is safe to invoke this routine
105252 ** on when SQLite is already shut down.  If SQLite is already shut down
105253 ** when this routine is invoked, then this routine is a harmless no-op.
105254 */
105255 SQLITE_API int sqlite3_shutdown(void){
105256   if( sqlite3GlobalConfig.isInit ){
105257     sqlite3_os_end();
105258     sqlite3_reset_auto_extension();
105259     sqlite3GlobalConfig.isInit = 0;
105260   }
105261   if( sqlite3GlobalConfig.isPCacheInit ){
105262     sqlite3PcacheShutdown();
105263     sqlite3GlobalConfig.isPCacheInit = 0;
105264   }
105265   if( sqlite3GlobalConfig.isMallocInit ){
105266     sqlite3MallocEnd();
105267     sqlite3GlobalConfig.isMallocInit = 0;
105268   }
105269   if( sqlite3GlobalConfig.isMutexInit ){
105270     sqlite3MutexEnd();
105271     sqlite3GlobalConfig.isMutexInit = 0;
105272   }
105273
105274   return SQLITE_OK;
105275 }
105276
105277 /*
105278 ** This API allows applications to modify the global configuration of
105279 ** the SQLite library at run-time.
105280 **
105281 ** This routine should only be called when there are no outstanding
105282 ** database connections or memory allocations.  This routine is not
105283 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
105284 ** behavior.
105285 */
105286 SQLITE_API int sqlite3_config(int op, ...){
105287   va_list ap;
105288   int rc = SQLITE_OK;
105289
105290   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
105291   ** the SQLite library is in use. */
105292   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
105293
105294   va_start(ap, op);
105295   switch( op ){
105296
105297     /* Mutex configuration options are only available in a threadsafe
105298     ** compile. 
105299     */
105300 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
105301     case SQLITE_CONFIG_SINGLETHREAD: {
105302       /* Disable all mutexing */
105303       sqlite3GlobalConfig.bCoreMutex = 0;
105304       sqlite3GlobalConfig.bFullMutex = 0;
105305       break;
105306     }
105307     case SQLITE_CONFIG_MULTITHREAD: {
105308       /* Disable mutexing of database connections */
105309       /* Enable mutexing of core data structures */
105310       sqlite3GlobalConfig.bCoreMutex = 1;
105311       sqlite3GlobalConfig.bFullMutex = 0;
105312       break;
105313     }
105314     case SQLITE_CONFIG_SERIALIZED: {
105315       /* Enable all mutexing */
105316       sqlite3GlobalConfig.bCoreMutex = 1;
105317       sqlite3GlobalConfig.bFullMutex = 1;
105318       break;
105319     }
105320     case SQLITE_CONFIG_MUTEX: {
105321       /* Specify an alternative mutex implementation */
105322       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
105323       break;
105324     }
105325     case SQLITE_CONFIG_GETMUTEX: {
105326       /* Retrieve the current mutex implementation */
105327       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
105328       break;
105329     }
105330 #endif
105331
105332
105333     case SQLITE_CONFIG_MALLOC: {
105334       /* Specify an alternative malloc implementation */
105335       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
105336       break;
105337     }
105338     case SQLITE_CONFIG_GETMALLOC: {
105339       /* Retrieve the current malloc() implementation */
105340       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
105341       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
105342       break;
105343     }
105344     case SQLITE_CONFIG_MEMSTATUS: {
105345       /* Enable or disable the malloc status collection */
105346       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
105347       break;
105348     }
105349     case SQLITE_CONFIG_SCRATCH: {
105350       /* Designate a buffer for scratch memory space */
105351       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
105352       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
105353       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
105354       break;
105355     }
105356     case SQLITE_CONFIG_PAGECACHE: {
105357       /* Designate a buffer for page cache memory space */
105358       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
105359       sqlite3GlobalConfig.szPage = va_arg(ap, int);
105360       sqlite3GlobalConfig.nPage = va_arg(ap, int);
105361       break;
105362     }
105363
105364     case SQLITE_CONFIG_PCACHE: {
105365       /* Specify an alternative page cache implementation */
105366       sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
105367       break;
105368     }
105369
105370     case SQLITE_CONFIG_GETPCACHE: {
105371       if( sqlite3GlobalConfig.pcache.xInit==0 ){
105372         sqlite3PCacheSetDefault();
105373       }
105374       *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
105375       break;
105376     }
105377
105378 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
105379     case SQLITE_CONFIG_HEAP: {
105380       /* Designate a buffer for heap memory space */
105381       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
105382       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
105383       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
105384
105385       if( sqlite3GlobalConfig.pHeap==0 ){
105386         /* If the heap pointer is NULL, then restore the malloc implementation
105387         ** back to NULL pointers too.  This will cause the malloc to go
105388         ** back to its default implementation when sqlite3_initialize() is
105389         ** run.
105390         */
105391         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
105392       }else{
105393         /* The heap pointer is not NULL, then install one of the
105394         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
105395         ** ENABLE_MEMSYS5 is defined, return an error.
105396         */
105397 #ifdef SQLITE_ENABLE_MEMSYS3
105398         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
105399 #endif
105400 #ifdef SQLITE_ENABLE_MEMSYS5
105401         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
105402 #endif
105403       }
105404       break;
105405     }
105406 #endif
105407
105408     case SQLITE_CONFIG_LOOKASIDE: {
105409       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
105410       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
105411       break;
105412     }
105413     
105414     /* Record a pointer to the logger funcction and its first argument.
105415     ** The default is NULL.  Logging is disabled if the function pointer is
105416     ** NULL.
105417     */
105418     case SQLITE_CONFIG_LOG: {
105419       /* MSVC is picky about pulling func ptrs from va lists.
105420       ** http://support.microsoft.com/kb/47961
105421       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
105422       */
105423       typedef void(*LOGFUNC_t)(void*,int,const char*);
105424       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
105425       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
105426       break;
105427     }
105428
105429     default: {
105430       rc = SQLITE_ERROR;
105431       break;
105432     }
105433   }
105434   va_end(ap);
105435   return rc;
105436 }
105437
105438 /*
105439 ** Set up the lookaside buffers for a database connection.
105440 ** Return SQLITE_OK on success.  
105441 ** If lookaside is already active, return SQLITE_BUSY.
105442 **
105443 ** The sz parameter is the number of bytes in each lookaside slot.
105444 ** The cnt parameter is the number of slots.  If pStart is NULL the
105445 ** space for the lookaside memory is obtained from sqlite3_malloc().
105446 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
105447 ** the lookaside memory.
105448 */
105449 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
105450   void *pStart;
105451   if( db->lookaside.nOut ){
105452     return SQLITE_BUSY;
105453   }
105454   /* Free any existing lookaside buffer for this handle before
105455   ** allocating a new one so we don't have to have space for 
105456   ** both at the same time.
105457   */
105458   if( db->lookaside.bMalloced ){
105459     sqlite3_free(db->lookaside.pStart);
105460   }
105461   /* The size of a lookaside slot needs to be larger than a pointer
105462   ** to be useful.
105463   */
105464   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
105465   if( cnt<0 ) cnt = 0;
105466   if( sz==0 || cnt==0 ){
105467     sz = 0;
105468     pStart = 0;
105469   }else if( pBuf==0 ){
105470     sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
105471     sqlite3BeginBenignMalloc();
105472     pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
105473     sqlite3EndBenignMalloc();
105474   }else{
105475     sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
105476     pStart = pBuf;
105477   }
105478   db->lookaside.pStart = pStart;
105479   db->lookaside.pFree = 0;
105480   db->lookaside.sz = (u16)sz;
105481   if( pStart ){
105482     int i;
105483     LookasideSlot *p;
105484     assert( sz > (int)sizeof(LookasideSlot*) );
105485     p = (LookasideSlot*)pStart;
105486     for(i=cnt-1; i>=0; i--){
105487       p->pNext = db->lookaside.pFree;
105488       db->lookaside.pFree = p;
105489       p = (LookasideSlot*)&((u8*)p)[sz];
105490     }
105491     db->lookaside.pEnd = p;
105492     db->lookaside.bEnabled = 1;
105493     db->lookaside.bMalloced = pBuf==0 ?1:0;
105494   }else{
105495     db->lookaside.pEnd = 0;
105496     db->lookaside.bEnabled = 0;
105497     db->lookaside.bMalloced = 0;
105498   }
105499   return SQLITE_OK;
105500 }
105501
105502 /*
105503 ** Return the mutex associated with a database connection.
105504 */
105505 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
105506   return db->mutex;
105507 }
105508
105509 /*
105510 ** Configuration settings for an individual database connection
105511 */
105512 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
105513   va_list ap;
105514   int rc;
105515   va_start(ap, op);
105516   switch( op ){
105517     case SQLITE_DBCONFIG_LOOKASIDE: {
105518       void *pBuf = va_arg(ap, void*); /* IMP: R-21112-12275 */
105519       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
105520       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
105521       rc = setupLookaside(db, pBuf, sz, cnt);
105522       break;
105523     }
105524     default: {
105525       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
105526       break;
105527     }
105528   }
105529   va_end(ap);
105530   return rc;
105531 }
105532
105533
105534 /*
105535 ** Return true if the buffer z[0..n-1] contains all spaces.
105536 */
105537 static int allSpaces(const char *z, int n){
105538   while( n>0 && z[n-1]==' ' ){ n--; }
105539   return n==0;
105540 }
105541
105542 /*
105543 ** This is the default collating function named "BINARY" which is always
105544 ** available.
105545 **
105546 ** If the padFlag argument is not NULL then space padding at the end
105547 ** of strings is ignored.  This implements the RTRIM collation.
105548 */
105549 static int binCollFunc(
105550   void *padFlag,
105551   int nKey1, const void *pKey1,
105552   int nKey2, const void *pKey2
105553 ){
105554   int rc, n;
105555   n = nKey1<nKey2 ? nKey1 : nKey2;
105556   rc = memcmp(pKey1, pKey2, n);
105557   if( rc==0 ){
105558     if( padFlag
105559      && allSpaces(((char*)pKey1)+n, nKey1-n)
105560      && allSpaces(((char*)pKey2)+n, nKey2-n)
105561     ){
105562       /* Leave rc unchanged at 0 */
105563     }else{
105564       rc = nKey1 - nKey2;
105565     }
105566   }
105567   return rc;
105568 }
105569
105570 /*
105571 ** Another built-in collating sequence: NOCASE. 
105572 **
105573 ** This collating sequence is intended to be used for "case independant
105574 ** comparison". SQLite's knowledge of upper and lower case equivalents
105575 ** extends only to the 26 characters used in the English language.
105576 **
105577 ** At the moment there is only a UTF-8 implementation.
105578 */
105579 static int nocaseCollatingFunc(
105580   void *NotUsed,
105581   int nKey1, const void *pKey1,
105582   int nKey2, const void *pKey2
105583 ){
105584   int r = sqlite3StrNICmp(
105585       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
105586   UNUSED_PARAMETER(NotUsed);
105587   if( 0==r ){
105588     r = nKey1-nKey2;
105589   }
105590   return r;
105591 }
105592
105593 /*
105594 ** Return the ROWID of the most recent insert
105595 */
105596 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
105597   return db->lastRowid;
105598 }
105599
105600 /*
105601 ** Return the number of changes in the most recent call to sqlite3_exec().
105602 */
105603 SQLITE_API int sqlite3_changes(sqlite3 *db){
105604   return db->nChange;
105605 }
105606
105607 /*
105608 ** Return the number of changes since the database handle was opened.
105609 */
105610 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
105611   return db->nTotalChange;
105612 }
105613
105614 /*
105615 ** Close all open savepoints. This function only manipulates fields of the
105616 ** database handle object, it does not close any savepoints that may be open
105617 ** at the b-tree/pager level.
105618 */
105619 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
105620   while( db->pSavepoint ){
105621     Savepoint *pTmp = db->pSavepoint;
105622     db->pSavepoint = pTmp->pNext;
105623     sqlite3DbFree(db, pTmp);
105624   }
105625   db->nSavepoint = 0;
105626   db->nStatement = 0;
105627   db->isTransactionSavepoint = 0;
105628 }
105629
105630 /*
105631 ** Invoke the destructor function associated with FuncDef p, if any. Except,
105632 ** if this is not the last copy of the function, do not invoke it. Multiple
105633 ** copies of a single function are created when create_function() is called
105634 ** with SQLITE_ANY as the encoding.
105635 */
105636 static void functionDestroy(sqlite3 *db, FuncDef *p){
105637   FuncDestructor *pDestructor = p->pDestructor;
105638   if( pDestructor ){
105639     pDestructor->nRef--;
105640     if( pDestructor->nRef==0 ){
105641       pDestructor->xDestroy(pDestructor->pUserData);
105642       sqlite3DbFree(db, pDestructor);
105643     }
105644   }
105645 }
105646
105647 /*
105648 ** Close an existing SQLite database
105649 */
105650 SQLITE_API int sqlite3_close(sqlite3 *db){
105651   HashElem *i;                    /* Hash table iterator */
105652   int j;
105653
105654   if( !db ){
105655     return SQLITE_OK;
105656   }
105657   if( !sqlite3SafetyCheckSickOrOk(db) ){
105658     return SQLITE_MISUSE_BKPT;
105659   }
105660   sqlite3_mutex_enter(db->mutex);
105661
105662   sqlite3ResetInternalSchema(db, 0);
105663
105664   /* If a transaction is open, the ResetInternalSchema() call above
105665   ** will not have called the xDisconnect() method on any virtual
105666   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
105667   ** call will do so. We need to do this before the check for active
105668   ** SQL statements below, as the v-table implementation may be storing
105669   ** some prepared statements internally.
105670   */
105671   sqlite3VtabRollback(db);
105672
105673   /* If there are any outstanding VMs, return SQLITE_BUSY. */
105674   if( db->pVdbe ){
105675     sqlite3Error(db, SQLITE_BUSY, 
105676         "unable to close due to unfinalised statements");
105677     sqlite3_mutex_leave(db->mutex);
105678     return SQLITE_BUSY;
105679   }
105680   assert( sqlite3SafetyCheckSickOrOk(db) );
105681
105682   for(j=0; j<db->nDb; j++){
105683     Btree *pBt = db->aDb[j].pBt;
105684     if( pBt && sqlite3BtreeIsInBackup(pBt) ){
105685       sqlite3Error(db, SQLITE_BUSY, 
105686           "unable to close due to unfinished backup operation");
105687       sqlite3_mutex_leave(db->mutex);
105688       return SQLITE_BUSY;
105689     }
105690   }
105691
105692   /* Free any outstanding Savepoint structures. */
105693   sqlite3CloseSavepoints(db);
105694
105695   for(j=0; j<db->nDb; j++){
105696     struct Db *pDb = &db->aDb[j];
105697     if( pDb->pBt ){
105698       sqlite3BtreeClose(pDb->pBt);
105699       pDb->pBt = 0;
105700       if( j!=1 ){
105701         pDb->pSchema = 0;
105702       }
105703     }
105704   }
105705   sqlite3ResetInternalSchema(db, 0);
105706
105707   /* Tell the code in notify.c that the connection no longer holds any
105708   ** locks and does not require any further unlock-notify callbacks.
105709   */
105710   sqlite3ConnectionClosed(db);
105711
105712   assert( db->nDb<=2 );
105713   assert( db->aDb==db->aDbStatic );
105714   for(j=0; j<ArraySize(db->aFunc.a); j++){
105715     FuncDef *pNext, *pHash, *p;
105716     for(p=db->aFunc.a[j]; p; p=pHash){
105717       pHash = p->pHash;
105718       while( p ){
105719         functionDestroy(db, p);
105720         pNext = p->pNext;
105721         sqlite3DbFree(db, p);
105722         p = pNext;
105723       }
105724     }
105725   }
105726   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
105727     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
105728     /* Invoke any destructors registered for collation sequence user data. */
105729     for(j=0; j<3; j++){
105730       if( pColl[j].xDel ){
105731         pColl[j].xDel(pColl[j].pUser);
105732       }
105733     }
105734     sqlite3DbFree(db, pColl);
105735   }
105736   sqlite3HashClear(&db->aCollSeq);
105737 #ifndef SQLITE_OMIT_VIRTUALTABLE
105738   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
105739     Module *pMod = (Module *)sqliteHashData(i);
105740     if( pMod->xDestroy ){
105741       pMod->xDestroy(pMod->pAux);
105742     }
105743     sqlite3DbFree(db, pMod);
105744   }
105745   sqlite3HashClear(&db->aModule);
105746 #endif
105747
105748   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
105749   if( db->pErr ){
105750     sqlite3ValueFree(db->pErr);
105751   }
105752   sqlite3CloseExtensions(db);
105753
105754   db->magic = SQLITE_MAGIC_ERROR;
105755
105756   /* The temp-database schema is allocated differently from the other schema
105757   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
105758   ** So it needs to be freed here. Todo: Why not roll the temp schema into
105759   ** the same sqliteMalloc() as the one that allocates the database 
105760   ** structure?
105761   */
105762   sqlite3DbFree(db, db->aDb[1].pSchema);
105763   sqlite3_mutex_leave(db->mutex);
105764   db->magic = SQLITE_MAGIC_CLOSED;
105765   sqlite3_mutex_free(db->mutex);
105766   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
105767   if( db->lookaside.bMalloced ){
105768     sqlite3_free(db->lookaside.pStart);
105769   }
105770   sqlite3_free(db);
105771   return SQLITE_OK;
105772 }
105773
105774 /*
105775 ** Rollback all database files.
105776 */
105777 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
105778   int i;
105779   int inTrans = 0;
105780   assert( sqlite3_mutex_held(db->mutex) );
105781   sqlite3BeginBenignMalloc();
105782   for(i=0; i<db->nDb; i++){
105783     if( db->aDb[i].pBt ){
105784       if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
105785         inTrans = 1;
105786       }
105787       sqlite3BtreeRollback(db->aDb[i].pBt);
105788       db->aDb[i].inTrans = 0;
105789     }
105790   }
105791   sqlite3VtabRollback(db);
105792   sqlite3EndBenignMalloc();
105793
105794   if( db->flags&SQLITE_InternChanges ){
105795     sqlite3ExpirePreparedStatements(db);
105796     sqlite3ResetInternalSchema(db, 0);
105797   }
105798
105799   /* Any deferred constraint violations have now been resolved. */
105800   db->nDeferredCons = 0;
105801
105802   /* If one has been configured, invoke the rollback-hook callback */
105803   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
105804     db->xRollbackCallback(db->pRollbackArg);
105805   }
105806 }
105807
105808 /*
105809 ** Return a static string that describes the kind of error specified in the
105810 ** argument.
105811 */
105812 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
105813   static const char* const aMsg[] = {
105814     /* SQLITE_OK          */ "not an error",
105815     /* SQLITE_ERROR       */ "SQL logic error or missing database",
105816     /* SQLITE_INTERNAL    */ 0,
105817     /* SQLITE_PERM        */ "access permission denied",
105818     /* SQLITE_ABORT       */ "callback requested query abort",
105819     /* SQLITE_BUSY        */ "database is locked",
105820     /* SQLITE_LOCKED      */ "database table is locked",
105821     /* SQLITE_NOMEM       */ "out of memory",
105822     /* SQLITE_READONLY    */ "attempt to write a readonly database",
105823     /* SQLITE_INTERRUPT   */ "interrupted",
105824     /* SQLITE_IOERR       */ "disk I/O error",
105825     /* SQLITE_CORRUPT     */ "database disk image is malformed",
105826     /* SQLITE_NOTFOUND    */ "unknown operation",
105827     /* SQLITE_FULL        */ "database or disk is full",
105828     /* SQLITE_CANTOPEN    */ "unable to open database file",
105829     /* SQLITE_PROTOCOL    */ "locking protocol",
105830     /* SQLITE_EMPTY       */ "table contains no data",
105831     /* SQLITE_SCHEMA      */ "database schema has changed",
105832     /* SQLITE_TOOBIG      */ "string or blob too big",
105833     /* SQLITE_CONSTRAINT  */ "constraint failed",
105834     /* SQLITE_MISMATCH    */ "datatype mismatch",
105835     /* SQLITE_MISUSE      */ "library routine called out of sequence",
105836     /* SQLITE_NOLFS       */ "large file support is disabled",
105837     /* SQLITE_AUTH        */ "authorization denied",
105838     /* SQLITE_FORMAT      */ "auxiliary database format error",
105839     /* SQLITE_RANGE       */ "bind or column index out of range",
105840     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
105841   };
105842   rc &= 0xff;
105843   if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
105844     return aMsg[rc];
105845   }else{
105846     return "unknown error";
105847   }
105848 }
105849
105850 /*
105851 ** This routine implements a busy callback that sleeps and tries
105852 ** again until a timeout value is reached.  The timeout value is
105853 ** an integer number of milliseconds passed in as the first
105854 ** argument.
105855 */
105856 static int sqliteDefaultBusyCallback(
105857  void *ptr,               /* Database connection */
105858  int count                /* Number of times table has been busy */
105859 ){
105860 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
105861   static const u8 delays[] =
105862      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
105863   static const u8 totals[] =
105864      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
105865 # define NDELAY (sizeof(delays)/sizeof(delays[0]))
105866   sqlite3 *db = (sqlite3 *)ptr;
105867   int timeout = db->busyTimeout;
105868   int delay, prior;
105869
105870   assert( count>=0 );
105871   if( count < NDELAY ){
105872     delay = delays[count];
105873     prior = totals[count];
105874   }else{
105875     delay = delays[NDELAY-1];
105876     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
105877   }
105878   if( prior + delay > timeout ){
105879     delay = timeout - prior;
105880     if( delay<=0 ) return 0;
105881   }
105882   sqlite3OsSleep(db->pVfs, delay*1000);
105883   return 1;
105884 #else
105885   sqlite3 *db = (sqlite3 *)ptr;
105886   int timeout = ((sqlite3 *)ptr)->busyTimeout;
105887   if( (count+1)*1000 > timeout ){
105888     return 0;
105889   }
105890   sqlite3OsSleep(db->pVfs, 1000000);
105891   return 1;
105892 #endif
105893 }
105894
105895 /*
105896 ** Invoke the given busy handler.
105897 **
105898 ** This routine is called when an operation failed with a lock.
105899 ** If this routine returns non-zero, the lock is retried.  If it
105900 ** returns 0, the operation aborts with an SQLITE_BUSY error.
105901 */
105902 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
105903   int rc;
105904   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
105905   rc = p->xFunc(p->pArg, p->nBusy);
105906   if( rc==0 ){
105907     p->nBusy = -1;
105908   }else{
105909     p->nBusy++;
105910   }
105911   return rc; 
105912 }
105913
105914 /*
105915 ** This routine sets the busy callback for an Sqlite database to the
105916 ** given callback function with the given argument.
105917 */
105918 SQLITE_API int sqlite3_busy_handler(
105919   sqlite3 *db,
105920   int (*xBusy)(void*,int),
105921   void *pArg
105922 ){
105923   sqlite3_mutex_enter(db->mutex);
105924   db->busyHandler.xFunc = xBusy;
105925   db->busyHandler.pArg = pArg;
105926   db->busyHandler.nBusy = 0;
105927   sqlite3_mutex_leave(db->mutex);
105928   return SQLITE_OK;
105929 }
105930
105931 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
105932 /*
105933 ** This routine sets the progress callback for an Sqlite database to the
105934 ** given callback function with the given argument. The progress callback will
105935 ** be invoked every nOps opcodes.
105936 */
105937 SQLITE_API void sqlite3_progress_handler(
105938   sqlite3 *db, 
105939   int nOps,
105940   int (*xProgress)(void*), 
105941   void *pArg
105942 ){
105943   sqlite3_mutex_enter(db->mutex);
105944   if( nOps>0 ){
105945     db->xProgress = xProgress;
105946     db->nProgressOps = nOps;
105947     db->pProgressArg = pArg;
105948   }else{
105949     db->xProgress = 0;
105950     db->nProgressOps = 0;
105951     db->pProgressArg = 0;
105952   }
105953   sqlite3_mutex_leave(db->mutex);
105954 }
105955 #endif
105956
105957
105958 /*
105959 ** This routine installs a default busy handler that waits for the
105960 ** specified number of milliseconds before returning 0.
105961 */
105962 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
105963   if( ms>0 ){
105964     db->busyTimeout = ms;
105965     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
105966   }else{
105967     sqlite3_busy_handler(db, 0, 0);
105968   }
105969   return SQLITE_OK;
105970 }
105971
105972 /*
105973 ** Cause any pending operation to stop at its earliest opportunity.
105974 */
105975 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
105976   db->u1.isInterrupted = 1;
105977 }
105978
105979
105980 /*
105981 ** This function is exactly the same as sqlite3_create_function(), except
105982 ** that it is designed to be called by internal code. The difference is
105983 ** that if a malloc() fails in sqlite3_create_function(), an error code
105984 ** is returned and the mallocFailed flag cleared. 
105985 */
105986 SQLITE_PRIVATE int sqlite3CreateFunc(
105987   sqlite3 *db,
105988   const char *zFunctionName,
105989   int nArg,
105990   int enc,
105991   void *pUserData,
105992   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
105993   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
105994   void (*xFinal)(sqlite3_context*),
105995   FuncDestructor *pDestructor
105996 ){
105997   FuncDef *p;
105998   int nName;
105999
106000   assert( sqlite3_mutex_held(db->mutex) );
106001   if( zFunctionName==0 ||
106002       (xFunc && (xFinal || xStep)) || 
106003       (!xFunc && (xFinal && !xStep)) ||
106004       (!xFunc && (!xFinal && xStep)) ||
106005       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
106006       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
106007     return SQLITE_MISUSE_BKPT;
106008   }
106009   
106010 #ifndef SQLITE_OMIT_UTF16
106011   /* If SQLITE_UTF16 is specified as the encoding type, transform this
106012   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
106013   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
106014   **
106015   ** If SQLITE_ANY is specified, add three versions of the function
106016   ** to the hash table.
106017   */
106018   if( enc==SQLITE_UTF16 ){
106019     enc = SQLITE_UTF16NATIVE;
106020   }else if( enc==SQLITE_ANY ){
106021     int rc;
106022     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
106023          pUserData, xFunc, xStep, xFinal, pDestructor);
106024     if( rc==SQLITE_OK ){
106025       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
106026           pUserData, xFunc, xStep, xFinal, pDestructor);
106027     }
106028     if( rc!=SQLITE_OK ){
106029       return rc;
106030     }
106031     enc = SQLITE_UTF16BE;
106032   }
106033 #else
106034   enc = SQLITE_UTF8;
106035 #endif
106036   
106037   /* Check if an existing function is being overridden or deleted. If so,
106038   ** and there are active VMs, then return SQLITE_BUSY. If a function
106039   ** is being overridden/deleted but there are no active VMs, allow the
106040   ** operation to continue but invalidate all precompiled statements.
106041   */
106042   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
106043   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
106044     if( db->activeVdbeCnt ){
106045       sqlite3Error(db, SQLITE_BUSY, 
106046         "unable to delete/modify user-function due to active statements");
106047       assert( !db->mallocFailed );
106048       return SQLITE_BUSY;
106049     }else{
106050       sqlite3ExpirePreparedStatements(db);
106051     }
106052   }
106053
106054   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
106055   assert(p || db->mallocFailed);
106056   if( !p ){
106057     return SQLITE_NOMEM;
106058   }
106059
106060   /* If an older version of the function with a configured destructor is
106061   ** being replaced invoke the destructor function here. */
106062   functionDestroy(db, p);
106063
106064   if( pDestructor ){
106065     pDestructor->nRef++;
106066   }
106067   p->pDestructor = pDestructor;
106068   p->flags = 0;
106069   p->xFunc = xFunc;
106070   p->xStep = xStep;
106071   p->xFinalize = xFinal;
106072   p->pUserData = pUserData;
106073   p->nArg = (u16)nArg;
106074   return SQLITE_OK;
106075 }
106076
106077 /*
106078 ** Create new user functions.
106079 */
106080 SQLITE_API int sqlite3_create_function(
106081   sqlite3 *db,
106082   const char *zFunc,
106083   int nArg,
106084   int enc,
106085   void *p,
106086   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
106087   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
106088   void (*xFinal)(sqlite3_context*)
106089 ){
106090   return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
106091                                     xFinal, 0);
106092 }
106093
106094 SQLITE_API int sqlite3_create_function_v2(
106095   sqlite3 *db,
106096   const char *zFunc,
106097   int nArg,
106098   int enc,
106099   void *p,
106100   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
106101   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
106102   void (*xFinal)(sqlite3_context*),
106103   void (*xDestroy)(void *)
106104 ){
106105   int rc = SQLITE_ERROR;
106106   FuncDestructor *pArg = 0;
106107   sqlite3_mutex_enter(db->mutex);
106108   if( xDestroy ){
106109     pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
106110     if( !pArg ){
106111       xDestroy(p);
106112       goto out;
106113     }
106114     pArg->xDestroy = xDestroy;
106115     pArg->pUserData = p;
106116   }
106117   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
106118   if( pArg && pArg->nRef==0 ){
106119     assert( rc!=SQLITE_OK );
106120     xDestroy(p);
106121     sqlite3DbFree(db, pArg);
106122   }
106123
106124  out:
106125   rc = sqlite3ApiExit(db, rc);
106126   sqlite3_mutex_leave(db->mutex);
106127   return rc;
106128 }
106129
106130 #ifndef SQLITE_OMIT_UTF16
106131 SQLITE_API int sqlite3_create_function16(
106132   sqlite3 *db,
106133   const void *zFunctionName,
106134   int nArg,
106135   int eTextRep,
106136   void *p,
106137   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
106138   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
106139   void (*xFinal)(sqlite3_context*)
106140 ){
106141   int rc;
106142   char *zFunc8;
106143   sqlite3_mutex_enter(db->mutex);
106144   assert( !db->mallocFailed );
106145   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
106146   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
106147   sqlite3DbFree(db, zFunc8);
106148   rc = sqlite3ApiExit(db, rc);
106149   sqlite3_mutex_leave(db->mutex);
106150   return rc;
106151 }
106152 #endif
106153
106154
106155 /*
106156 ** Declare that a function has been overloaded by a virtual table.
106157 **
106158 ** If the function already exists as a regular global function, then
106159 ** this routine is a no-op.  If the function does not exist, then create
106160 ** a new one that always throws a run-time error.  
106161 **
106162 ** When virtual tables intend to provide an overloaded function, they
106163 ** should call this routine to make sure the global function exists.
106164 ** A global function must exist in order for name resolution to work
106165 ** properly.
106166 */
106167 SQLITE_API int sqlite3_overload_function(
106168   sqlite3 *db,
106169   const char *zName,
106170   int nArg
106171 ){
106172   int nName = sqlite3Strlen30(zName);
106173   int rc;
106174   sqlite3_mutex_enter(db->mutex);
106175   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
106176     sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
106177                       0, sqlite3InvalidFunction, 0, 0, 0);
106178   }
106179   rc = sqlite3ApiExit(db, SQLITE_OK);
106180   sqlite3_mutex_leave(db->mutex);
106181   return rc;
106182 }
106183
106184 #ifndef SQLITE_OMIT_TRACE
106185 /*
106186 ** Register a trace function.  The pArg from the previously registered trace
106187 ** is returned.  
106188 **
106189 ** A NULL trace function means that no tracing is executes.  A non-NULL
106190 ** trace is a pointer to a function that is invoked at the start of each
106191 ** SQL statement.
106192 */
106193 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
106194   void *pOld;
106195   sqlite3_mutex_enter(db->mutex);
106196   pOld = db->pTraceArg;
106197   db->xTrace = xTrace;
106198   db->pTraceArg = pArg;
106199   sqlite3_mutex_leave(db->mutex);
106200   return pOld;
106201 }
106202 /*
106203 ** Register a profile function.  The pArg from the previously registered 
106204 ** profile function is returned.  
106205 **
106206 ** A NULL profile function means that no profiling is executes.  A non-NULL
106207 ** profile is a pointer to a function that is invoked at the conclusion of
106208 ** each SQL statement that is run.
106209 */
106210 SQLITE_API void *sqlite3_profile(
106211   sqlite3 *db,
106212   void (*xProfile)(void*,const char*,sqlite_uint64),
106213   void *pArg
106214 ){
106215   void *pOld;
106216   sqlite3_mutex_enter(db->mutex);
106217   pOld = db->pProfileArg;
106218   db->xProfile = xProfile;
106219   db->pProfileArg = pArg;
106220   sqlite3_mutex_leave(db->mutex);
106221   return pOld;
106222 }
106223 #endif /* SQLITE_OMIT_TRACE */
106224
106225 /*** EXPERIMENTAL ***
106226 **
106227 ** Register a function to be invoked when a transaction comments.
106228 ** If the invoked function returns non-zero, then the commit becomes a
106229 ** rollback.
106230 */
106231 SQLITE_API void *sqlite3_commit_hook(
106232   sqlite3 *db,              /* Attach the hook to this database */
106233   int (*xCallback)(void*),  /* Function to invoke on each commit */
106234   void *pArg                /* Argument to the function */
106235 ){
106236   void *pOld;
106237   sqlite3_mutex_enter(db->mutex);
106238   pOld = db->pCommitArg;
106239   db->xCommitCallback = xCallback;
106240   db->pCommitArg = pArg;
106241   sqlite3_mutex_leave(db->mutex);
106242   return pOld;
106243 }
106244
106245 /*
106246 ** Register a callback to be invoked each time a row is updated,
106247 ** inserted or deleted using this database connection.
106248 */
106249 SQLITE_API void *sqlite3_update_hook(
106250   sqlite3 *db,              /* Attach the hook to this database */
106251   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
106252   void *pArg                /* Argument to the function */
106253 ){
106254   void *pRet;
106255   sqlite3_mutex_enter(db->mutex);
106256   pRet = db->pUpdateArg;
106257   db->xUpdateCallback = xCallback;
106258   db->pUpdateArg = pArg;
106259   sqlite3_mutex_leave(db->mutex);
106260   return pRet;
106261 }
106262
106263 /*
106264 ** Register a callback to be invoked each time a transaction is rolled
106265 ** back by this database connection.
106266 */
106267 SQLITE_API void *sqlite3_rollback_hook(
106268   sqlite3 *db,              /* Attach the hook to this database */
106269   void (*xCallback)(void*), /* Callback function */
106270   void *pArg                /* Argument to the function */
106271 ){
106272   void *pRet;
106273   sqlite3_mutex_enter(db->mutex);
106274   pRet = db->pRollbackArg;
106275   db->xRollbackCallback = xCallback;
106276   db->pRollbackArg = pArg;
106277   sqlite3_mutex_leave(db->mutex);
106278   return pRet;
106279 }
106280
106281 #ifndef SQLITE_OMIT_WAL
106282 /*
106283 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
106284 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
106285 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
106286 ** wal_autocheckpoint()).
106287 */ 
106288 SQLITE_PRIVATE int sqlite3WalDefaultHook(
106289   void *pClientData,     /* Argument */
106290   sqlite3 *db,           /* Connection */
106291   const char *zDb,       /* Database */
106292   int nFrame             /* Size of WAL */
106293 ){
106294   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
106295     sqlite3BeginBenignMalloc();
106296     sqlite3_wal_checkpoint(db, zDb);
106297     sqlite3EndBenignMalloc();
106298   }
106299   return SQLITE_OK;
106300 }
106301 #endif /* SQLITE_OMIT_WAL */
106302
106303 /*
106304 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
106305 ** a database after committing a transaction if there are nFrame or
106306 ** more frames in the log file. Passing zero or a negative value as the
106307 ** nFrame parameter disables automatic checkpoints entirely.
106308 **
106309 ** The callback registered by this function replaces any existing callback
106310 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
106311 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
106312 ** configured by this function.
106313 */
106314 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
106315 #ifdef SQLITE_OMIT_WAL
106316   UNUSED_PARAMETER(db);
106317   UNUSED_PARAMETER(nFrame);
106318 #else
106319   if( nFrame>0 ){
106320     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
106321   }else{
106322     sqlite3_wal_hook(db, 0, 0);
106323   }
106324 #endif
106325   return SQLITE_OK;
106326 }
106327
106328 /*
106329 ** Register a callback to be invoked each time a transaction is written
106330 ** into the write-ahead-log by this database connection.
106331 */
106332 SQLITE_API void *sqlite3_wal_hook(
106333   sqlite3 *db,                    /* Attach the hook to this db handle */
106334   int(*xCallback)(void *, sqlite3*, const char*, int),
106335   void *pArg                      /* First argument passed to xCallback() */
106336 ){
106337 #ifndef SQLITE_OMIT_WAL
106338   void *pRet;
106339   sqlite3_mutex_enter(db->mutex);
106340   pRet = db->pWalArg;
106341   db->xWalCallback = xCallback;
106342   db->pWalArg = pArg;
106343   sqlite3_mutex_leave(db->mutex);
106344   return pRet;
106345 #else
106346   return 0;
106347 #endif
106348 }
106349
106350
106351 /*
106352 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
106353 ** to contains a zero-length string, all attached databases are 
106354 ** checkpointed.
106355 */
106356 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
106357 #ifdef SQLITE_OMIT_WAL
106358   return SQLITE_OK;
106359 #else
106360   int rc;                         /* Return code */
106361   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
106362
106363   sqlite3_mutex_enter(db->mutex);
106364   if( zDb && zDb[0] ){
106365     iDb = sqlite3FindDbName(db, zDb);
106366   }
106367   if( iDb<0 ){
106368     rc = SQLITE_ERROR;
106369     sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
106370   }else{
106371     rc = sqlite3Checkpoint(db, iDb);
106372     sqlite3Error(db, rc, 0);
106373   }
106374   rc = sqlite3ApiExit(db, rc);
106375   sqlite3_mutex_leave(db->mutex);
106376   return rc;
106377 #endif
106378 }
106379
106380 #ifndef SQLITE_OMIT_WAL
106381 /*
106382 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
106383 ** not currently open in WAL mode.
106384 **
106385 ** If a transaction is open on the database being checkpointed, this 
106386 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If 
106387 ** an error occurs while running the checkpoint, an SQLite error code is 
106388 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
106389 **
106390 ** The mutex on database handle db should be held by the caller. The mutex
106391 ** associated with the specific b-tree being checkpointed is taken by
106392 ** this function while the checkpoint is running.
106393 **
106394 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
106395 ** checkpointed. If an error is encountered it is returned immediately -
106396 ** no attempt is made to checkpoint any remaining databases.
106397 */
106398 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb){
106399   int rc = SQLITE_OK;             /* Return code */
106400   int i;                          /* Used to iterate through attached dbs */
106401
106402   assert( sqlite3_mutex_held(db->mutex) );
106403
106404   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
106405     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
106406       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt);
106407     }
106408   }
106409
106410   return rc;
106411 }
106412 #endif /* SQLITE_OMIT_WAL */
106413
106414 /*
106415 ** This function returns true if main-memory should be used instead of
106416 ** a temporary file for transient pager files and statement journals.
106417 ** The value returned depends on the value of db->temp_store (runtime
106418 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
106419 ** following table describes the relationship between these two values
106420 ** and this functions return value.
106421 **
106422 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
106423 **   -----------------     --------------     ------------------------------
106424 **   0                     any                file      (return 0)
106425 **   1                     1                  file      (return 0)
106426 **   1                     2                  memory    (return 1)
106427 **   1                     0                  file      (return 0)
106428 **   2                     1                  file      (return 0)
106429 **   2                     2                  memory    (return 1)
106430 **   2                     0                  memory    (return 1)
106431 **   3                     any                memory    (return 1)
106432 */
106433 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
106434 #if SQLITE_TEMP_STORE==1
106435   return ( db->temp_store==2 );
106436 #endif
106437 #if SQLITE_TEMP_STORE==2
106438   return ( db->temp_store!=1 );
106439 #endif
106440 #if SQLITE_TEMP_STORE==3
106441   return 1;
106442 #endif
106443 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
106444   return 0;
106445 #endif
106446 }
106447
106448 /*
106449 ** Return UTF-8 encoded English language explanation of the most recent
106450 ** error.
106451 */
106452 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
106453   const char *z;
106454   if( !db ){
106455     return sqlite3ErrStr(SQLITE_NOMEM);
106456   }
106457   if( !sqlite3SafetyCheckSickOrOk(db) ){
106458     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
106459   }
106460   sqlite3_mutex_enter(db->mutex);
106461   if( db->mallocFailed ){
106462     z = sqlite3ErrStr(SQLITE_NOMEM);
106463   }else{
106464     z = (char*)sqlite3_value_text(db->pErr);
106465     assert( !db->mallocFailed );
106466     if( z==0 ){
106467       z = sqlite3ErrStr(db->errCode);
106468     }
106469   }
106470   sqlite3_mutex_leave(db->mutex);
106471   return z;
106472 }
106473
106474 #ifndef SQLITE_OMIT_UTF16
106475 /*
106476 ** Return UTF-16 encoded English language explanation of the most recent
106477 ** error.
106478 */
106479 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
106480   static const u16 outOfMem[] = {
106481     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
106482   };
106483   static const u16 misuse[] = {
106484     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', 
106485     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', 
106486     'c', 'a', 'l', 'l', 'e', 'd', ' ', 
106487     'o', 'u', 't', ' ', 
106488     'o', 'f', ' ', 
106489     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
106490   };
106491
106492   const void *z;
106493   if( !db ){
106494     return (void *)outOfMem;
106495   }
106496   if( !sqlite3SafetyCheckSickOrOk(db) ){
106497     return (void *)misuse;
106498   }
106499   sqlite3_mutex_enter(db->mutex);
106500   if( db->mallocFailed ){
106501     z = (void *)outOfMem;
106502   }else{
106503     z = sqlite3_value_text16(db->pErr);
106504     if( z==0 ){
106505       sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
106506            SQLITE_UTF8, SQLITE_STATIC);
106507       z = sqlite3_value_text16(db->pErr);
106508     }
106509     /* A malloc() may have failed within the call to sqlite3_value_text16()
106510     ** above. If this is the case, then the db->mallocFailed flag needs to
106511     ** be cleared before returning. Do this directly, instead of via
106512     ** sqlite3ApiExit(), to avoid setting the database handle error message.
106513     */
106514     db->mallocFailed = 0;
106515   }
106516   sqlite3_mutex_leave(db->mutex);
106517   return z;
106518 }
106519 #endif /* SQLITE_OMIT_UTF16 */
106520
106521 /*
106522 ** Return the most recent error code generated by an SQLite routine. If NULL is
106523 ** passed to this function, we assume a malloc() failed during sqlite3_open().
106524 */
106525 SQLITE_API int sqlite3_errcode(sqlite3 *db){
106526   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
106527     return SQLITE_MISUSE_BKPT;
106528   }
106529   if( !db || db->mallocFailed ){
106530     return SQLITE_NOMEM;
106531   }
106532   return db->errCode & db->errMask;
106533 }
106534 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
106535   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
106536     return SQLITE_MISUSE_BKPT;
106537   }
106538   if( !db || db->mallocFailed ){
106539     return SQLITE_NOMEM;
106540   }
106541   return db->errCode;
106542 }
106543
106544 /*
106545 ** Create a new collating function for database "db".  The name is zName
106546 ** and the encoding is enc.
106547 */
106548 static int createCollation(
106549   sqlite3* db,
106550   const char *zName, 
106551   u8 enc,
106552   u8 collType,
106553   void* pCtx,
106554   int(*xCompare)(void*,int,const void*,int,const void*),
106555   void(*xDel)(void*)
106556 ){
106557   CollSeq *pColl;
106558   int enc2;
106559   int nName = sqlite3Strlen30(zName);
106560   
106561   assert( sqlite3_mutex_held(db->mutex) );
106562
106563   /* If SQLITE_UTF16 is specified as the encoding type, transform this
106564   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
106565   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
106566   */
106567   enc2 = enc;
106568   testcase( enc2==SQLITE_UTF16 );
106569   testcase( enc2==SQLITE_UTF16_ALIGNED );
106570   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
106571     enc2 = SQLITE_UTF16NATIVE;
106572   }
106573   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
106574     return SQLITE_MISUSE_BKPT;
106575   }
106576
106577   /* Check if this call is removing or replacing an existing collation 
106578   ** sequence. If so, and there are active VMs, return busy. If there
106579   ** are no active VMs, invalidate any pre-compiled statements.
106580   */
106581   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
106582   if( pColl && pColl->xCmp ){
106583     if( db->activeVdbeCnt ){
106584       sqlite3Error(db, SQLITE_BUSY, 
106585         "unable to delete/modify collation sequence due to active statements");
106586       return SQLITE_BUSY;
106587     }
106588     sqlite3ExpirePreparedStatements(db);
106589
106590     /* If collation sequence pColl was created directly by a call to
106591     ** sqlite3_create_collation, and not generated by synthCollSeq(),
106592     ** then any copies made by synthCollSeq() need to be invalidated.
106593     ** Also, collation destructor - CollSeq.xDel() - function may need
106594     ** to be called.
106595     */ 
106596     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
106597       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
106598       int j;
106599       for(j=0; j<3; j++){
106600         CollSeq *p = &aColl[j];
106601         if( p->enc==pColl->enc ){
106602           if( p->xDel ){
106603             p->xDel(p->pUser);
106604           }
106605           p->xCmp = 0;
106606         }
106607       }
106608     }
106609   }
106610
106611   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
106612   if( pColl==0 ) return SQLITE_NOMEM;
106613   pColl->xCmp = xCompare;
106614   pColl->pUser = pCtx;
106615   pColl->xDel = xDel;
106616   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
106617   pColl->type = collType;
106618   sqlite3Error(db, SQLITE_OK, 0);
106619   return SQLITE_OK;
106620 }
106621
106622
106623 /*
106624 ** This array defines hard upper bounds on limit values.  The
106625 ** initializer must be kept in sync with the SQLITE_LIMIT_*
106626 ** #defines in sqlite3.h.
106627 */
106628 static const int aHardLimit[] = {
106629   SQLITE_MAX_LENGTH,
106630   SQLITE_MAX_SQL_LENGTH,
106631   SQLITE_MAX_COLUMN,
106632   SQLITE_MAX_EXPR_DEPTH,
106633   SQLITE_MAX_COMPOUND_SELECT,
106634   SQLITE_MAX_VDBE_OP,
106635   SQLITE_MAX_FUNCTION_ARG,
106636   SQLITE_MAX_ATTACHED,
106637   SQLITE_MAX_LIKE_PATTERN_LENGTH,
106638   SQLITE_MAX_VARIABLE_NUMBER,
106639   SQLITE_MAX_TRIGGER_DEPTH,
106640 };
106641
106642 /*
106643 ** Make sure the hard limits are set to reasonable values
106644 */
106645 #if SQLITE_MAX_LENGTH<100
106646 # error SQLITE_MAX_LENGTH must be at least 100
106647 #endif
106648 #if SQLITE_MAX_SQL_LENGTH<100
106649 # error SQLITE_MAX_SQL_LENGTH must be at least 100
106650 #endif
106651 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
106652 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
106653 #endif
106654 #if SQLITE_MAX_COMPOUND_SELECT<2
106655 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
106656 #endif
106657 #if SQLITE_MAX_VDBE_OP<40
106658 # error SQLITE_MAX_VDBE_OP must be at least 40
106659 #endif
106660 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
106661 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
106662 #endif
106663 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30
106664 # error SQLITE_MAX_ATTACHED must be between 0 and 30
106665 #endif
106666 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
106667 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
106668 #endif
106669 #if SQLITE_MAX_COLUMN>32767
106670 # error SQLITE_MAX_COLUMN must not exceed 32767
106671 #endif
106672 #if SQLITE_MAX_TRIGGER_DEPTH<1
106673 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
106674 #endif
106675
106676
106677 /*
106678 ** Change the value of a limit.  Report the old value.
106679 ** If an invalid limit index is supplied, report -1.
106680 ** Make no changes but still report the old value if the
106681 ** new limit is negative.
106682 **
106683 ** A new lower limit does not shrink existing constructs.
106684 ** It merely prevents new constructs that exceed the limit
106685 ** from forming.
106686 */
106687 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
106688   int oldLimit;
106689
106690
106691   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
106692   ** there is a hard upper bound set at compile-time by a C preprocessor
106693   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
106694   ** "_MAX_".)
106695   */
106696   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
106697   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
106698   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
106699   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
106700   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
106701   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
106702   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
106703   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
106704   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
106705                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
106706   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
106707   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
106708   assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
106709
106710
106711   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
106712     return -1;
106713   }
106714   oldLimit = db->aLimit[limitId];
106715   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
106716     if( newLimit>aHardLimit[limitId] ){
106717       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
106718     }
106719     db->aLimit[limitId] = newLimit;
106720   }
106721   return oldLimit;                     /* IMP: R-53341-35419 */
106722 }
106723
106724 /*
106725 ** This routine does the work of opening a database on behalf of
106726 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
106727 ** is UTF-8 encoded.
106728 */
106729 static int openDatabase(
106730   const char *zFilename, /* Database filename UTF-8 encoded */
106731   sqlite3 **ppDb,        /* OUT: Returned database handle */
106732   unsigned flags,        /* Operational flags */
106733   const char *zVfs       /* Name of the VFS to use */
106734 ){
106735   sqlite3 *db;
106736   int rc;
106737   int isThreadsafe;
106738
106739   *ppDb = 0;
106740 #ifndef SQLITE_OMIT_AUTOINIT
106741   rc = sqlite3_initialize();
106742   if( rc ) return rc;
106743 #endif
106744
106745   /* Only allow sensible combinations of bits in the flags argument.  
106746   ** Throw an error if any non-sense combination is used.  If we
106747   ** do not block illegal combinations here, it could trigger
106748   ** assert() statements in deeper layers.  Sensible combinations
106749   ** are:
106750   **
106751   **  1:  SQLITE_OPEN_READONLY
106752   **  2:  SQLITE_OPEN_READWRITE
106753   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
106754   */
106755   assert( SQLITE_OPEN_READONLY  == 0x01 );
106756   assert( SQLITE_OPEN_READWRITE == 0x02 );
106757   assert( SQLITE_OPEN_CREATE    == 0x04 );
106758   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
106759   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
106760   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
106761   if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE;
106762
106763   if( sqlite3GlobalConfig.bCoreMutex==0 ){
106764     isThreadsafe = 0;
106765   }else if( flags & SQLITE_OPEN_NOMUTEX ){
106766     isThreadsafe = 0;
106767   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
106768     isThreadsafe = 1;
106769   }else{
106770     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
106771   }
106772   if( flags & SQLITE_OPEN_PRIVATECACHE ){
106773     flags &= ~SQLITE_OPEN_SHAREDCACHE;
106774   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
106775     flags |= SQLITE_OPEN_SHAREDCACHE;
106776   }
106777
106778   /* Remove harmful bits from the flags parameter
106779   **
106780   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
106781   ** dealt with in the previous code block.  Besides these, the only
106782   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
106783   ** SQLITE_OPEN_READWRITE, and SQLITE_OPEN_CREATE.  Silently mask
106784   ** off all other flags.
106785   */
106786   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
106787                SQLITE_OPEN_EXCLUSIVE |
106788                SQLITE_OPEN_MAIN_DB |
106789                SQLITE_OPEN_TEMP_DB | 
106790                SQLITE_OPEN_TRANSIENT_DB | 
106791                SQLITE_OPEN_MAIN_JOURNAL | 
106792                SQLITE_OPEN_TEMP_JOURNAL | 
106793                SQLITE_OPEN_SUBJOURNAL | 
106794                SQLITE_OPEN_MASTER_JOURNAL |
106795                SQLITE_OPEN_NOMUTEX |
106796                SQLITE_OPEN_FULLMUTEX |
106797                SQLITE_OPEN_WAL
106798              );
106799
106800   /* Allocate the sqlite data structure */
106801   db = sqlite3MallocZero( sizeof(sqlite3) );
106802   if( db==0 ) goto opendb_out;
106803   if( isThreadsafe ){
106804     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
106805     if( db->mutex==0 ){
106806       sqlite3_free(db);
106807       db = 0;
106808       goto opendb_out;
106809     }
106810   }
106811   sqlite3_mutex_enter(db->mutex);
106812   db->errMask = 0xff;
106813   db->nDb = 2;
106814   db->magic = SQLITE_MAGIC_BUSY;
106815   db->aDb = db->aDbStatic;
106816
106817   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
106818   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
106819   db->autoCommit = 1;
106820   db->nextAutovac = -1;
106821   db->nextPagesize = 0;
106822   db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex
106823 #if SQLITE_DEFAULT_FILE_FORMAT<4
106824                  | SQLITE_LegacyFileFmt
106825 #endif
106826 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
106827                  | SQLITE_LoadExtension
106828 #endif
106829 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
106830                  | SQLITE_RecTriggers
106831 #endif
106832 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
106833                  | SQLITE_ForeignKeys
106834 #endif
106835       ;
106836   sqlite3HashInit(&db->aCollSeq);
106837 #ifndef SQLITE_OMIT_VIRTUALTABLE
106838   sqlite3HashInit(&db->aModule);
106839 #endif
106840
106841   db->pVfs = sqlite3_vfs_find(zVfs);
106842   if( !db->pVfs ){
106843     rc = SQLITE_ERROR;
106844     sqlite3Error(db, rc, "no such vfs: %s", zVfs);
106845     goto opendb_out;
106846   }
106847
106848   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
106849   ** and UTF-16, so add a version for each to avoid any unnecessary
106850   ** conversions. The only error that can occur here is a malloc() failure.
106851   */
106852   createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0,
106853                   binCollFunc, 0);
106854   createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0,
106855                   binCollFunc, 0);
106856   createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0,
106857                   binCollFunc, 0);
106858   createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1,
106859                   binCollFunc, 0);
106860   if( db->mallocFailed ){
106861     goto opendb_out;
106862   }
106863   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
106864   assert( db->pDfltColl!=0 );
106865
106866   /* Also add a UTF-8 case-insensitive collation sequence. */
106867   createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
106868                   nocaseCollatingFunc, 0);
106869
106870   /* Open the backend database driver */
106871   db->openFlags = flags;
106872   rc = sqlite3BtreeOpen(zFilename, db, &db->aDb[0].pBt, 0,
106873                         flags | SQLITE_OPEN_MAIN_DB);
106874   if( rc!=SQLITE_OK ){
106875     if( rc==SQLITE_IOERR_NOMEM ){
106876       rc = SQLITE_NOMEM;
106877     }
106878     sqlite3Error(db, rc, 0);
106879     goto opendb_out;
106880   }
106881   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
106882   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
106883
106884
106885   /* The default safety_level for the main database is 'full'; for the temp
106886   ** database it is 'NONE'. This matches the pager layer defaults.  
106887   */
106888   db->aDb[0].zName = "main";
106889   db->aDb[0].safety_level = 3;
106890   db->aDb[1].zName = "temp";
106891   db->aDb[1].safety_level = 1;
106892
106893   db->magic = SQLITE_MAGIC_OPEN;
106894   if( db->mallocFailed ){
106895     goto opendb_out;
106896   }
106897
106898   /* Register all built-in functions, but do not attempt to read the
106899   ** database schema yet. This is delayed until the first time the database
106900   ** is accessed.
106901   */
106902   sqlite3Error(db, SQLITE_OK, 0);
106903   sqlite3RegisterBuiltinFunctions(db);
106904
106905   /* Load automatic extensions - extensions that have been registered
106906   ** using the sqlite3_automatic_extension() API.
106907   */
106908   sqlite3AutoLoadExtensions(db);
106909   rc = sqlite3_errcode(db);
106910   if( rc!=SQLITE_OK ){
106911     goto opendb_out;
106912   }
106913
106914 #ifdef SQLITE_ENABLE_FTS1
106915   if( !db->mallocFailed ){
106916     extern int sqlite3Fts1Init(sqlite3*);
106917     rc = sqlite3Fts1Init(db);
106918   }
106919 #endif
106920
106921 #ifdef SQLITE_ENABLE_FTS2
106922   if( !db->mallocFailed && rc==SQLITE_OK ){
106923     extern int sqlite3Fts2Init(sqlite3*);
106924     rc = sqlite3Fts2Init(db);
106925   }
106926 #endif
106927
106928 #ifdef SQLITE_ENABLE_FTS3
106929   if( !db->mallocFailed && rc==SQLITE_OK ){
106930     rc = sqlite3Fts3Init(db);
106931   }
106932 #endif
106933
106934 #ifdef SQLITE_ENABLE_ICU
106935   if( !db->mallocFailed && rc==SQLITE_OK ){
106936     rc = sqlite3IcuInit(db);
106937   }
106938 #endif
106939
106940 #ifdef SQLITE_ENABLE_RTREE
106941   if( !db->mallocFailed && rc==SQLITE_OK){
106942     rc = sqlite3RtreeInit(db);
106943   }
106944 #endif
106945
106946   sqlite3Error(db, rc, 0);
106947
106948   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
106949   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
106950   ** mode.  Doing nothing at all also makes NORMAL the default.
106951   */
106952 #ifdef SQLITE_DEFAULT_LOCKING_MODE
106953   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
106954   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
106955                           SQLITE_DEFAULT_LOCKING_MODE);
106956 #endif
106957
106958   /* Enable the lookaside-malloc subsystem */
106959   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
106960                         sqlite3GlobalConfig.nLookaside);
106961
106962   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
106963
106964 opendb_out:
106965   if( db ){
106966     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
106967     sqlite3_mutex_leave(db->mutex);
106968   }
106969   rc = sqlite3_errcode(db);
106970   if( rc==SQLITE_NOMEM ){
106971     sqlite3_close(db);
106972     db = 0;
106973   }else if( rc!=SQLITE_OK ){
106974     db->magic = SQLITE_MAGIC_SICK;
106975   }
106976   *ppDb = db;
106977   return sqlite3ApiExit(0, rc);
106978 }
106979
106980 /*
106981 ** Open a new database handle.
106982 */
106983 SQLITE_API int sqlite3_open(
106984   const char *zFilename, 
106985   sqlite3 **ppDb 
106986 ){
106987   return openDatabase(zFilename, ppDb,
106988                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
106989 }
106990 SQLITE_API int sqlite3_open_v2(
106991   const char *filename,   /* Database filename (UTF-8) */
106992   sqlite3 **ppDb,         /* OUT: SQLite db handle */
106993   int flags,              /* Flags */
106994   const char *zVfs        /* Name of VFS module to use */
106995 ){
106996   return openDatabase(filename, ppDb, flags, zVfs);
106997 }
106998
106999 #ifndef SQLITE_OMIT_UTF16
107000 /*
107001 ** Open a new database handle.
107002 */
107003 SQLITE_API int sqlite3_open16(
107004   const void *zFilename, 
107005   sqlite3 **ppDb
107006 ){
107007   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
107008   sqlite3_value *pVal;
107009   int rc;
107010
107011   assert( zFilename );
107012   assert( ppDb );
107013   *ppDb = 0;
107014 #ifndef SQLITE_OMIT_AUTOINIT
107015   rc = sqlite3_initialize();
107016   if( rc ) return rc;
107017 #endif
107018   pVal = sqlite3ValueNew(0);
107019   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
107020   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
107021   if( zFilename8 ){
107022     rc = openDatabase(zFilename8, ppDb,
107023                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
107024     assert( *ppDb || rc==SQLITE_NOMEM );
107025     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
107026       ENC(*ppDb) = SQLITE_UTF16NATIVE;
107027     }
107028   }else{
107029     rc = SQLITE_NOMEM;
107030   }
107031   sqlite3ValueFree(pVal);
107032
107033   return sqlite3ApiExit(0, rc);
107034 }
107035 #endif /* SQLITE_OMIT_UTF16 */
107036
107037 /*
107038 ** Register a new collation sequence with the database handle db.
107039 */
107040 SQLITE_API int sqlite3_create_collation(
107041   sqlite3* db, 
107042   const char *zName, 
107043   int enc, 
107044   void* pCtx,
107045   int(*xCompare)(void*,int,const void*,int,const void*)
107046 ){
107047   int rc;
107048   sqlite3_mutex_enter(db->mutex);
107049   assert( !db->mallocFailed );
107050   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
107051   rc = sqlite3ApiExit(db, rc);
107052   sqlite3_mutex_leave(db->mutex);
107053   return rc;
107054 }
107055
107056 /*
107057 ** Register a new collation sequence with the database handle db.
107058 */
107059 SQLITE_API int sqlite3_create_collation_v2(
107060   sqlite3* db, 
107061   const char *zName, 
107062   int enc, 
107063   void* pCtx,
107064   int(*xCompare)(void*,int,const void*,int,const void*),
107065   void(*xDel)(void*)
107066 ){
107067   int rc;
107068   sqlite3_mutex_enter(db->mutex);
107069   assert( !db->mallocFailed );
107070   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel);
107071   rc = sqlite3ApiExit(db, rc);
107072   sqlite3_mutex_leave(db->mutex);
107073   return rc;
107074 }
107075
107076 #ifndef SQLITE_OMIT_UTF16
107077 /*
107078 ** Register a new collation sequence with the database handle db.
107079 */
107080 SQLITE_API int sqlite3_create_collation16(
107081   sqlite3* db, 
107082   const void *zName,
107083   int enc, 
107084   void* pCtx,
107085   int(*xCompare)(void*,int,const void*,int,const void*)
107086 ){
107087   int rc = SQLITE_OK;
107088   char *zName8;
107089   sqlite3_mutex_enter(db->mutex);
107090   assert( !db->mallocFailed );
107091   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
107092   if( zName8 ){
107093     rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
107094     sqlite3DbFree(db, zName8);
107095   }
107096   rc = sqlite3ApiExit(db, rc);
107097   sqlite3_mutex_leave(db->mutex);
107098   return rc;
107099 }
107100 #endif /* SQLITE_OMIT_UTF16 */
107101
107102 /*
107103 ** Register a collation sequence factory callback with the database handle
107104 ** db. Replace any previously installed collation sequence factory.
107105 */
107106 SQLITE_API int sqlite3_collation_needed(
107107   sqlite3 *db, 
107108   void *pCollNeededArg, 
107109   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
107110 ){
107111   sqlite3_mutex_enter(db->mutex);
107112   db->xCollNeeded = xCollNeeded;
107113   db->xCollNeeded16 = 0;
107114   db->pCollNeededArg = pCollNeededArg;
107115   sqlite3_mutex_leave(db->mutex);
107116   return SQLITE_OK;
107117 }
107118
107119 #ifndef SQLITE_OMIT_UTF16
107120 /*
107121 ** Register a collation sequence factory callback with the database handle
107122 ** db. Replace any previously installed collation sequence factory.
107123 */
107124 SQLITE_API int sqlite3_collation_needed16(
107125   sqlite3 *db, 
107126   void *pCollNeededArg, 
107127   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
107128 ){
107129   sqlite3_mutex_enter(db->mutex);
107130   db->xCollNeeded = 0;
107131   db->xCollNeeded16 = xCollNeeded16;
107132   db->pCollNeededArg = pCollNeededArg;
107133   sqlite3_mutex_leave(db->mutex);
107134   return SQLITE_OK;
107135 }
107136 #endif /* SQLITE_OMIT_UTF16 */
107137
107138 #ifndef SQLITE_OMIT_DEPRECATED
107139 /*
107140 ** This function is now an anachronism. It used to be used to recover from a
107141 ** malloc() failure, but SQLite now does this automatically.
107142 */
107143 SQLITE_API int sqlite3_global_recover(void){
107144   return SQLITE_OK;
107145 }
107146 #endif
107147
107148 /*
107149 ** Test to see whether or not the database connection is in autocommit
107150 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
107151 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
107152 ** by the next COMMIT or ROLLBACK.
107153 **
107154 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
107155 */
107156 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
107157   return db->autoCommit;
107158 }
107159
107160 /*
107161 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
107162 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
107163 ** constants.  They server two purposes:
107164 **
107165 **   1.  Serve as a convenient place to set a breakpoint in a debugger
107166 **       to detect when version error conditions occurs.
107167 **
107168 **   2.  Invoke sqlite3_log() to provide the source code location where
107169 **       a low-level error is first detected.
107170 */
107171 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
107172   testcase( sqlite3GlobalConfig.xLog!=0 );
107173   sqlite3_log(SQLITE_CORRUPT,
107174               "database corruption at line %d of [%.10s]",
107175               lineno, 20+sqlite3_sourceid());
107176   return SQLITE_CORRUPT;
107177 }
107178 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
107179   testcase( sqlite3GlobalConfig.xLog!=0 );
107180   sqlite3_log(SQLITE_MISUSE, 
107181               "misuse at line %d of [%.10s]",
107182               lineno, 20+sqlite3_sourceid());
107183   return SQLITE_MISUSE;
107184 }
107185 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
107186   testcase( sqlite3GlobalConfig.xLog!=0 );
107187   sqlite3_log(SQLITE_CANTOPEN, 
107188               "cannot open file at line %d of [%.10s]",
107189               lineno, 20+sqlite3_sourceid());
107190   return SQLITE_CANTOPEN;
107191 }
107192
107193
107194 #ifndef SQLITE_OMIT_DEPRECATED
107195 /*
107196 ** This is a convenience routine that makes sure that all thread-specific
107197 ** data for this thread has been deallocated.
107198 **
107199 ** SQLite no longer uses thread-specific data so this routine is now a
107200 ** no-op.  It is retained for historical compatibility.
107201 */
107202 SQLITE_API void sqlite3_thread_cleanup(void){
107203 }
107204 #endif
107205
107206 /*
107207 ** Return meta information about a specific column of a database table.
107208 ** See comment in sqlite3.h (sqlite.h.in) for details.
107209 */
107210 #ifdef SQLITE_ENABLE_COLUMN_METADATA
107211 SQLITE_API int sqlite3_table_column_metadata(
107212   sqlite3 *db,                /* Connection handle */
107213   const char *zDbName,        /* Database name or NULL */
107214   const char *zTableName,     /* Table name */
107215   const char *zColumnName,    /* Column name */
107216   char const **pzDataType,    /* OUTPUT: Declared data type */
107217   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
107218   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
107219   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
107220   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
107221 ){
107222   int rc;
107223   char *zErrMsg = 0;
107224   Table *pTab = 0;
107225   Column *pCol = 0;
107226   int iCol;
107227
107228   char const *zDataType = 0;
107229   char const *zCollSeq = 0;
107230   int notnull = 0;
107231   int primarykey = 0;
107232   int autoinc = 0;
107233
107234   /* Ensure the database schema has been loaded */
107235   sqlite3_mutex_enter(db->mutex);
107236   sqlite3BtreeEnterAll(db);
107237   rc = sqlite3Init(db, &zErrMsg);
107238   if( SQLITE_OK!=rc ){
107239     goto error_out;
107240   }
107241
107242   /* Locate the table in question */
107243   pTab = sqlite3FindTable(db, zTableName, zDbName);
107244   if( !pTab || pTab->pSelect ){
107245     pTab = 0;
107246     goto error_out;
107247   }
107248
107249   /* Find the column for which info is requested */
107250   if( sqlite3IsRowid(zColumnName) ){
107251     iCol = pTab->iPKey;
107252     if( iCol>=0 ){
107253       pCol = &pTab->aCol[iCol];
107254     }
107255   }else{
107256     for(iCol=0; iCol<pTab->nCol; iCol++){
107257       pCol = &pTab->aCol[iCol];
107258       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
107259         break;
107260       }
107261     }
107262     if( iCol==pTab->nCol ){
107263       pTab = 0;
107264       goto error_out;
107265     }
107266   }
107267
107268   /* The following block stores the meta information that will be returned
107269   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
107270   ** and autoinc. At this point there are two possibilities:
107271   ** 
107272   **     1. The specified column name was rowid", "oid" or "_rowid_" 
107273   **        and there is no explicitly declared IPK column. 
107274   **
107275   **     2. The table is not a view and the column name identified an 
107276   **        explicitly declared column. Copy meta information from *pCol.
107277   */ 
107278   if( pCol ){
107279     zDataType = pCol->zType;
107280     zCollSeq = pCol->zColl;
107281     notnull = pCol->notNull!=0;
107282     primarykey  = pCol->isPrimKey!=0;
107283     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
107284   }else{
107285     zDataType = "INTEGER";
107286     primarykey = 1;
107287   }
107288   if( !zCollSeq ){
107289     zCollSeq = "BINARY";
107290   }
107291
107292 error_out:
107293   sqlite3BtreeLeaveAll(db);
107294
107295   /* Whether the function call succeeded or failed, set the output parameters
107296   ** to whatever their local counterparts contain. If an error did occur,
107297   ** this has the effect of zeroing all output parameters.
107298   */
107299   if( pzDataType ) *pzDataType = zDataType;
107300   if( pzCollSeq ) *pzCollSeq = zCollSeq;
107301   if( pNotNull ) *pNotNull = notnull;
107302   if( pPrimaryKey ) *pPrimaryKey = primarykey;
107303   if( pAutoinc ) *pAutoinc = autoinc;
107304
107305   if( SQLITE_OK==rc && !pTab ){
107306     sqlite3DbFree(db, zErrMsg);
107307     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
107308         zColumnName);
107309     rc = SQLITE_ERROR;
107310   }
107311   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
107312   sqlite3DbFree(db, zErrMsg);
107313   rc = sqlite3ApiExit(db, rc);
107314   sqlite3_mutex_leave(db->mutex);
107315   return rc;
107316 }
107317 #endif
107318
107319 /*
107320 ** Sleep for a little while.  Return the amount of time slept.
107321 */
107322 SQLITE_API int sqlite3_sleep(int ms){
107323   sqlite3_vfs *pVfs;
107324   int rc;
107325   pVfs = sqlite3_vfs_find(0);
107326   if( pVfs==0 ) return 0;
107327
107328   /* This function works in milliseconds, but the underlying OsSleep() 
107329   ** API uses microseconds. Hence the 1000's.
107330   */
107331   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
107332   return rc;
107333 }
107334
107335 /*
107336 ** Enable or disable the extended result codes.
107337 */
107338 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
107339   sqlite3_mutex_enter(db->mutex);
107340   db->errMask = onoff ? 0xffffffff : 0xff;
107341   sqlite3_mutex_leave(db->mutex);
107342   return SQLITE_OK;
107343 }
107344
107345 /*
107346 ** Invoke the xFileControl method on a particular database.
107347 */
107348 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
107349   int rc = SQLITE_ERROR;
107350   int iDb;
107351   sqlite3_mutex_enter(db->mutex);
107352   if( zDbName==0 ){
107353     iDb = 0;
107354   }else{
107355     for(iDb=0; iDb<db->nDb; iDb++){
107356       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
107357     }
107358   }
107359   if( iDb<db->nDb ){
107360     Btree *pBtree = db->aDb[iDb].pBt;
107361     if( pBtree ){
107362       Pager *pPager;
107363       sqlite3_file *fd;
107364       sqlite3BtreeEnter(pBtree);
107365       pPager = sqlite3BtreePager(pBtree);
107366       assert( pPager!=0 );
107367       fd = sqlite3PagerFile(pPager);
107368       assert( fd!=0 );
107369       if( op==SQLITE_FCNTL_FILE_POINTER ){
107370         *(sqlite3_file**)pArg = fd;
107371         rc = SQLITE_OK;
107372       }else if( fd->pMethods ){
107373         rc = sqlite3OsFileControl(fd, op, pArg);
107374       }else{
107375         rc = SQLITE_NOTFOUND;
107376       }
107377       sqlite3BtreeLeave(pBtree);
107378     }
107379   }
107380   sqlite3_mutex_leave(db->mutex);
107381   return rc;   
107382 }
107383
107384 /*
107385 ** Interface to the testing logic.
107386 */
107387 SQLITE_API int sqlite3_test_control(int op, ...){
107388   int rc = 0;
107389 #ifndef SQLITE_OMIT_BUILTIN_TEST
107390   va_list ap;
107391   va_start(ap, op);
107392   switch( op ){
107393
107394     /*
107395     ** Save the current state of the PRNG.
107396     */
107397     case SQLITE_TESTCTRL_PRNG_SAVE: {
107398       sqlite3PrngSaveState();
107399       break;
107400     }
107401
107402     /*
107403     ** Restore the state of the PRNG to the last state saved using
107404     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
107405     ** this verb acts like PRNG_RESET.
107406     */
107407     case SQLITE_TESTCTRL_PRNG_RESTORE: {
107408       sqlite3PrngRestoreState();
107409       break;
107410     }
107411
107412     /*
107413     ** Reset the PRNG back to its uninitialized state.  The next call
107414     ** to sqlite3_randomness() will reseed the PRNG using a single call
107415     ** to the xRandomness method of the default VFS.
107416     */
107417     case SQLITE_TESTCTRL_PRNG_RESET: {
107418       sqlite3PrngResetState();
107419       break;
107420     }
107421
107422     /*
107423     **  sqlite3_test_control(BITVEC_TEST, size, program)
107424     **
107425     ** Run a test against a Bitvec object of size.  The program argument
107426     ** is an array of integers that defines the test.  Return -1 on a
107427     ** memory allocation error, 0 on success, or non-zero for an error.
107428     ** See the sqlite3BitvecBuiltinTest() for additional information.
107429     */
107430     case SQLITE_TESTCTRL_BITVEC_TEST: {
107431       int sz = va_arg(ap, int);
107432       int *aProg = va_arg(ap, int*);
107433       rc = sqlite3BitvecBuiltinTest(sz, aProg);
107434       break;
107435     }
107436
107437     /*
107438     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
107439     **
107440     ** Register hooks to call to indicate which malloc() failures 
107441     ** are benign.
107442     */
107443     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
107444       typedef void (*void_function)(void);
107445       void_function xBenignBegin;
107446       void_function xBenignEnd;
107447       xBenignBegin = va_arg(ap, void_function);
107448       xBenignEnd = va_arg(ap, void_function);
107449       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
107450       break;
107451     }
107452
107453     /*
107454     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
107455     **
107456     ** Set the PENDING byte to the value in the argument, if X>0.
107457     ** Make no changes if X==0.  Return the value of the pending byte
107458     ** as it existing before this routine was called.
107459     **
107460     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
107461     ** an incompatible database file format.  Changing the PENDING byte
107462     ** while any database connection is open results in undefined and
107463     ** dileterious behavior.
107464     */
107465     case SQLITE_TESTCTRL_PENDING_BYTE: {
107466       rc = PENDING_BYTE;
107467 #ifndef SQLITE_OMIT_WSD
107468       {
107469         unsigned int newVal = va_arg(ap, unsigned int);
107470         if( newVal ) sqlite3PendingByte = newVal;
107471       }
107472 #endif
107473       break;
107474     }
107475
107476     /*
107477     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
107478     **
107479     ** This action provides a run-time test to see whether or not
107480     ** assert() was enabled at compile-time.  If X is true and assert()
107481     ** is enabled, then the return value is true.  If X is true and
107482     ** assert() is disabled, then the return value is zero.  If X is
107483     ** false and assert() is enabled, then the assertion fires and the
107484     ** process aborts.  If X is false and assert() is disabled, then the
107485     ** return value is zero.
107486     */
107487     case SQLITE_TESTCTRL_ASSERT: {
107488       volatile int x = 0;
107489       assert( (x = va_arg(ap,int))!=0 );
107490       rc = x;
107491       break;
107492     }
107493
107494
107495     /*
107496     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
107497     **
107498     ** This action provides a run-time test to see how the ALWAYS and
107499     ** NEVER macros were defined at compile-time.
107500     **
107501     ** The return value is ALWAYS(X).  
107502     **
107503     ** The recommended test is X==2.  If the return value is 2, that means
107504     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
107505     ** default setting.  If the return value is 1, then ALWAYS() is either
107506     ** hard-coded to true or else it asserts if its argument is false.
107507     ** The first behavior (hard-coded to true) is the case if
107508     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
107509     ** behavior (assert if the argument to ALWAYS() is false) is the case if
107510     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
107511     **
107512     ** The run-time test procedure might look something like this:
107513     **
107514     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
107515     **      // ALWAYS() and NEVER() are no-op pass-through macros
107516     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
107517     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
107518     **    }else{
107519     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
107520     **    }
107521     */
107522     case SQLITE_TESTCTRL_ALWAYS: {
107523       int x = va_arg(ap,int);
107524       rc = ALWAYS(x);
107525       break;
107526     }
107527
107528     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
107529     **
107530     ** Set the nReserve size to N for the main database on the database
107531     ** connection db.
107532     */
107533     case SQLITE_TESTCTRL_RESERVE: {
107534       sqlite3 *db = va_arg(ap, sqlite3*);
107535       int x = va_arg(ap,int);
107536       sqlite3_mutex_enter(db->mutex);
107537       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
107538       sqlite3_mutex_leave(db->mutex);
107539       break;
107540     }
107541
107542     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
107543     **
107544     ** Enable or disable various optimizations for testing purposes.  The 
107545     ** argument N is a bitmask of optimizations to be disabled.  For normal
107546     ** operation N should be 0.  The idea is that a test program (like the
107547     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
107548     ** with various optimizations disabled to verify that the same answer
107549     ** is obtained in every case.
107550     */
107551     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
107552       sqlite3 *db = va_arg(ap, sqlite3*);
107553       int x = va_arg(ap,int);
107554       db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
107555       break;
107556     }
107557
107558 #ifdef SQLITE_N_KEYWORD
107559     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
107560     **
107561     ** If zWord is a keyword recognized by the parser, then return the
107562     ** number of keywords.  Or if zWord is not a keyword, return 0.
107563     ** 
107564     ** This test feature is only available in the amalgamation since
107565     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
107566     ** is built using separate source files.
107567     */
107568     case SQLITE_TESTCTRL_ISKEYWORD: {
107569       const char *zWord = va_arg(ap, const char*);
107570       int n = sqlite3Strlen30(zWord);
107571       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
107572       break;
107573     }
107574 #endif 
107575
107576     /* sqlite3_test_control(SQLITE_TESTCTRL_PGHDRSZ)
107577     **
107578     ** Return the size of a pcache header in bytes.
107579     */
107580     case SQLITE_TESTCTRL_PGHDRSZ: {
107581       rc = sizeof(PgHdr);
107582       break;
107583     }
107584
107585     /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
107586     **
107587     ** Pass pFree into sqlite3ScratchFree(). 
107588     ** If sz>0 then allocate a scratch buffer into pNew.  
107589     */
107590     case SQLITE_TESTCTRL_SCRATCHMALLOC: {
107591       void *pFree, **ppNew;
107592       int sz;
107593       sz = va_arg(ap, int);
107594       ppNew = va_arg(ap, void**);
107595       pFree = va_arg(ap, void*);
107596       if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
107597       sqlite3ScratchFree(pFree);
107598       break;
107599     }
107600
107601   }
107602   va_end(ap);
107603 #endif /* SQLITE_OMIT_BUILTIN_TEST */
107604   return rc;
107605 }
107606
107607 /************** End of main.c ************************************************/
107608 /************** Begin file notify.c ******************************************/
107609 /*
107610 ** 2009 March 3
107611 **
107612 ** The author disclaims copyright to this source code.  In place of
107613 ** a legal notice, here is a blessing:
107614 **
107615 **    May you do good and not evil.
107616 **    May you find forgiveness for yourself and forgive others.
107617 **    May you share freely, never taking more than you give.
107618 **
107619 *************************************************************************
107620 **
107621 ** This file contains the implementation of the sqlite3_unlock_notify()
107622 ** API method and its associated functionality.
107623 */
107624
107625 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
107626 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
107627
107628 /*
107629 ** Public interfaces:
107630 **
107631 **   sqlite3ConnectionBlocked()
107632 **   sqlite3ConnectionUnlocked()
107633 **   sqlite3ConnectionClosed()
107634 **   sqlite3_unlock_notify()
107635 */
107636
107637 #define assertMutexHeld() \
107638   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
107639
107640 /*
107641 ** Head of a linked list of all sqlite3 objects created by this process
107642 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
107643 ** is not NULL. This variable may only accessed while the STATIC_MASTER
107644 ** mutex is held.
107645 */
107646 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
107647
107648 #ifndef NDEBUG
107649 /*
107650 ** This function is a complex assert() that verifies the following 
107651 ** properties of the blocked connections list:
107652 **
107653 **   1) Each entry in the list has a non-NULL value for either 
107654 **      pUnlockConnection or pBlockingConnection, or both.
107655 **
107656 **   2) All entries in the list that share a common value for 
107657 **      xUnlockNotify are grouped together.
107658 **
107659 **   3) If the argument db is not NULL, then none of the entries in the
107660 **      blocked connections list have pUnlockConnection or pBlockingConnection
107661 **      set to db. This is used when closing connection db.
107662 */
107663 static void checkListProperties(sqlite3 *db){
107664   sqlite3 *p;
107665   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
107666     int seen = 0;
107667     sqlite3 *p2;
107668
107669     /* Verify property (1) */
107670     assert( p->pUnlockConnection || p->pBlockingConnection );
107671
107672     /* Verify property (2) */
107673     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
107674       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
107675       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
107676       assert( db==0 || p->pUnlockConnection!=db );
107677       assert( db==0 || p->pBlockingConnection!=db );
107678     }
107679   }
107680 }
107681 #else
107682 # define checkListProperties(x)
107683 #endif
107684
107685 /*
107686 ** Remove connection db from the blocked connections list. If connection
107687 ** db is not currently a part of the list, this function is a no-op.
107688 */
107689 static void removeFromBlockedList(sqlite3 *db){
107690   sqlite3 **pp;
107691   assertMutexHeld();
107692   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
107693     if( *pp==db ){
107694       *pp = (*pp)->pNextBlocked;
107695       break;
107696     }
107697   }
107698 }
107699
107700 /*
107701 ** Add connection db to the blocked connections list. It is assumed
107702 ** that it is not already a part of the list.
107703 */
107704 static void addToBlockedList(sqlite3 *db){
107705   sqlite3 **pp;
107706   assertMutexHeld();
107707   for(
107708     pp=&sqlite3BlockedList; 
107709     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; 
107710     pp=&(*pp)->pNextBlocked
107711   );
107712   db->pNextBlocked = *pp;
107713   *pp = db;
107714 }
107715
107716 /*
107717 ** Obtain the STATIC_MASTER mutex.
107718 */
107719 static void enterMutex(void){
107720   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
107721   checkListProperties(0);
107722 }
107723
107724 /*
107725 ** Release the STATIC_MASTER mutex.
107726 */
107727 static void leaveMutex(void){
107728   assertMutexHeld();
107729   checkListProperties(0);
107730   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
107731 }
107732
107733 /*
107734 ** Register an unlock-notify callback.
107735 **
107736 ** This is called after connection "db" has attempted some operation
107737 ** but has received an SQLITE_LOCKED error because another connection
107738 ** (call it pOther) in the same process was busy using the same shared
107739 ** cache.  pOther is found by looking at db->pBlockingConnection.
107740 **
107741 ** If there is no blocking connection, the callback is invoked immediately,
107742 ** before this routine returns.
107743 **
107744 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
107745 ** a deadlock.
107746 **
107747 ** Otherwise, make arrangements to invoke xNotify when pOther drops
107748 ** its locks.
107749 **
107750 ** Each call to this routine overrides any prior callbacks registered
107751 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
107752 ** cancelled.
107753 */
107754 SQLITE_API int sqlite3_unlock_notify(
107755   sqlite3 *db,
107756   void (*xNotify)(void **, int),
107757   void *pArg
107758 ){
107759   int rc = SQLITE_OK;
107760
107761   sqlite3_mutex_enter(db->mutex);
107762   enterMutex();
107763
107764   if( xNotify==0 ){
107765     removeFromBlockedList(db);
107766     db->pBlockingConnection = 0;
107767     db->pUnlockConnection = 0;
107768     db->xUnlockNotify = 0;
107769     db->pUnlockArg = 0;
107770   }else if( 0==db->pBlockingConnection ){
107771     /* The blocking transaction has been concluded. Or there never was a 
107772     ** blocking transaction. In either case, invoke the notify callback
107773     ** immediately. 
107774     */
107775     xNotify(&pArg, 1);
107776   }else{
107777     sqlite3 *p;
107778
107779     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
107780     if( p ){
107781       rc = SQLITE_LOCKED;              /* Deadlock detected. */
107782     }else{
107783       db->pUnlockConnection = db->pBlockingConnection;
107784       db->xUnlockNotify = xNotify;
107785       db->pUnlockArg = pArg;
107786       removeFromBlockedList(db);
107787       addToBlockedList(db);
107788     }
107789   }
107790
107791   leaveMutex();
107792   assert( !db->mallocFailed );
107793   sqlite3Error(db, rc, (rc?"database is deadlocked":0));
107794   sqlite3_mutex_leave(db->mutex);
107795   return rc;
107796 }
107797
107798 /*
107799 ** This function is called while stepping or preparing a statement 
107800 ** associated with connection db. The operation will return SQLITE_LOCKED
107801 ** to the user because it requires a lock that will not be available
107802 ** until connection pBlocker concludes its current transaction.
107803 */
107804 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
107805   enterMutex();
107806   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
107807     addToBlockedList(db);
107808   }
107809   db->pBlockingConnection = pBlocker;
107810   leaveMutex();
107811 }
107812
107813 /*
107814 ** This function is called when
107815 ** the transaction opened by database db has just finished. Locks held 
107816 ** by database connection db have been released.
107817 **
107818 ** This function loops through each entry in the blocked connections
107819 ** list and does the following:
107820 **
107821 **   1) If the sqlite3.pBlockingConnection member of a list entry is
107822 **      set to db, then set pBlockingConnection=0.
107823 **
107824 **   2) If the sqlite3.pUnlockConnection member of a list entry is
107825 **      set to db, then invoke the configured unlock-notify callback and
107826 **      set pUnlockConnection=0.
107827 **
107828 **   3) If the two steps above mean that pBlockingConnection==0 and
107829 **      pUnlockConnection==0, remove the entry from the blocked connections
107830 **      list.
107831 */
107832 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
107833   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
107834   int nArg = 0;                            /* Number of entries in aArg[] */
107835   sqlite3 **pp;                            /* Iterator variable */
107836   void **aArg;               /* Arguments to the unlock callback */
107837   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
107838   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
107839
107840   aArg = aStatic;
107841   enterMutex();         /* Enter STATIC_MASTER mutex */
107842
107843   /* This loop runs once for each entry in the blocked-connections list. */
107844   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
107845     sqlite3 *p = *pp;
107846
107847     /* Step 1. */
107848     if( p->pBlockingConnection==db ){
107849       p->pBlockingConnection = 0;
107850     }
107851
107852     /* Step 2. */
107853     if( p->pUnlockConnection==db ){
107854       assert( p->xUnlockNotify );
107855       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
107856         xUnlockNotify(aArg, nArg);
107857         nArg = 0;
107858       }
107859
107860       sqlite3BeginBenignMalloc();
107861       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
107862       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
107863       if( (!aDyn && nArg==(int)ArraySize(aStatic))
107864        || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
107865       ){
107866         /* The aArg[] array needs to grow. */
107867         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
107868         if( pNew ){
107869           memcpy(pNew, aArg, nArg*sizeof(void *));
107870           sqlite3_free(aDyn);
107871           aDyn = aArg = pNew;
107872         }else{
107873           /* This occurs when the array of context pointers that need to
107874           ** be passed to the unlock-notify callback is larger than the
107875           ** aStatic[] array allocated on the stack and the attempt to 
107876           ** allocate a larger array from the heap has failed.
107877           **
107878           ** This is a difficult situation to handle. Returning an error
107879           ** code to the caller is insufficient, as even if an error code
107880           ** is returned the transaction on connection db will still be
107881           ** closed and the unlock-notify callbacks on blocked connections
107882           ** will go unissued. This might cause the application to wait
107883           ** indefinitely for an unlock-notify callback that will never 
107884           ** arrive.
107885           **
107886           ** Instead, invoke the unlock-notify callback with the context
107887           ** array already accumulated. We can then clear the array and
107888           ** begin accumulating any further context pointers without 
107889           ** requiring any dynamic allocation. This is sub-optimal because
107890           ** it means that instead of one callback with a large array of
107891           ** context pointers the application will receive two or more
107892           ** callbacks with smaller arrays of context pointers, which will
107893           ** reduce the applications ability to prioritize multiple 
107894           ** connections. But it is the best that can be done under the
107895           ** circumstances.
107896           */
107897           xUnlockNotify(aArg, nArg);
107898           nArg = 0;
107899         }
107900       }
107901       sqlite3EndBenignMalloc();
107902
107903       aArg[nArg++] = p->pUnlockArg;
107904       xUnlockNotify = p->xUnlockNotify;
107905       p->pUnlockConnection = 0;
107906       p->xUnlockNotify = 0;
107907       p->pUnlockArg = 0;
107908     }
107909
107910     /* Step 3. */
107911     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
107912       /* Remove connection p from the blocked connections list. */
107913       *pp = p->pNextBlocked;
107914       p->pNextBlocked = 0;
107915     }else{
107916       pp = &p->pNextBlocked;
107917     }
107918   }
107919
107920   if( nArg!=0 ){
107921     xUnlockNotify(aArg, nArg);
107922   }
107923   sqlite3_free(aDyn);
107924   leaveMutex();         /* Leave STATIC_MASTER mutex */
107925 }
107926
107927 /*
107928 ** This is called when the database connection passed as an argument is 
107929 ** being closed. The connection is removed from the blocked list.
107930 */
107931 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
107932   sqlite3ConnectionUnlocked(db);
107933   enterMutex();
107934   removeFromBlockedList(db);
107935   checkListProperties(db);
107936   leaveMutex();
107937 }
107938 #endif
107939
107940 /************** End of notify.c **********************************************/
107941 /************** Begin file fts3.c ********************************************/
107942 /*
107943 ** 2006 Oct 10
107944 **
107945 ** The author disclaims copyright to this source code.  In place of
107946 ** a legal notice, here is a blessing:
107947 **
107948 **    May you do good and not evil.
107949 **    May you find forgiveness for yourself and forgive others.
107950 **    May you share freely, never taking more than you give.
107951 **
107952 ******************************************************************************
107953 **
107954 ** This is an SQLite module implementing full-text search.
107955 */
107956
107957 /*
107958 ** The code in this file is only compiled if:
107959 **
107960 **     * The FTS3 module is being built as an extension
107961 **       (in which case SQLITE_CORE is not defined), or
107962 **
107963 **     * The FTS3 module is being built into the core of
107964 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
107965 */
107966
107967 /* The full-text index is stored in a series of b+tree (-like)
107968 ** structures called segments which map terms to doclists.  The
107969 ** structures are like b+trees in layout, but are constructed from the
107970 ** bottom up in optimal fashion and are not updatable.  Since trees
107971 ** are built from the bottom up, things will be described from the
107972 ** bottom up.
107973 **
107974 **
107975 **** Varints ****
107976 ** The basic unit of encoding is a variable-length integer called a
107977 ** varint.  We encode variable-length integers in little-endian order
107978 ** using seven bits * per byte as follows:
107979 **
107980 ** KEY:
107981 **         A = 0xxxxxxx    7 bits of data and one flag bit
107982 **         B = 1xxxxxxx    7 bits of data and one flag bit
107983 **
107984 **  7 bits - A
107985 ** 14 bits - BA
107986 ** 21 bits - BBA
107987 ** and so on.
107988 **
107989 ** This is similar in concept to how sqlite encodes "varints" but
107990 ** the encoding is not the same.  SQLite varints are big-endian
107991 ** are are limited to 9 bytes in length whereas FTS3 varints are
107992 ** little-endian and can be up to 10 bytes in length (in theory).
107993 **
107994 ** Example encodings:
107995 **
107996 **     1:    0x01
107997 **   127:    0x7f
107998 **   128:    0x81 0x00
107999 **
108000 **
108001 **** Document lists ****
108002 ** A doclist (document list) holds a docid-sorted list of hits for a
108003 ** given term.  Doclists hold docids and associated token positions.
108004 ** A docid is the unique integer identifier for a single document.
108005 ** A position is the index of a word within the document.  The first 
108006 ** word of the document has a position of 0.
108007 **
108008 ** FTS3 used to optionally store character offsets using a compile-time
108009 ** option.  But that functionality is no longer supported.
108010 **
108011 ** A doclist is stored like this:
108012 **
108013 ** array {
108014 **   varint docid;
108015 **   array {                (position list for column 0)
108016 **     varint position;     (2 more than the delta from previous position)
108017 **   }
108018 **   array {
108019 **     varint POS_COLUMN;   (marks start of position list for new column)
108020 **     varint column;       (index of new column)
108021 **     array {
108022 **       varint position;   (2 more than the delta from previous position)
108023 **     }
108024 **   }
108025 **   varint POS_END;        (marks end of positions for this document.
108026 ** }
108027 **
108028 ** Here, array { X } means zero or more occurrences of X, adjacent in
108029 ** memory.  A "position" is an index of a token in the token stream
108030 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur 
108031 ** in the same logical place as the position element, and act as sentinals
108032 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
108033 ** The positions numbers are not stored literally but rather as two more
108034 ** than the difference from the prior position, or the just the position plus
108035 ** 2 for the first position.  Example:
108036 **
108037 **   label:       A B C D E  F  G H   I  J K
108038 **   value:     123 5 9 1 1 14 35 0 234 72 0
108039 **
108040 ** The 123 value is the first docid.  For column zero in this document
108041 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
108042 ** at D signals the start of a new column; the 1 at E indicates that the
108043 ** new column is column number 1.  There are two positions at 12 and 45
108044 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
108045 ** 234 at I is the next docid.  It has one position 72 (72-2) and then
108046 ** terminates with the 0 at K.
108047 **
108048 ** A "position-list" is the list of positions for multiple columns for
108049 ** a single docid.  A "column-list" is the set of positions for a single
108050 ** column.  Hence, a position-list consists of one or more column-lists,
108051 ** a document record consists of a docid followed by a position-list and
108052 ** a doclist consists of one or more document records.
108053 **
108054 ** A bare doclist omits the position information, becoming an 
108055 ** array of varint-encoded docids.
108056 **
108057 **** Segment leaf nodes ****
108058 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
108059 ** nodes are written using LeafWriter, and read using LeafReader (to
108060 ** iterate through a single leaf node's data) and LeavesReader (to
108061 ** iterate through a segment's entire leaf layer).  Leaf nodes have
108062 ** the format:
108063 **
108064 ** varint iHeight;             (height from leaf level, always 0)
108065 ** varint nTerm;               (length of first term)
108066 ** char pTerm[nTerm];          (content of first term)
108067 ** varint nDoclist;            (length of term's associated doclist)
108068 ** char pDoclist[nDoclist];    (content of doclist)
108069 ** array {
108070 **                             (further terms are delta-encoded)
108071 **   varint nPrefix;           (length of prefix shared with previous term)
108072 **   varint nSuffix;           (length of unshared suffix)
108073 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
108074 **   varint nDoclist;          (length of term's associated doclist)
108075 **   char pDoclist[nDoclist];  (content of doclist)
108076 ** }
108077 **
108078 ** Here, array { X } means zero or more occurrences of X, adjacent in
108079 ** memory.
108080 **
108081 ** Leaf nodes are broken into blocks which are stored contiguously in
108082 ** the %_segments table in sorted order.  This means that when the end
108083 ** of a node is reached, the next term is in the node with the next
108084 ** greater node id.
108085 **
108086 ** New data is spilled to a new leaf node when the current node
108087 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
108088 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
108089 ** node (a leaf node with a single term and doclist).  The goal of
108090 ** these settings is to pack together groups of small doclists while
108091 ** making it efficient to directly access large doclists.  The
108092 ** assumption is that large doclists represent terms which are more
108093 ** likely to be query targets.
108094 **
108095 ** TODO(shess) It may be useful for blocking decisions to be more
108096 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
108097 ** node rather than splitting into 2k and .5k nodes.  My intuition is
108098 ** that this might extend through 2x or 4x the pagesize.
108099 **
108100 **
108101 **** Segment interior nodes ****
108102 ** Segment interior nodes store blockids for subtree nodes and terms
108103 ** to describe what data is stored by the each subtree.  Interior
108104 ** nodes are written using InteriorWriter, and read using
108105 ** InteriorReader.  InteriorWriters are created as needed when
108106 ** SegmentWriter creates new leaf nodes, or when an interior node
108107 ** itself grows too big and must be split.  The format of interior
108108 ** nodes:
108109 **
108110 ** varint iHeight;           (height from leaf level, always >0)
108111 ** varint iBlockid;          (block id of node's leftmost subtree)
108112 ** optional {
108113 **   varint nTerm;           (length of first term)
108114 **   char pTerm[nTerm];      (content of first term)
108115 **   array {
108116 **                                (further terms are delta-encoded)
108117 **     varint nPrefix;            (length of shared prefix with previous term)
108118 **     varint nSuffix;            (length of unshared suffix)
108119 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
108120 **   }
108121 ** }
108122 **
108123 ** Here, optional { X } means an optional element, while array { X }
108124 ** means zero or more occurrences of X, adjacent in memory.
108125 **
108126 ** An interior node encodes n terms separating n+1 subtrees.  The
108127 ** subtree blocks are contiguous, so only the first subtree's blockid
108128 ** is encoded.  The subtree at iBlockid will contain all terms less
108129 ** than the first term encoded (or all terms if no term is encoded).
108130 ** Otherwise, for terms greater than or equal to pTerm[i] but less
108131 ** than pTerm[i+1], the subtree for that term will be rooted at
108132 ** iBlockid+i.  Interior nodes only store enough term data to
108133 ** distinguish adjacent children (if the rightmost term of the left
108134 ** child is "something", and the leftmost term of the right child is
108135 ** "wicked", only "w" is stored).
108136 **
108137 ** New data is spilled to a new interior node at the same height when
108138 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
108139 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
108140 ** interior nodes and making the tree too skinny.  The interior nodes
108141 ** at a given height are naturally tracked by interior nodes at
108142 ** height+1, and so on.
108143 **
108144 **
108145 **** Segment directory ****
108146 ** The segment directory in table %_segdir stores meta-information for
108147 ** merging and deleting segments, and also the root node of the
108148 ** segment's tree.
108149 **
108150 ** The root node is the top node of the segment's tree after encoding
108151 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
108152 ** This could be either a leaf node or an interior node.  If the top
108153 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
108154 ** and a new root interior node is generated (which should always fit
108155 ** within ROOT_MAX because it only needs space for 2 varints, the
108156 ** height and the blockid of the previous root).
108157 **
108158 ** The meta-information in the segment directory is:
108159 **   level               - segment level (see below)
108160 **   idx                 - index within level
108161 **                       - (level,idx uniquely identify a segment)
108162 **   start_block         - first leaf node
108163 **   leaves_end_block    - last leaf node
108164 **   end_block           - last block (including interior nodes)
108165 **   root                - contents of root node
108166 **
108167 ** If the root node is a leaf node, then start_block,
108168 ** leaves_end_block, and end_block are all 0.
108169 **
108170 **
108171 **** Segment merging ****
108172 ** To amortize update costs, segments are grouped into levels and
108173 ** merged in batches.  Each increase in level represents exponentially
108174 ** more documents.
108175 **
108176 ** New documents (actually, document updates) are tokenized and
108177 ** written individually (using LeafWriter) to a level 0 segment, with
108178 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
108179 ** level 0 segments are merged into a single level 1 segment.  Level 1
108180 ** is populated like level 0, and eventually MERGE_COUNT level 1
108181 ** segments are merged to a single level 2 segment (representing
108182 ** MERGE_COUNT^2 updates), and so on.
108183 **
108184 ** A segment merge traverses all segments at a given level in
108185 ** parallel, performing a straightforward sorted merge.  Since segment
108186 ** leaf nodes are written in to the %_segments table in order, this
108187 ** merge traverses the underlying sqlite disk structures efficiently.
108188 ** After the merge, all segment blocks from the merged level are
108189 ** deleted.
108190 **
108191 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
108192 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
108193 ** very similar performance numbers to 16 on insertion, though they're
108194 ** a tiny bit slower (perhaps due to more overhead in merge-time
108195 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
108196 ** 16, 2 about 66% slower than 16.
108197 **
108198 ** At query time, high MERGE_COUNT increases the number of segments
108199 ** which need to be scanned and merged.  For instance, with 100k docs
108200 ** inserted:
108201 **
108202 **    MERGE_COUNT   segments
108203 **       16           25
108204 **        8           12
108205 **        4           10
108206 **        2            6
108207 **
108208 ** This appears to have only a moderate impact on queries for very
108209 ** frequent terms (which are somewhat dominated by segment merge
108210 ** costs), and infrequent and non-existent terms still seem to be fast
108211 ** even with many segments.
108212 **
108213 ** TODO(shess) That said, it would be nice to have a better query-side
108214 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
108215 ** optimizations to things like doclist merging will swing the sweet
108216 ** spot around.
108217 **
108218 **
108219 **
108220 **** Handling of deletions and updates ****
108221 ** Since we're using a segmented structure, with no docid-oriented
108222 ** index into the term index, we clearly cannot simply update the term
108223 ** index when a document is deleted or updated.  For deletions, we
108224 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
108225 ** we simply write the new doclist.  Segment merges overwrite older
108226 ** data for a particular docid with newer data, so deletes or updates
108227 ** will eventually overtake the earlier data and knock it out.  The
108228 ** query logic likewise merges doclists so that newer data knocks out
108229 ** older data.
108230 **
108231 ** TODO(shess) Provide a VACUUM type operation to clear out all
108232 ** deletions and duplications.  This would basically be a forced merge
108233 ** into a single segment.
108234 */
108235
108236 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
108237
108238 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
108239 # define SQLITE_CORE 1
108240 #endif
108241
108242 /************** Include fts3Int.h in the middle of fts3.c ********************/
108243 /************** Begin file fts3Int.h *****************************************/
108244 /*
108245 ** 2009 Nov 12
108246 **
108247 ** The author disclaims copyright to this source code.  In place of
108248 ** a legal notice, here is a blessing:
108249 **
108250 **    May you do good and not evil.
108251 **    May you find forgiveness for yourself and forgive others.
108252 **    May you share freely, never taking more than you give.
108253 **
108254 ******************************************************************************
108255 **
108256 */
108257
108258 #ifndef _FTSINT_H
108259 #define _FTSINT_H
108260
108261 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
108262 # define NDEBUG 1
108263 #endif
108264
108265 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
108266 /************** Begin file fts3_tokenizer.h **********************************/
108267 /*
108268 ** 2006 July 10
108269 **
108270 ** The author disclaims copyright to this source code.
108271 **
108272 *************************************************************************
108273 ** Defines the interface to tokenizers used by fulltext-search.  There
108274 ** are three basic components:
108275 **
108276 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
108277 ** interface functions.  This is essentially the class structure for
108278 ** tokenizers.
108279 **
108280 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
108281 ** including customization information defined at creation time.
108282 **
108283 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
108284 ** tokens from a particular input.
108285 */
108286 #ifndef _FTS3_TOKENIZER_H_
108287 #define _FTS3_TOKENIZER_H_
108288
108289 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
108290 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
108291 ** we will need a way to register the API consistently.
108292 */
108293
108294 /*
108295 ** Structures used by the tokenizer interface. When a new tokenizer
108296 ** implementation is registered, the caller provides a pointer to
108297 ** an sqlite3_tokenizer_module containing pointers to the callback
108298 ** functions that make up an implementation.
108299 **
108300 ** When an fts3 table is created, it passes any arguments passed to
108301 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
108302 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
108303 ** implementation. The xCreate() function in turn returns an 
108304 ** sqlite3_tokenizer structure representing the specific tokenizer to
108305 ** be used for the fts3 table (customized by the tokenizer clause arguments).
108306 **
108307 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
108308 ** method is called. It returns an sqlite3_tokenizer_cursor object
108309 ** that may be used to tokenize a specific input buffer based on
108310 ** the tokenization rules supplied by a specific sqlite3_tokenizer
108311 ** object.
108312 */
108313 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
108314 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
108315 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
108316
108317 struct sqlite3_tokenizer_module {
108318
108319   /*
108320   ** Structure version. Should always be set to 0.
108321   */
108322   int iVersion;
108323
108324   /*
108325   ** Create a new tokenizer. The values in the argv[] array are the
108326   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
108327   ** TABLE statement that created the fts3 table. For example, if
108328   ** the following SQL is executed:
108329   **
108330   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
108331   **
108332   ** then argc is set to 2, and the argv[] array contains pointers
108333   ** to the strings "arg1" and "arg2".
108334   **
108335   ** This method should return either SQLITE_OK (0), or an SQLite error 
108336   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
108337   ** to point at the newly created tokenizer structure. The generic
108338   ** sqlite3_tokenizer.pModule variable should not be initialised by
108339   ** this callback. The caller will do so.
108340   */
108341   int (*xCreate)(
108342     int argc,                           /* Size of argv array */
108343     const char *const*argv,             /* Tokenizer argument strings */
108344     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
108345   );
108346
108347   /*
108348   ** Destroy an existing tokenizer. The fts3 module calls this method
108349   ** exactly once for each successful call to xCreate().
108350   */
108351   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
108352
108353   /*
108354   ** Create a tokenizer cursor to tokenize an input buffer. The caller
108355   ** is responsible for ensuring that the input buffer remains valid
108356   ** until the cursor is closed (using the xClose() method). 
108357   */
108358   int (*xOpen)(
108359     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
108360     const char *pInput, int nBytes,      /* Input buffer */
108361     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
108362   );
108363
108364   /*
108365   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
108366   ** method exactly once for each successful call to xOpen().
108367   */
108368   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
108369
108370   /*
108371   ** Retrieve the next token from the tokenizer cursor pCursor. This
108372   ** method should either return SQLITE_OK and set the values of the
108373   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
108374   ** the end of the buffer has been reached, or an SQLite error code.
108375   **
108376   ** *ppToken should be set to point at a buffer containing the 
108377   ** normalized version of the token (i.e. after any case-folding and/or
108378   ** stemming has been performed). *pnBytes should be set to the length
108379   ** of this buffer in bytes. The input text that generated the token is
108380   ** identified by the byte offsets returned in *piStartOffset and
108381   ** *piEndOffset. *piStartOffset should be set to the index of the first
108382   ** byte of the token in the input buffer. *piEndOffset should be set
108383   ** to the index of the first byte just past the end of the token in
108384   ** the input buffer.
108385   **
108386   ** The buffer *ppToken is set to point at is managed by the tokenizer
108387   ** implementation. It is only required to be valid until the next call
108388   ** to xNext() or xClose(). 
108389   */
108390   /* TODO(shess) current implementation requires pInput to be
108391   ** nul-terminated.  This should either be fixed, or pInput/nBytes
108392   ** should be converted to zInput.
108393   */
108394   int (*xNext)(
108395     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
108396     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
108397     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
108398     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
108399     int *piPosition      /* OUT: Number of tokens returned before this one */
108400   );
108401 };
108402
108403 struct sqlite3_tokenizer {
108404   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
108405   /* Tokenizer implementations will typically add additional fields */
108406 };
108407
108408 struct sqlite3_tokenizer_cursor {
108409   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
108410   /* Tokenizer implementations will typically add additional fields */
108411 };
108412
108413 int fts3_global_term_cnt(int iTerm, int iCol);
108414 int fts3_term_cnt(int iTerm, int iCol);
108415
108416
108417 #endif /* _FTS3_TOKENIZER_H_ */
108418
108419 /************** End of fts3_tokenizer.h **************************************/
108420 /************** Continuing where we left off in fts3Int.h ********************/
108421 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
108422 /************** Begin file fts3_hash.h ***************************************/
108423 /*
108424 ** 2001 September 22
108425 **
108426 ** The author disclaims copyright to this source code.  In place of
108427 ** a legal notice, here is a blessing:
108428 **
108429 **    May you do good and not evil.
108430 **    May you find forgiveness for yourself and forgive others.
108431 **    May you share freely, never taking more than you give.
108432 **
108433 *************************************************************************
108434 ** This is the header file for the generic hash-table implemenation
108435 ** used in SQLite.  We've modified it slightly to serve as a standalone
108436 ** hash table implementation for the full-text indexing module.
108437 **
108438 */
108439 #ifndef _FTS3_HASH_H_
108440 #define _FTS3_HASH_H_
108441
108442 /* Forward declarations of structures. */
108443 typedef struct Fts3Hash Fts3Hash;
108444 typedef struct Fts3HashElem Fts3HashElem;
108445
108446 /* A complete hash table is an instance of the following structure.
108447 ** The internals of this structure are intended to be opaque -- client
108448 ** code should not attempt to access or modify the fields of this structure
108449 ** directly.  Change this structure only by using the routines below.
108450 ** However, many of the "procedures" and "functions" for modifying and
108451 ** accessing this structure are really macros, so we can't really make
108452 ** this structure opaque.
108453 */
108454 struct Fts3Hash {
108455   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
108456   char copyKey;           /* True if copy of key made on insert */
108457   int count;              /* Number of entries in this table */
108458   Fts3HashElem *first;    /* The first element of the array */
108459   int htsize;             /* Number of buckets in the hash table */
108460   struct _fts3ht {        /* the hash table */
108461     int count;               /* Number of entries with this hash */
108462     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
108463   } *ht;
108464 };
108465
108466 /* Each element in the hash table is an instance of the following 
108467 ** structure.  All elements are stored on a single doubly-linked list.
108468 **
108469 ** Again, this structure is intended to be opaque, but it can't really
108470 ** be opaque because it is used by macros.
108471 */
108472 struct Fts3HashElem {
108473   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
108474   void *data;                /* Data associated with this element */
108475   void *pKey; int nKey;      /* Key associated with this element */
108476 };
108477
108478 /*
108479 ** There are 2 different modes of operation for a hash table:
108480 **
108481 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
108482 **                           (including the null-terminator, if any).  Case
108483 **                           is respected in comparisons.
108484 **
108485 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
108486 **                           memcmp() is used to compare keys.
108487 **
108488 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
108489 */
108490 #define FTS3_HASH_STRING    1
108491 #define FTS3_HASH_BINARY    2
108492
108493 /*
108494 ** Access routines.  To delete, insert a NULL pointer.
108495 */
108496 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
108497 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
108498 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
108499 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
108500 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
108501
108502 /*
108503 ** Shorthand for the functions above
108504 */
108505 #define fts3HashInit     sqlite3Fts3HashInit
108506 #define fts3HashInsert   sqlite3Fts3HashInsert
108507 #define fts3HashFind     sqlite3Fts3HashFind
108508 #define fts3HashClear    sqlite3Fts3HashClear
108509 #define fts3HashFindElem sqlite3Fts3HashFindElem
108510
108511 /*
108512 ** Macros for looping over all elements of a hash table.  The idiom is
108513 ** like this:
108514 **
108515 **   Fts3Hash h;
108516 **   Fts3HashElem *p;
108517 **   ...
108518 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
108519 **     SomeStructure *pData = fts3HashData(p);
108520 **     // do something with pData
108521 **   }
108522 */
108523 #define fts3HashFirst(H)  ((H)->first)
108524 #define fts3HashNext(E)   ((E)->next)
108525 #define fts3HashData(E)   ((E)->data)
108526 #define fts3HashKey(E)    ((E)->pKey)
108527 #define fts3HashKeysize(E) ((E)->nKey)
108528
108529 /*
108530 ** Number of entries in a hash table
108531 */
108532 #define fts3HashCount(H)  ((H)->count)
108533
108534 #endif /* _FTS3_HASH_H_ */
108535
108536 /************** End of fts3_hash.h *******************************************/
108537 /************** Continuing where we left off in fts3Int.h ********************/
108538
108539 /*
108540 ** This constant controls how often segments are merged. Once there are
108541 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
108542 ** segment of level N+1.
108543 */
108544 #define FTS3_MERGE_COUNT 16
108545
108546 /*
108547 ** This is the maximum amount of data (in bytes) to store in the 
108548 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
108549 ** populated as documents are inserted/updated/deleted in a transaction
108550 ** and used to create a new segment when the transaction is committed.
108551 ** However if this limit is reached midway through a transaction, a new 
108552 ** segment is created and the hash table cleared immediately.
108553 */
108554 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
108555
108556 /*
108557 ** Macro to return the number of elements in an array. SQLite has a
108558 ** similar macro called ArraySize(). Use a different name to avoid
108559 ** a collision when building an amalgamation with built-in FTS3.
108560 */
108561 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
108562
108563 /*
108564 ** Maximum length of a varint encoded integer. The varint format is different
108565 ** from that used by SQLite, so the maximum length is 10, not 9.
108566 */
108567 #define FTS3_VARINT_MAX 10
108568
108569 /*
108570 ** The testcase() macro is only used by the amalgamation.  If undefined,
108571 ** make it a no-op.
108572 */
108573 #ifndef testcase
108574 # define testcase(X)
108575 #endif
108576
108577 /*
108578 ** Terminator values for position-lists and column-lists.
108579 */
108580 #define POS_COLUMN  (1)     /* Column-list terminator */
108581 #define POS_END     (0)     /* Position-list terminator */ 
108582
108583 /*
108584 ** This section provides definitions to allow the
108585 ** FTS3 extension to be compiled outside of the 
108586 ** amalgamation.
108587 */
108588 #ifndef SQLITE_AMALGAMATION
108589 /*
108590 ** Macros indicating that conditional expressions are always true or
108591 ** false.
108592 */
108593 #ifdef SQLITE_COVERAGE_TEST
108594 # define ALWAYS(x) (1)
108595 # define NEVER(X)  (0)
108596 #else
108597 # define ALWAYS(x) (x)
108598 # define NEVER(X)  (x)
108599 #endif
108600
108601 /*
108602 ** Internal types used by SQLite.
108603 */
108604 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
108605 typedef short int i16;            /* 2-byte (or larger) signed integer */
108606 typedef unsigned int u32;         /* 4-byte unsigned integer */
108607 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
108608 /*
108609 ** Macro used to suppress compiler warnings for unused parameters.
108610 */
108611 #define UNUSED_PARAMETER(x) (void)(x)
108612 #endif
108613
108614 typedef struct Fts3Table Fts3Table;
108615 typedef struct Fts3Cursor Fts3Cursor;
108616 typedef struct Fts3Expr Fts3Expr;
108617 typedef struct Fts3Phrase Fts3Phrase;
108618 typedef struct Fts3PhraseToken Fts3PhraseToken;
108619
108620 typedef struct Fts3SegFilter Fts3SegFilter;
108621 typedef struct Fts3DeferredToken Fts3DeferredToken;
108622 typedef struct Fts3SegReader Fts3SegReader;
108623 typedef struct Fts3SegReaderArray Fts3SegReaderArray;
108624
108625 /*
108626 ** A connection to a fulltext index is an instance of the following
108627 ** structure. The xCreate and xConnect methods create an instance
108628 ** of this structure and xDestroy and xDisconnect free that instance.
108629 ** All other methods receive a pointer to the structure as one of their
108630 ** arguments.
108631 */
108632 struct Fts3Table {
108633   sqlite3_vtab base;              /* Base class used by SQLite core */
108634   sqlite3 *db;                    /* The database connection */
108635   const char *zDb;                /* logical database name */
108636   const char *zName;              /* virtual table name */
108637   int nColumn;                    /* number of named columns in virtual table */
108638   char **azColumn;                /* column names.  malloced */
108639   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
108640
108641   /* Precompiled statements used by the implementation. Each of these 
108642   ** statements is run and reset within a single virtual table API call. 
108643   */
108644   sqlite3_stmt *aStmt[24];
108645
108646   int nNodeSize;                  /* Soft limit for node size */
108647   u8 bHasStat;                    /* True if %_stat table exists */
108648   u8 bHasDocsize;                 /* True if %_docsize table exists */
108649   int nPgsz;                      /* Page size for host database */
108650   char *zSegmentsTbl;             /* Name of %_segments table */
108651   sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
108652
108653   /* The following hash table is used to buffer pending index updates during
108654   ** transactions. Variable nPendingData estimates the memory size of the 
108655   ** pending data, including hash table overhead, but not malloc overhead. 
108656   ** When nPendingData exceeds nMaxPendingData, the buffer is flushed 
108657   ** automatically. Variable iPrevDocid is the docid of the most recently
108658   ** inserted record.
108659   */
108660   int nMaxPendingData;
108661   int nPendingData;
108662   sqlite_int64 iPrevDocid;
108663   Fts3Hash pendingTerms;
108664 };
108665
108666 /*
108667 ** When the core wants to read from the virtual table, it creates a
108668 ** virtual table cursor (an instance of the following structure) using
108669 ** the xOpen method. Cursors are destroyed using the xClose method.
108670 */
108671 struct Fts3Cursor {
108672   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
108673   i16 eSearch;                    /* Search strategy (see below) */
108674   u8 isEof;                       /* True if at End Of Results */
108675   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
108676   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
108677   Fts3Expr *pExpr;                /* Parsed MATCH query string */
108678   int nPhrase;                    /* Number of matchable phrases in query */
108679   Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
108680   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
108681   char *pNextId;                  /* Pointer into the body of aDoclist */
108682   char *aDoclist;                 /* List of docids for full-text queries */
108683   int nDoclist;                   /* Size of buffer at aDoclist */
108684   int eEvalmode;                  /* An FTS3_EVAL_XX constant */
108685   int nRowAvg;                    /* Average size of database rows, in pages */
108686
108687   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
108688   u32 *aMatchinfo;                /* Information about most recent match */
108689   int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
108690   char *zMatchinfo;               /* Matchinfo specification */
108691 };
108692
108693 #define FTS3_EVAL_FILTER    0
108694 #define FTS3_EVAL_NEXT      1
108695 #define FTS3_EVAL_MATCHINFO 2
108696
108697 /*
108698 ** The Fts3Cursor.eSearch member is always set to one of the following.
108699 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
108700 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
108701 ** of the column to be searched.  For example, in
108702 **
108703 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
108704 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
108705 ** 
108706 ** Because the LHS of the MATCH operator is 2nd column "b",
108707 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
108708 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1" 
108709 ** indicating that all columns should be searched,
108710 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
108711 */
108712 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
108713 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
108714 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
108715
108716 /*
108717 ** A "phrase" is a sequence of one or more tokens that must match in
108718 ** sequence.  A single token is the base case and the most common case.
108719 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
108720 ** nToken will be the number of tokens in the string.
108721 **
108722 ** The nDocMatch and nMatch variables contain data that may be used by the
108723 ** matchinfo() function. They are populated when the full-text index is 
108724 ** queried for hits on the phrase. If one or more tokens in the phrase
108725 ** are deferred, the nDocMatch and nMatch variables are populated based
108726 ** on the assumption that the 
108727 */
108728 struct Fts3PhraseToken {
108729   char *z;                        /* Text of the token */
108730   int n;                          /* Number of bytes in buffer z */
108731   int isPrefix;                   /* True if token ends with a "*" character */
108732   int bFulltext;                  /* True if full-text index was used */
108733   Fts3SegReaderArray *pArray;     /* Segment-reader for this token */
108734   Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
108735 };
108736
108737 struct Fts3Phrase {
108738   /* Variables populated by fts3_expr.c when parsing a MATCH expression */
108739   int nToken;                /* Number of tokens in the phrase */
108740   int iColumn;               /* Index of column this phrase must match */
108741   int isNot;                 /* Phrase prefixed by unary not (-) operator */
108742   Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
108743 };
108744
108745 /*
108746 ** A tree of these objects forms the RHS of a MATCH operator.
108747 **
108748 ** If Fts3Expr.eType is either FTSQUERY_NEAR or FTSQUERY_PHRASE and isLoaded
108749 ** is true, then aDoclist points to a malloced buffer, size nDoclist bytes, 
108750 ** containing the results of the NEAR or phrase query in FTS3 doclist
108751 ** format. As usual, the initial "Length" field found in doclists stored
108752 ** on disk is omitted from this buffer.
108753 **
108754 ** Variable pCurrent always points to the start of a docid field within
108755 ** aDoclist. Since the doclist is usually scanned in docid order, this can
108756 ** be used to accelerate seeking to the required docid within the doclist.
108757 */
108758 struct Fts3Expr {
108759   int eType;                 /* One of the FTSQUERY_XXX values defined below */
108760   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
108761   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
108762   Fts3Expr *pLeft;           /* Left operand */
108763   Fts3Expr *pRight;          /* Right operand */
108764   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
108765
108766   int isLoaded;              /* True if aDoclist/nDoclist are initialized. */
108767   char *aDoclist;            /* Buffer containing doclist */
108768   int nDoclist;              /* Size of aDoclist in bytes */
108769
108770   sqlite3_int64 iCurrent;
108771   char *pCurrent;
108772 };
108773
108774 /*
108775 ** Candidate values for Fts3Query.eType. Note that the order of the first
108776 ** four values is in order of precedence when parsing expressions. For 
108777 ** example, the following:
108778 **
108779 **   "a OR b AND c NOT d NEAR e"
108780 **
108781 ** is equivalent to:
108782 **
108783 **   "a OR (b AND (c NOT (d NEAR e)))"
108784 */
108785 #define FTSQUERY_NEAR   1
108786 #define FTSQUERY_NOT    2
108787 #define FTSQUERY_AND    3
108788 #define FTSQUERY_OR     4
108789 #define FTSQUERY_PHRASE 5
108790
108791
108792 /* fts3_write.c */
108793 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
108794 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
108795 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
108796 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
108797 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, sqlite3_int64,
108798   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
108799 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(Fts3Table*,const char*,int,int,Fts3SegReader**);
108800 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
108801 SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
108802   Fts3Table *, Fts3SegReader **, int, Fts3SegFilter *,
108803   int (*)(Fts3Table *, void *, char *, int, char *, int),  void *
108804 );
108805 SQLITE_PRIVATE int sqlite3Fts3SegReaderCost(Fts3Cursor *, Fts3SegReader *, int *);
108806 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, sqlite3_stmt **);
108807 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
108808 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*);
108809
108810 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
108811 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
108812
108813 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
108814 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
108815 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
108816 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
108817 SQLITE_PRIVATE char *sqlite3Fts3DeferredDoclist(Fts3DeferredToken *, int *);
108818
108819 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
108820
108821 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
108822 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
108823 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
108824 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
108825 #define FTS3_SEGMENT_PREFIX        0x00000008
108826
108827 /* Type passed as 4th argument to SegmentReaderIterate() */
108828 struct Fts3SegFilter {
108829   const char *zTerm;
108830   int nTerm;
108831   int iCol;
108832   int flags;
108833 };
108834
108835 /* fts3.c */
108836 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
108837 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
108838 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
108839 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
108840 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
108841
108842 SQLITE_PRIVATE char *sqlite3Fts3FindPositions(Fts3Expr *, sqlite3_int64, int);
108843 SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Cursor *, Fts3Expr *);
108844 SQLITE_PRIVATE int sqlite3Fts3ExprLoadFtDoclist(Fts3Cursor *, Fts3Expr *, char **, int *);
108845 SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *, Fts3Expr *, int);
108846
108847 /* fts3_tokenizer.c */
108848 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
108849 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
108850 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *, 
108851     sqlite3_tokenizer **, char **
108852 );
108853 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
108854
108855 /* fts3_snippet.c */
108856 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
108857 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
108858   const char *, const char *, int, int
108859 );
108860 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
108861
108862 /* fts3_expr.c */
108863 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, 
108864   char **, int, int, const char *, int, Fts3Expr **
108865 );
108866 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
108867 #ifdef SQLITE_TEST
108868 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
108869 #endif
108870
108871 #endif /* _FTSINT_H */
108872
108873 /************** End of fts3Int.h *********************************************/
108874 /************** Continuing where we left off in fts3.c ***********************/
108875
108876
108877 #ifndef SQLITE_CORE 
108878   SQLITE_EXTENSION_INIT1
108879 #endif
108880
108881 /* 
108882 ** Write a 64-bit variable-length integer to memory starting at p[0].
108883 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
108884 ** The number of bytes written is returned.
108885 */
108886 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
108887   unsigned char *q = (unsigned char *) p;
108888   sqlite_uint64 vu = v;
108889   do{
108890     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
108891     vu >>= 7;
108892   }while( vu!=0 );
108893   q[-1] &= 0x7f;  /* turn off high bit in final byte */
108894   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
108895   return (int) (q - (unsigned char *)p);
108896 }
108897
108898 /* 
108899 ** Read a 64-bit variable-length integer from memory starting at p[0].
108900 ** Return the number of bytes read, or 0 on error.
108901 ** The value is stored in *v.
108902 */
108903 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
108904   const unsigned char *q = (const unsigned char *) p;
108905   sqlite_uint64 x = 0, y = 1;
108906   while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
108907     x += y * (*q++ & 0x7f);
108908     y <<= 7;
108909   }
108910   x += y * (*q++);
108911   *v = (sqlite_int64) x;
108912   return (int) (q - (unsigned char *)p);
108913 }
108914
108915 /*
108916 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
108917 ** 32-bit integer before it is returned.
108918 */
108919 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
108920  sqlite_int64 i;
108921  int ret = sqlite3Fts3GetVarint(p, &i);
108922  *pi = (int) i;
108923  return ret;
108924 }
108925
108926 /*
108927 ** Return the number of bytes required to encode v as a varint
108928 */
108929 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
108930   int i = 0;
108931   do{
108932     i++;
108933     v >>= 7;
108934   }while( v!=0 );
108935   return i;
108936 }
108937
108938 /*
108939 ** Convert an SQL-style quoted string into a normal string by removing
108940 ** the quote characters.  The conversion is done in-place.  If the
108941 ** input does not begin with a quote character, then this routine
108942 ** is a no-op.
108943 **
108944 ** Examples:
108945 **
108946 **     "abc"   becomes   abc
108947 **     'xyz'   becomes   xyz
108948 **     [pqr]   becomes   pqr
108949 **     `mno`   becomes   mno
108950 **
108951 */
108952 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
108953   char quote;                     /* Quote character (if any ) */
108954
108955   quote = z[0];
108956   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
108957     int iIn = 1;                  /* Index of next byte to read from input */
108958     int iOut = 0;                 /* Index of next byte to write to output */
108959
108960     /* If the first byte was a '[', then the close-quote character is a ']' */
108961     if( quote=='[' ) quote = ']';  
108962
108963     while( ALWAYS(z[iIn]) ){
108964       if( z[iIn]==quote ){
108965         if( z[iIn+1]!=quote ) break;
108966         z[iOut++] = quote;
108967         iIn += 2;
108968       }else{
108969         z[iOut++] = z[iIn++];
108970       }
108971     }
108972     z[iOut] = '\0';
108973   }
108974 }
108975
108976 /*
108977 ** Read a single varint from the doclist at *pp and advance *pp to point
108978 ** to the first byte past the end of the varint.  Add the value of the varint
108979 ** to *pVal.
108980 */
108981 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
108982   sqlite3_int64 iVal;
108983   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
108984   *pVal += iVal;
108985 }
108986
108987 /*
108988 ** As long as *pp has not reached its end (pEnd), then do the same
108989 ** as fts3GetDeltaVarint(): read a single varint and add it to *pVal.
108990 ** But if we have reached the end of the varint, just set *pp=0 and
108991 ** leave *pVal unchanged.
108992 */
108993 static void fts3GetDeltaVarint2(char **pp, char *pEnd, sqlite3_int64 *pVal){
108994   if( *pp>=pEnd ){
108995     *pp = 0;
108996   }else{
108997     fts3GetDeltaVarint(pp, pVal);
108998   }
108999 }
109000
109001 /*
109002 ** The xDisconnect() virtual table method.
109003 */
109004 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
109005   Fts3Table *p = (Fts3Table *)pVtab;
109006   int i;
109007
109008   assert( p->nPendingData==0 );
109009   assert( p->pSegments==0 );
109010
109011   /* Free any prepared statements held */
109012   for(i=0; i<SizeofArray(p->aStmt); i++){
109013     sqlite3_finalize(p->aStmt[i]);
109014   }
109015   sqlite3_free(p->zSegmentsTbl);
109016
109017   /* Invoke the tokenizer destructor to free the tokenizer. */
109018   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
109019
109020   sqlite3_free(p);
109021   return SQLITE_OK;
109022 }
109023
109024 /*
109025 ** Construct one or more SQL statements from the format string given
109026 ** and then evaluate those statements. The success code is written
109027 ** into *pRc.
109028 **
109029 ** If *pRc is initially non-zero then this routine is a no-op.
109030 */
109031 static void fts3DbExec(
109032   int *pRc,              /* Success code */
109033   sqlite3 *db,           /* Database in which to run SQL */
109034   const char *zFormat,   /* Format string for SQL */
109035   ...                    /* Arguments to the format string */
109036 ){
109037   va_list ap;
109038   char *zSql;
109039   if( *pRc ) return;
109040   va_start(ap, zFormat);
109041   zSql = sqlite3_vmprintf(zFormat, ap);
109042   va_end(ap);
109043   if( zSql==0 ){
109044     *pRc = SQLITE_NOMEM;
109045   }else{
109046     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
109047     sqlite3_free(zSql);
109048   }
109049 }
109050
109051 /*
109052 ** The xDestroy() virtual table method.
109053 */
109054 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
109055   int rc = SQLITE_OK;              /* Return code */
109056   Fts3Table *p = (Fts3Table *)pVtab;
109057   sqlite3 *db = p->db;
109058
109059   /* Drop the shadow tables */
109060   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", p->zDb, p->zName);
109061   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", p->zDb,p->zName);
109062   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", p->zDb, p->zName);
109063   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", p->zDb, p->zName);
109064   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", p->zDb, p->zName);
109065
109066   /* If everything has worked, invoke fts3DisconnectMethod() to free the
109067   ** memory associated with the Fts3Table structure and return SQLITE_OK.
109068   ** Otherwise, return an SQLite error code.
109069   */
109070   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
109071 }
109072
109073
109074 /*
109075 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
109076 ** passed as the first argument. This is done as part of the xConnect()
109077 ** and xCreate() methods.
109078 **
109079 ** If *pRc is non-zero when this function is called, it is a no-op. 
109080 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
109081 ** before returning.
109082 */
109083 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
109084   if( *pRc==SQLITE_OK ){
109085     int i;                        /* Iterator variable */
109086     int rc;                       /* Return code */
109087     char *zSql;                   /* SQL statement passed to declare_vtab() */
109088     char *zCols;                  /* List of user defined columns */
109089
109090     /* Create a list of user columns for the virtual table */
109091     zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
109092     for(i=1; zCols && i<p->nColumn; i++){
109093       zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
109094     }
109095
109096     /* Create the whole "CREATE TABLE" statement to pass to SQLite */
109097     zSql = sqlite3_mprintf(
109098         "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN)", zCols, p->zName
109099     );
109100     if( !zCols || !zSql ){
109101       rc = SQLITE_NOMEM;
109102     }else{
109103       rc = sqlite3_declare_vtab(p->db, zSql);
109104     }
109105
109106     sqlite3_free(zSql);
109107     sqlite3_free(zCols);
109108     *pRc = rc;
109109   }
109110 }
109111
109112 /*
109113 ** Create the backing store tables (%_content, %_segments and %_segdir)
109114 ** required by the FTS3 table passed as the only argument. This is done
109115 ** as part of the vtab xCreate() method.
109116 **
109117 ** If the p->bHasDocsize boolean is true (indicating that this is an
109118 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
109119 ** %_stat tables required by FTS4.
109120 */
109121 static int fts3CreateTables(Fts3Table *p){
109122   int rc = SQLITE_OK;             /* Return code */
109123   int i;                          /* Iterator variable */
109124   char *zContentCols;             /* Columns of %_content table */
109125   sqlite3 *db = p->db;            /* The database connection */
109126
109127   /* Create a list of user columns for the content table */
109128   zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
109129   for(i=0; zContentCols && i<p->nColumn; i++){
109130     char *z = p->azColumn[i];
109131     zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
109132   }
109133   if( zContentCols==0 ) rc = SQLITE_NOMEM;
109134
109135   /* Create the content table */
109136   fts3DbExec(&rc, db, 
109137      "CREATE TABLE %Q.'%q_content'(%s)",
109138      p->zDb, p->zName, zContentCols
109139   );
109140   sqlite3_free(zContentCols);
109141   /* Create other tables */
109142   fts3DbExec(&rc, db, 
109143       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
109144       p->zDb, p->zName
109145   );
109146   fts3DbExec(&rc, db, 
109147       "CREATE TABLE %Q.'%q_segdir'("
109148         "level INTEGER,"
109149         "idx INTEGER,"
109150         "start_block INTEGER,"
109151         "leaves_end_block INTEGER,"
109152         "end_block INTEGER,"
109153         "root BLOB,"
109154         "PRIMARY KEY(level, idx)"
109155       ");",
109156       p->zDb, p->zName
109157   );
109158   if( p->bHasDocsize ){
109159     fts3DbExec(&rc, db, 
109160         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
109161         p->zDb, p->zName
109162     );
109163   }
109164   if( p->bHasStat ){
109165     fts3DbExec(&rc, db, 
109166         "CREATE TABLE %Q.'%q_stat'(id INTEGER PRIMARY KEY, value BLOB);",
109167         p->zDb, p->zName
109168     );
109169   }
109170   return rc;
109171 }
109172
109173 /*
109174 ** Store the current database page-size in bytes in p->nPgsz.
109175 **
109176 ** If *pRc is non-zero when this function is called, it is a no-op. 
109177 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
109178 ** before returning.
109179 */
109180 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
109181   if( *pRc==SQLITE_OK ){
109182     int rc;                       /* Return code */
109183     char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
109184     sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
109185   
109186     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
109187     if( !zSql ){
109188       rc = SQLITE_NOMEM;
109189     }else{
109190       rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
109191       if( rc==SQLITE_OK ){
109192         sqlite3_step(pStmt);
109193         p->nPgsz = sqlite3_column_int(pStmt, 0);
109194         rc = sqlite3_finalize(pStmt);
109195       }
109196     }
109197     assert( p->nPgsz>0 || rc!=SQLITE_OK );
109198     sqlite3_free(zSql);
109199     *pRc = rc;
109200   }
109201 }
109202
109203 /*
109204 ** "Special" FTS4 arguments are column specifications of the following form:
109205 **
109206 **   <key> = <value>
109207 **
109208 ** There may not be whitespace surrounding the "=" character. The <value> 
109209 ** term may be quoted, but the <key> may not.
109210 */
109211 static int fts3IsSpecialColumn(
109212   const char *z, 
109213   int *pnKey,
109214   char **pzValue
109215 ){
109216   char *zValue;
109217   const char *zCsr = z;
109218
109219   while( *zCsr!='=' ){
109220     if( *zCsr=='\0' ) return 0;
109221     zCsr++;
109222   }
109223
109224   *pnKey = (int)(zCsr-z);
109225   zValue = sqlite3_mprintf("%s", &zCsr[1]);
109226   if( zValue ){
109227     sqlite3Fts3Dequote(zValue);
109228   }
109229   *pzValue = zValue;
109230   return 1;
109231 }
109232
109233 /*
109234 ** This function is the implementation of both the xConnect and xCreate
109235 ** methods of the FTS3 virtual table.
109236 **
109237 ** The argv[] array contains the following:
109238 **
109239 **   argv[0]   -> module name  ("fts3" or "fts4")
109240 **   argv[1]   -> database name
109241 **   argv[2]   -> table name
109242 **   argv[...] -> "column name" and other module argument fields.
109243 */
109244 static int fts3InitVtab(
109245   int isCreate,                   /* True for xCreate, false for xConnect */
109246   sqlite3 *db,                    /* The SQLite database connection */
109247   void *pAux,                     /* Hash table containing tokenizers */
109248   int argc,                       /* Number of elements in argv array */
109249   const char * const *argv,       /* xCreate/xConnect argument array */
109250   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
109251   char **pzErr                    /* Write any error message here */
109252 ){
109253   Fts3Hash *pHash = (Fts3Hash *)pAux;
109254   Fts3Table *p = 0;               /* Pointer to allocated vtab */
109255   int rc = SQLITE_OK;             /* Return code */
109256   int i;                          /* Iterator variable */
109257   int nByte;                      /* Size of allocation used for *p */
109258   int iCol;                       /* Column index */
109259   int nString = 0;                /* Bytes required to hold all column names */
109260   int nCol = 0;                   /* Number of columns in the FTS table */
109261   char *zCsr;                     /* Space for holding column names */
109262   int nDb;                        /* Bytes required to hold database name */
109263   int nName;                      /* Bytes required to hold table name */
109264   int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
109265   int bNoDocsize = 0;             /* True to omit %_docsize table */
109266   const char **aCol;              /* Array of column names */
109267   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
109268
109269   assert( strlen(argv[0])==4 );
109270   assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
109271        || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
109272   );
109273
109274   nDb = (int)strlen(argv[1]) + 1;
109275   nName = (int)strlen(argv[2]) + 1;
109276
109277   aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) );
109278   if( !aCol ) return SQLITE_NOMEM;
109279   memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
109280
109281   /* Loop through all of the arguments passed by the user to the FTS3/4
109282   ** module (i.e. all the column names and special arguments). This loop
109283   ** does the following:
109284   **
109285   **   + Figures out the number of columns the FTSX table will have, and
109286   **     the number of bytes of space that must be allocated to store copies
109287   **     of the column names.
109288   **
109289   **   + If there is a tokenizer specification included in the arguments,
109290   **     initializes the tokenizer pTokenizer.
109291   */
109292   for(i=3; rc==SQLITE_OK && i<argc; i++){
109293     char const *z = argv[i];
109294     int nKey;
109295     char *zVal;
109296
109297     /* Check if this is a tokenizer specification */
109298     if( !pTokenizer 
109299      && strlen(z)>8
109300      && 0==sqlite3_strnicmp(z, "tokenize", 8) 
109301      && 0==sqlite3Fts3IsIdChar(z[8])
109302     ){
109303       rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
109304     }
109305
109306     /* Check if it is an FTS4 special argument. */
109307     else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
109308       if( !zVal ){
109309         rc = SQLITE_NOMEM;
109310         goto fts3_init_out;
109311       }
109312       if( nKey==9 && 0==sqlite3_strnicmp(z, "matchinfo", 9) ){
109313         if( strlen(zVal)==4 && 0==sqlite3_strnicmp(zVal, "fts3", 4) ){
109314           bNoDocsize = 1;
109315         }else{
109316           *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
109317           rc = SQLITE_ERROR;
109318         }
109319       }else{
109320         *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
109321         rc = SQLITE_ERROR;
109322       }
109323       sqlite3_free(zVal);
109324     }
109325
109326     /* Otherwise, the argument is a column name. */
109327     else {
109328       nString += (int)(strlen(z) + 1);
109329       aCol[nCol++] = z;
109330     }
109331   }
109332   if( rc!=SQLITE_OK ) goto fts3_init_out;
109333
109334   if( nCol==0 ){
109335     assert( nString==0 );
109336     aCol[0] = "content";
109337     nString = 8;
109338     nCol = 1;
109339   }
109340
109341   if( pTokenizer==0 ){
109342     rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
109343     if( rc!=SQLITE_OK ) goto fts3_init_out;
109344   }
109345   assert( pTokenizer );
109346
109347
109348   /* Allocate and populate the Fts3Table structure. */
109349   nByte = sizeof(Fts3Table) +              /* Fts3Table */
109350           nCol * sizeof(char *) +              /* azColumn */
109351           nName +                              /* zName */
109352           nDb +                                /* zDb */
109353           nString;                             /* Space for azColumn strings */
109354   p = (Fts3Table*)sqlite3_malloc(nByte);
109355   if( p==0 ){
109356     rc = SQLITE_NOMEM;
109357     goto fts3_init_out;
109358   }
109359   memset(p, 0, nByte);
109360   p->db = db;
109361   p->nColumn = nCol;
109362   p->nPendingData = 0;
109363   p->azColumn = (char **)&p[1];
109364   p->pTokenizer = pTokenizer;
109365   p->nNodeSize = 1000;
109366   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
109367   p->bHasDocsize = (isFts4 && bNoDocsize==0);
109368   p->bHasStat = isFts4;
109369   fts3HashInit(&p->pendingTerms, FTS3_HASH_STRING, 1);
109370
109371   /* Fill in the zName and zDb fields of the vtab structure. */
109372   zCsr = (char *)&p->azColumn[nCol];
109373   p->zName = zCsr;
109374   memcpy(zCsr, argv[2], nName);
109375   zCsr += nName;
109376   p->zDb = zCsr;
109377   memcpy(zCsr, argv[1], nDb);
109378   zCsr += nDb;
109379
109380   /* Fill in the azColumn array */
109381   for(iCol=0; iCol<nCol; iCol++){
109382     char *z; 
109383     int n;
109384     z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
109385     memcpy(zCsr, z, n);
109386     zCsr[n] = '\0';
109387     sqlite3Fts3Dequote(zCsr);
109388     p->azColumn[iCol] = zCsr;
109389     zCsr += n+1;
109390     assert( zCsr <= &((char *)p)[nByte] );
109391   }
109392
109393   /* If this is an xCreate call, create the underlying tables in the 
109394   ** database. TODO: For xConnect(), it could verify that said tables exist.
109395   */
109396   if( isCreate ){
109397     rc = fts3CreateTables(p);
109398   }
109399
109400   /* Figure out the page-size for the database. This is required in order to
109401   ** estimate the cost of loading large doclists from the database (see 
109402   ** function sqlite3Fts3SegReaderCost() for details).
109403   */
109404   fts3DatabasePageSize(&rc, p);
109405
109406   /* Declare the table schema to SQLite. */
109407   fts3DeclareVtab(&rc, p);
109408
109409 fts3_init_out:
109410
109411   sqlite3_free((void *)aCol);
109412   if( rc!=SQLITE_OK ){
109413     if( p ){
109414       fts3DisconnectMethod((sqlite3_vtab *)p);
109415     }else if( pTokenizer ){
109416       pTokenizer->pModule->xDestroy(pTokenizer);
109417     }
109418   }else{
109419     *ppVTab = &p->base;
109420   }
109421   return rc;
109422 }
109423
109424 /*
109425 ** The xConnect() and xCreate() methods for the virtual table. All the
109426 ** work is done in function fts3InitVtab().
109427 */
109428 static int fts3ConnectMethod(
109429   sqlite3 *db,                    /* Database connection */
109430   void *pAux,                     /* Pointer to tokenizer hash table */
109431   int argc,                       /* Number of elements in argv array */
109432   const char * const *argv,       /* xCreate/xConnect argument array */
109433   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
109434   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
109435 ){
109436   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
109437 }
109438 static int fts3CreateMethod(
109439   sqlite3 *db,                    /* Database connection */
109440   void *pAux,                     /* Pointer to tokenizer hash table */
109441   int argc,                       /* Number of elements in argv array */
109442   const char * const *argv,       /* xCreate/xConnect argument array */
109443   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
109444   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
109445 ){
109446   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
109447 }
109448
109449 /* 
109450 ** Implementation of the xBestIndex method for FTS3 tables. There
109451 ** are three possible strategies, in order of preference:
109452 **
109453 **   1. Direct lookup by rowid or docid. 
109454 **   2. Full-text search using a MATCH operator on a non-docid column.
109455 **   3. Linear scan of %_content table.
109456 */
109457 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
109458   Fts3Table *p = (Fts3Table *)pVTab;
109459   int i;                          /* Iterator variable */
109460   int iCons = -1;                 /* Index of constraint to use */
109461
109462   /* By default use a full table scan. This is an expensive option,
109463   ** so search through the constraints to see if a more efficient 
109464   ** strategy is possible.
109465   */
109466   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
109467   pInfo->estimatedCost = 500000;
109468   for(i=0; i<pInfo->nConstraint; i++){
109469     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
109470     if( pCons->usable==0 ) continue;
109471
109472     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
109473     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
109474      && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
109475     ){
109476       pInfo->idxNum = FTS3_DOCID_SEARCH;
109477       pInfo->estimatedCost = 1.0;
109478       iCons = i;
109479     }
109480
109481     /* A MATCH constraint. Use a full-text search.
109482     **
109483     ** If there is more than one MATCH constraint available, use the first
109484     ** one encountered. If there is both a MATCH constraint and a direct
109485     ** rowid/docid lookup, prefer the MATCH strategy. This is done even 
109486     ** though the rowid/docid lookup is faster than a MATCH query, selecting
109487     ** it would lead to an "unable to use function MATCH in the requested 
109488     ** context" error.
109489     */
109490     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH 
109491      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
109492     ){
109493       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
109494       pInfo->estimatedCost = 2.0;
109495       iCons = i;
109496       break;
109497     }
109498   }
109499
109500   if( iCons>=0 ){
109501     pInfo->aConstraintUsage[iCons].argvIndex = 1;
109502     pInfo->aConstraintUsage[iCons].omit = 1;
109503   } 
109504   return SQLITE_OK;
109505 }
109506
109507 /*
109508 ** Implementation of xOpen method.
109509 */
109510 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
109511   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
109512
109513   UNUSED_PARAMETER(pVTab);
109514
109515   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
109516   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, 
109517   ** if the allocation fails, return SQLITE_NOMEM.
109518   */
109519   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
109520   if( !pCsr ){
109521     return SQLITE_NOMEM;
109522   }
109523   memset(pCsr, 0, sizeof(Fts3Cursor));
109524   return SQLITE_OK;
109525 }
109526
109527 /*
109528 ** Close the cursor.  For additional information see the documentation
109529 ** on the xClose method of the virtual table interface.
109530 */
109531 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
109532   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
109533   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
109534   sqlite3_finalize(pCsr->pStmt);
109535   sqlite3Fts3ExprFree(pCsr->pExpr);
109536   sqlite3Fts3FreeDeferredTokens(pCsr);
109537   sqlite3_free(pCsr->aDoclist);
109538   sqlite3_free(pCsr->aMatchinfo);
109539   sqlite3_free(pCsr);
109540   return SQLITE_OK;
109541 }
109542
109543 /*
109544 ** Position the pCsr->pStmt statement so that it is on the row
109545 ** of the %_content table that contains the last match.  Return
109546 ** SQLITE_OK on success.  
109547 */
109548 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
109549   if( pCsr->isRequireSeek ){
109550     pCsr->isRequireSeek = 0;
109551     sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
109552     if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
109553       return SQLITE_OK;
109554     }else{
109555       int rc = sqlite3_reset(pCsr->pStmt);
109556       if( rc==SQLITE_OK ){
109557         /* If no row was found and no error has occured, then the %_content
109558         ** table is missing a row that is present in the full-text index.
109559         ** The data structures are corrupt.
109560         */
109561         rc = SQLITE_CORRUPT;
109562       }
109563       pCsr->isEof = 1;
109564       if( pContext ){
109565         sqlite3_result_error_code(pContext, rc);
109566       }
109567       return rc;
109568     }
109569   }else{
109570     return SQLITE_OK;
109571   }
109572 }
109573
109574 /*
109575 ** This function is used to process a single interior node when searching
109576 ** a b-tree for a term or term prefix. The node data is passed to this 
109577 ** function via the zNode/nNode parameters. The term to search for is
109578 ** passed in zTerm/nTerm.
109579 **
109580 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
109581 ** of the child node that heads the sub-tree that may contain the term.
109582 **
109583 ** If piLast is not NULL, then *piLast is set to the right-most child node
109584 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
109585 ** a prefix.
109586 **
109587 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
109588 */
109589 static int fts3ScanInteriorNode(
109590   const char *zTerm,              /* Term to select leaves for */
109591   int nTerm,                      /* Size of term zTerm in bytes */
109592   const char *zNode,              /* Buffer containing segment interior node */
109593   int nNode,                      /* Size of buffer at zNode */
109594   sqlite3_int64 *piFirst,         /* OUT: Selected child node */
109595   sqlite3_int64 *piLast           /* OUT: Selected child node */
109596 ){
109597   int rc = SQLITE_OK;             /* Return code */
109598   const char *zCsr = zNode;       /* Cursor to iterate through node */
109599   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
109600   char *zBuffer = 0;              /* Buffer to load terms into */
109601   int nAlloc = 0;                 /* Size of allocated buffer */
109602   int isFirstTerm = 1;            /* True when processing first term on page */
109603   sqlite3_int64 iChild;           /* Block id of child node to descend to */
109604
109605   /* Skip over the 'height' varint that occurs at the start of every 
109606   ** interior node. Then load the blockid of the left-child of the b-tree
109607   ** node into variable iChild.  
109608   **
109609   ** Even if the data structure on disk is corrupted, this (reading two
109610   ** varints from the buffer) does not risk an overread. If zNode is a
109611   ** root node, then the buffer comes from a SELECT statement. SQLite does
109612   ** not make this guarantee explicitly, but in practice there are always
109613   ** either more than 20 bytes of allocated space following the nNode bytes of
109614   ** contents, or two zero bytes. Or, if the node is read from the %_segments
109615   ** table, then there are always 20 bytes of zeroed padding following the
109616   ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
109617   */
109618   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
109619   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
109620   if( zCsr>zEnd ){
109621     return SQLITE_CORRUPT;
109622   }
109623   
109624   while( zCsr<zEnd && (piFirst || piLast) ){
109625     int cmp;                      /* memcmp() result */
109626     int nSuffix;                  /* Size of term suffix */
109627     int nPrefix = 0;              /* Size of term prefix */
109628     int nBuffer;                  /* Total term size */
109629   
109630     /* Load the next term on the node into zBuffer. Use realloc() to expand
109631     ** the size of zBuffer if required.  */
109632     if( !isFirstTerm ){
109633       zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
109634     }
109635     isFirstTerm = 0;
109636     zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
109637     
109638     if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
109639       rc = SQLITE_CORRUPT;
109640       goto finish_scan;
109641     }
109642     if( nPrefix+nSuffix>nAlloc ){
109643       char *zNew;
109644       nAlloc = (nPrefix+nSuffix) * 2;
109645       zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
109646       if( !zNew ){
109647         rc = SQLITE_NOMEM;
109648         goto finish_scan;
109649       }
109650       zBuffer = zNew;
109651     }
109652     memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
109653     nBuffer = nPrefix + nSuffix;
109654     zCsr += nSuffix;
109655
109656     /* Compare the term we are searching for with the term just loaded from
109657     ** the interior node. If the specified term is greater than or equal
109658     ** to the term from the interior node, then all terms on the sub-tree 
109659     ** headed by node iChild are smaller than zTerm. No need to search 
109660     ** iChild.
109661     **
109662     ** If the interior node term is larger than the specified term, then
109663     ** the tree headed by iChild may contain the specified term.
109664     */
109665     cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
109666     if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
109667       *piFirst = iChild;
109668       piFirst = 0;
109669     }
109670
109671     if( piLast && cmp<0 ){
109672       *piLast = iChild;
109673       piLast = 0;
109674     }
109675
109676     iChild++;
109677   };
109678
109679   if( piFirst ) *piFirst = iChild;
109680   if( piLast ) *piLast = iChild;
109681
109682  finish_scan:
109683   sqlite3_free(zBuffer);
109684   return rc;
109685 }
109686
109687
109688 /*
109689 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
109690 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
109691 ** contains a term. This function searches the sub-tree headed by the zNode
109692 ** node for the range of leaf nodes that may contain the specified term
109693 ** or terms for which the specified term is a prefix.
109694 **
109695 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the 
109696 ** left-most leaf node in the tree that may contain the specified term.
109697 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
109698 ** right-most leaf node that may contain a term for which the specified
109699 ** term is a prefix.
109700 **
109701 ** It is possible that the range of returned leaf nodes does not contain 
109702 ** the specified term or any terms for which it is a prefix. However, if the 
109703 ** segment does contain any such terms, they are stored within the identified
109704 ** range. Because this function only inspects interior segment nodes (and
109705 ** never loads leaf nodes into memory), it is not possible to be sure.
109706 **
109707 ** If an error occurs, an error code other than SQLITE_OK is returned.
109708 */ 
109709 static int fts3SelectLeaf(
109710   Fts3Table *p,                   /* Virtual table handle */
109711   const char *zTerm,              /* Term to select leaves for */
109712   int nTerm,                      /* Size of term zTerm in bytes */
109713   const char *zNode,              /* Buffer containing segment interior node */
109714   int nNode,                      /* Size of buffer at zNode */
109715   sqlite3_int64 *piLeaf,          /* Selected leaf node */
109716   sqlite3_int64 *piLeaf2          /* Selected leaf node */
109717 ){
109718   int rc;                         /* Return code */
109719   int iHeight;                    /* Height of this node in tree */
109720
109721   assert( piLeaf || piLeaf2 );
109722
109723   sqlite3Fts3GetVarint32(zNode, &iHeight);
109724   rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
109725   assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
109726
109727   if( rc==SQLITE_OK && iHeight>1 ){
109728     char *zBlob = 0;              /* Blob read from %_segments table */
109729     int nBlob;                    /* Size of zBlob in bytes */
109730
109731     if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
109732       rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob);
109733       if( rc==SQLITE_OK ){
109734         rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
109735       }
109736       sqlite3_free(zBlob);
109737       piLeaf = 0;
109738       zBlob = 0;
109739     }
109740
109741     if( rc==SQLITE_OK ){
109742       rc = sqlite3Fts3ReadBlock(p, piLeaf ? *piLeaf : *piLeaf2, &zBlob, &nBlob);
109743     }
109744     if( rc==SQLITE_OK ){
109745       rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
109746     }
109747     sqlite3_free(zBlob);
109748   }
109749
109750   return rc;
109751 }
109752
109753 /*
109754 ** This function is used to create delta-encoded serialized lists of FTS3 
109755 ** varints. Each call to this function appends a single varint to a list.
109756 */
109757 static void fts3PutDeltaVarint(
109758   char **pp,                      /* IN/OUT: Output pointer */
109759   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
109760   sqlite3_int64 iVal              /* Write this value to the list */
109761 ){
109762   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
109763   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
109764   *piPrev = iVal;
109765 }
109766
109767 /*
109768 ** When this function is called, *ppPoslist is assumed to point to the 
109769 ** start of a position-list. After it returns, *ppPoslist points to the
109770 ** first byte after the position-list.
109771 **
109772 ** A position list is list of positions (delta encoded) and columns for 
109773 ** a single document record of a doclist.  So, in other words, this
109774 ** routine advances *ppPoslist so that it points to the next docid in
109775 ** the doclist, or to the first byte past the end of the doclist.
109776 **
109777 ** If pp is not NULL, then the contents of the position list are copied
109778 ** to *pp. *pp is set to point to the first byte past the last byte copied
109779 ** before this function returns.
109780 */
109781 static void fts3PoslistCopy(char **pp, char **ppPoslist){
109782   char *pEnd = *ppPoslist;
109783   char c = 0;
109784
109785   /* The end of a position list is marked by a zero encoded as an FTS3 
109786   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
109787   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
109788   ** of some other, multi-byte, value.
109789   **
109790   ** The following while-loop moves pEnd to point to the first byte that is not 
109791   ** immediately preceded by a byte with the 0x80 bit set. Then increments
109792   ** pEnd once more so that it points to the byte immediately following the
109793   ** last byte in the position-list.
109794   */
109795   while( *pEnd | c ){
109796     c = *pEnd++ & 0x80;
109797     testcase( c!=0 && (*pEnd)==0 );
109798   }
109799   pEnd++;  /* Advance past the POS_END terminator byte */
109800
109801   if( pp ){
109802     int n = (int)(pEnd - *ppPoslist);
109803     char *p = *pp;
109804     memcpy(p, *ppPoslist, n);
109805     p += n;
109806     *pp = p;
109807   }
109808   *ppPoslist = pEnd;
109809 }
109810
109811 /*
109812 ** When this function is called, *ppPoslist is assumed to point to the 
109813 ** start of a column-list. After it returns, *ppPoslist points to the
109814 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
109815 **
109816 ** A column-list is list of delta-encoded positions for a single column
109817 ** within a single document within a doclist.
109818 **
109819 ** The column-list is terminated either by a POS_COLUMN varint (1) or
109820 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
109821 ** the POS_COLUMN or POS_END that terminates the column-list.
109822 **
109823 ** If pp is not NULL, then the contents of the column-list are copied
109824 ** to *pp. *pp is set to point to the first byte past the last byte copied
109825 ** before this function returns.  The POS_COLUMN or POS_END terminator
109826 ** is not copied into *pp.
109827 */
109828 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
109829   char *pEnd = *ppPoslist;
109830   char c = 0;
109831
109832   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
109833   ** not part of a multi-byte varint.
109834   */
109835   while( 0xFE & (*pEnd | c) ){
109836     c = *pEnd++ & 0x80;
109837     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
109838   }
109839   if( pp ){
109840     int n = (int)(pEnd - *ppPoslist);
109841     char *p = *pp;
109842     memcpy(p, *ppPoslist, n);
109843     p += n;
109844     *pp = p;
109845   }
109846   *ppPoslist = pEnd;
109847 }
109848
109849 /*
109850 ** Value used to signify the end of an position-list. This is safe because
109851 ** it is not possible to have a document with 2^31 terms.
109852 */
109853 #define POSITION_LIST_END 0x7fffffff
109854
109855 /*
109856 ** This function is used to help parse position-lists. When this function is
109857 ** called, *pp may point to the start of the next varint in the position-list
109858 ** being parsed, or it may point to 1 byte past the end of the position-list
109859 ** (in which case **pp will be a terminator bytes POS_END (0) or
109860 ** (1)).
109861 **
109862 ** If *pp points past the end of the current position-list, set *pi to 
109863 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
109864 ** increment the current value of *pi by the value read, and set *pp to
109865 ** point to the next value before returning.
109866 **
109867 ** Before calling this routine *pi must be initialized to the value of
109868 ** the previous position, or zero if we are reading the first position
109869 ** in the position-list.  Because positions are delta-encoded, the value
109870 ** of the previous position is needed in order to compute the value of
109871 ** the next position.
109872 */
109873 static void fts3ReadNextPos(
109874   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
109875   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
109876 ){
109877   if( (**pp)&0xFE ){
109878     fts3GetDeltaVarint(pp, pi);
109879     *pi -= 2;
109880   }else{
109881     *pi = POSITION_LIST_END;
109882   }
109883 }
109884
109885 /*
109886 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
109887 ** the value of iCol encoded as a varint to *pp.   This will start a new
109888 ** column list.
109889 **
109890 ** Set *pp to point to the byte just after the last byte written before 
109891 ** returning (do not modify it if iCol==0). Return the total number of bytes
109892 ** written (0 if iCol==0).
109893 */
109894 static int fts3PutColNumber(char **pp, int iCol){
109895   int n = 0;                      /* Number of bytes written */
109896   if( iCol ){
109897     char *p = *pp;                /* Output pointer */
109898     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
109899     *p = 0x01;
109900     *pp = &p[n];
109901   }
109902   return n;
109903 }
109904
109905 /*
109906 ** Compute the union of two position lists.  The output written
109907 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
109908 ** order and with any duplicates removed.  All pointers are
109909 ** updated appropriately.   The caller is responsible for insuring
109910 ** that there is enough space in *pp to hold the complete output.
109911 */
109912 static void fts3PoslistMerge(
109913   char **pp,                      /* Output buffer */
109914   char **pp1,                     /* Left input list */
109915   char **pp2                      /* Right input list */
109916 ){
109917   char *p = *pp;
109918   char *p1 = *pp1;
109919   char *p2 = *pp2;
109920
109921   while( *p1 || *p2 ){
109922     int iCol1;         /* The current column index in pp1 */
109923     int iCol2;         /* The current column index in pp2 */
109924
109925     if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
109926     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
109927     else iCol1 = 0;
109928
109929     if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
109930     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
109931     else iCol2 = 0;
109932
109933     if( iCol1==iCol2 ){
109934       sqlite3_int64 i1 = 0;       /* Last position from pp1 */
109935       sqlite3_int64 i2 = 0;       /* Last position from pp2 */
109936       sqlite3_int64 iPrev = 0;
109937       int n = fts3PutColNumber(&p, iCol1);
109938       p1 += n;
109939       p2 += n;
109940
109941       /* At this point, both p1 and p2 point to the start of column-lists
109942       ** for the same column (the column with index iCol1 and iCol2).
109943       ** A column-list is a list of non-negative delta-encoded varints, each 
109944       ** incremented by 2 before being stored. Each list is terminated by a
109945       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
109946       ** and writes the results to buffer p. p is left pointing to the byte
109947       ** after the list written. No terminator (POS_END or POS_COLUMN) is
109948       ** written to the output.
109949       */
109950       fts3GetDeltaVarint(&p1, &i1);
109951       fts3GetDeltaVarint(&p2, &i2);
109952       do {
109953         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2); 
109954         iPrev -= 2;
109955         if( i1==i2 ){
109956           fts3ReadNextPos(&p1, &i1);
109957           fts3ReadNextPos(&p2, &i2);
109958         }else if( i1<i2 ){
109959           fts3ReadNextPos(&p1, &i1);
109960         }else{
109961           fts3ReadNextPos(&p2, &i2);
109962         }
109963       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
109964     }else if( iCol1<iCol2 ){
109965       p1 += fts3PutColNumber(&p, iCol1);
109966       fts3ColumnlistCopy(&p, &p1);
109967     }else{
109968       p2 += fts3PutColNumber(&p, iCol2);
109969       fts3ColumnlistCopy(&p, &p2);
109970     }
109971   }
109972
109973   *p++ = POS_END;
109974   *pp = p;
109975   *pp1 = p1 + 1;
109976   *pp2 = p2 + 1;
109977 }
109978
109979 /*
109980 ** nToken==1 searches for adjacent positions.
109981 **
109982 ** This function is used to merge two position lists into one. When it is
109983 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
109984 ** the part of a doclist that follows each document id. For example, if a row
109985 ** contains:
109986 **
109987 **     'a b c'|'x y z'|'a b b a'
109988 **
109989 ** Then the position list for this row for token 'b' would consist of:
109990 **
109991 **     0x02 0x01 0x02 0x03 0x03 0x00
109992 **
109993 ** When this function returns, both *pp1 and *pp2 are left pointing to the
109994 ** byte following the 0x00 terminator of their respective position lists.
109995 **
109996 ** If isSaveLeft is 0, an entry is added to the output position list for 
109997 ** each position in *pp2 for which there exists one or more positions in
109998 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
109999 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
110000 ** slots before it.
110001 */
110002 static int fts3PoslistPhraseMerge(
110003   char **pp,                      /* IN/OUT: Preallocated output buffer */
110004   int nToken,                     /* Maximum difference in token positions */
110005   int isSaveLeft,                 /* Save the left position */
110006   int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
110007   char **pp1,                     /* IN/OUT: Left input list */
110008   char **pp2                      /* IN/OUT: Right input list */
110009 ){
110010   char *p = (pp ? *pp : 0);
110011   char *p1 = *pp1;
110012   char *p2 = *pp2;
110013   int iCol1 = 0;
110014   int iCol2 = 0;
110015
110016   /* Never set both isSaveLeft and isExact for the same invocation. */
110017   assert( isSaveLeft==0 || isExact==0 );
110018
110019   assert( *p1!=0 && *p2!=0 );
110020   if( *p1==POS_COLUMN ){ 
110021     p1++;
110022     p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
110023   }
110024   if( *p2==POS_COLUMN ){ 
110025     p2++;
110026     p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
110027   }
110028
110029   while( 1 ){
110030     if( iCol1==iCol2 ){
110031       char *pSave = p;
110032       sqlite3_int64 iPrev = 0;
110033       sqlite3_int64 iPos1 = 0;
110034       sqlite3_int64 iPos2 = 0;
110035
110036       if( pp && iCol1 ){
110037         *p++ = POS_COLUMN;
110038         p += sqlite3Fts3PutVarint(p, iCol1);
110039       }
110040
110041       assert( *p1!=POS_END && *p1!=POS_COLUMN );
110042       assert( *p2!=POS_END && *p2!=POS_COLUMN );
110043       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
110044       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
110045
110046       while( 1 ){
110047         if( iPos2==iPos1+nToken 
110048          || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) 
110049         ){
110050           sqlite3_int64 iSave;
110051           if( !pp ){
110052             fts3PoslistCopy(0, &p2);
110053             fts3PoslistCopy(0, &p1);
110054             *pp1 = p1;
110055             *pp2 = p2;
110056             return 1;
110057           }
110058           iSave = isSaveLeft ? iPos1 : iPos2;
110059           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
110060           pSave = 0;
110061         }
110062         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
110063           if( (*p2&0xFE)==0 ) break;
110064           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
110065         }else{
110066           if( (*p1&0xFE)==0 ) break;
110067           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
110068         }
110069       }
110070
110071       if( pSave ){
110072         assert( pp && p );
110073         p = pSave;
110074       }
110075
110076       fts3ColumnlistCopy(0, &p1);
110077       fts3ColumnlistCopy(0, &p2);
110078       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
110079       if( 0==*p1 || 0==*p2 ) break;
110080
110081       p1++;
110082       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
110083       p2++;
110084       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
110085     }
110086
110087     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
110088     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
110089     ** end of the position list, or the 0x01 that precedes the next 
110090     ** column-number in the position list. 
110091     */
110092     else if( iCol1<iCol2 ){
110093       fts3ColumnlistCopy(0, &p1);
110094       if( 0==*p1 ) break;
110095       p1++;
110096       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
110097     }else{
110098       fts3ColumnlistCopy(0, &p2);
110099       if( 0==*p2 ) break;
110100       p2++;
110101       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
110102     }
110103   }
110104
110105   fts3PoslistCopy(0, &p2);
110106   fts3PoslistCopy(0, &p1);
110107   *pp1 = p1;
110108   *pp2 = p2;
110109   if( !pp || *pp==p ){
110110     return 0;
110111   }
110112   *p++ = 0x00;
110113   *pp = p;
110114   return 1;
110115 }
110116
110117 /*
110118 ** Merge two position-lists as required by the NEAR operator.
110119 */
110120 static int fts3PoslistNearMerge(
110121   char **pp,                      /* Output buffer */
110122   char *aTmp,                     /* Temporary buffer space */
110123   int nRight,                     /* Maximum difference in token positions */
110124   int nLeft,                      /* Maximum difference in token positions */
110125   char **pp1,                     /* IN/OUT: Left input list */
110126   char **pp2                      /* IN/OUT: Right input list */
110127 ){
110128   char *p1 = *pp1;
110129   char *p2 = *pp2;
110130
110131   if( !pp ){
110132     if( fts3PoslistPhraseMerge(0, nRight, 0, 0, pp1, pp2) ) return 1;
110133     *pp1 = p1;
110134     *pp2 = p2;
110135     return fts3PoslistPhraseMerge(0, nLeft, 0, 0, pp2, pp1);
110136   }else{
110137     char *pTmp1 = aTmp;
110138     char *pTmp2;
110139     char *aTmp2;
110140     int res = 1;
110141
110142     fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
110143     aTmp2 = pTmp2 = pTmp1;
110144     *pp1 = p1;
110145     *pp2 = p2;
110146     fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
110147     if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
110148       fts3PoslistMerge(pp, &aTmp, &aTmp2);
110149     }else if( pTmp1!=aTmp ){
110150       fts3PoslistCopy(pp, &aTmp);
110151     }else if( pTmp2!=aTmp2 ){
110152       fts3PoslistCopy(pp, &aTmp2);
110153     }else{
110154       res = 0;
110155     }
110156
110157     return res;
110158   }
110159 }
110160
110161 /*
110162 ** Values that may be used as the first parameter to fts3DoclistMerge().
110163 */
110164 #define MERGE_NOT        2        /* D + D -> D */
110165 #define MERGE_AND        3        /* D + D -> D */
110166 #define MERGE_OR         4        /* D + D -> D */
110167 #define MERGE_POS_OR     5        /* P + P -> P */
110168 #define MERGE_PHRASE     6        /* P + P -> D */
110169 #define MERGE_POS_PHRASE 7        /* P + P -> P */
110170 #define MERGE_NEAR       8        /* P + P -> D */
110171 #define MERGE_POS_NEAR   9        /* P + P -> P */
110172
110173 /*
110174 ** Merge the two doclists passed in buffer a1 (size n1 bytes) and a2
110175 ** (size n2 bytes). The output is written to pre-allocated buffer aBuffer,
110176 ** which is guaranteed to be large enough to hold the results. The number
110177 ** of bytes written to aBuffer is stored in *pnBuffer before returning.
110178 **
110179 ** If successful, SQLITE_OK is returned. Otherwise, if a malloc error
110180 ** occurs while allocating a temporary buffer as part of the merge operation,
110181 ** SQLITE_NOMEM is returned.
110182 */
110183 static int fts3DoclistMerge(
110184   int mergetype,                  /* One of the MERGE_XXX constants */
110185   int nParam1,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
110186   int nParam2,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
110187   char *aBuffer,                  /* Pre-allocated output buffer */
110188   int *pnBuffer,                  /* OUT: Bytes written to aBuffer */
110189   char *a1,                       /* Buffer containing first doclist */
110190   int n1,                         /* Size of buffer a1 */
110191   char *a2,                       /* Buffer containing second doclist */
110192   int n2,                         /* Size of buffer a2 */
110193   int *pnDoc                      /* OUT: Number of docids in output */
110194 ){
110195   sqlite3_int64 i1 = 0;
110196   sqlite3_int64 i2 = 0;
110197   sqlite3_int64 iPrev = 0;
110198
110199   char *p = aBuffer;
110200   char *p1 = a1;
110201   char *p2 = a2;
110202   char *pEnd1 = &a1[n1];
110203   char *pEnd2 = &a2[n2];
110204   int nDoc = 0;
110205
110206   assert( mergetype==MERGE_OR     || mergetype==MERGE_POS_OR 
110207        || mergetype==MERGE_AND    || mergetype==MERGE_NOT
110208        || mergetype==MERGE_PHRASE || mergetype==MERGE_POS_PHRASE
110209        || mergetype==MERGE_NEAR   || mergetype==MERGE_POS_NEAR
110210   );
110211
110212   if( !aBuffer ){
110213     *pnBuffer = 0;
110214     return SQLITE_NOMEM;
110215   }
110216
110217   /* Read the first docid from each doclist */
110218   fts3GetDeltaVarint2(&p1, pEnd1, &i1);
110219   fts3GetDeltaVarint2(&p2, pEnd2, &i2);
110220
110221   switch( mergetype ){
110222     case MERGE_OR:
110223     case MERGE_POS_OR:
110224       while( p1 || p2 ){
110225         if( p2 && p1 && i1==i2 ){
110226           fts3PutDeltaVarint(&p, &iPrev, i1);
110227           if( mergetype==MERGE_POS_OR ) fts3PoslistMerge(&p, &p1, &p2);
110228           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
110229           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
110230         }else if( !p2 || (p1 && i1<i2) ){
110231           fts3PutDeltaVarint(&p, &iPrev, i1);
110232           if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p1);
110233           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
110234         }else{
110235           fts3PutDeltaVarint(&p, &iPrev, i2);
110236           if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p2);
110237           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
110238         }
110239       }
110240       break;
110241
110242     case MERGE_AND:
110243       while( p1 && p2 ){
110244         if( i1==i2 ){
110245           fts3PutDeltaVarint(&p, &iPrev, i1);
110246           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
110247           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
110248           nDoc++;
110249         }else if( i1<i2 ){
110250           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
110251         }else{
110252           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
110253         }
110254       }
110255       break;
110256
110257     case MERGE_NOT:
110258       while( p1 ){
110259         if( p2 && i1==i2 ){
110260           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
110261           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
110262         }else if( !p2 || i1<i2 ){
110263           fts3PutDeltaVarint(&p, &iPrev, i1);
110264           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
110265         }else{
110266           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
110267         }
110268       }
110269       break;
110270
110271     case MERGE_POS_PHRASE:
110272     case MERGE_PHRASE: {
110273       char **ppPos = (mergetype==MERGE_PHRASE ? 0 : &p);
110274       while( p1 && p2 ){
110275         if( i1==i2 ){
110276           char *pSave = p;
110277           sqlite3_int64 iPrevSave = iPrev;
110278           fts3PutDeltaVarint(&p, &iPrev, i1);
110279           if( 0==fts3PoslistPhraseMerge(ppPos, nParam1, 0, 1, &p1, &p2) ){
110280             p = pSave;
110281             iPrev = iPrevSave;
110282           }else{
110283             nDoc++;
110284           }
110285           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
110286           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
110287         }else if( i1<i2 ){
110288           fts3PoslistCopy(0, &p1);
110289           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
110290         }else{
110291           fts3PoslistCopy(0, &p2);
110292           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
110293         }
110294       }
110295       break;
110296     }
110297
110298     default: assert( mergetype==MERGE_POS_NEAR || mergetype==MERGE_NEAR ); {
110299       char *aTmp = 0;
110300       char **ppPos = 0;
110301
110302       if( mergetype==MERGE_POS_NEAR ){
110303         ppPos = &p;
110304         aTmp = sqlite3_malloc(2*(n1+n2+1));
110305         if( !aTmp ){
110306           return SQLITE_NOMEM;
110307         }
110308       }
110309
110310       while( p1 && p2 ){
110311         if( i1==i2 ){
110312           char *pSave = p;
110313           sqlite3_int64 iPrevSave = iPrev;
110314           fts3PutDeltaVarint(&p, &iPrev, i1);
110315
110316           if( !fts3PoslistNearMerge(ppPos, aTmp, nParam1, nParam2, &p1, &p2) ){
110317             iPrev = iPrevSave;
110318             p = pSave;
110319           }
110320
110321           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
110322           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
110323         }else if( i1<i2 ){
110324           fts3PoslistCopy(0, &p1);
110325           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
110326         }else{
110327           fts3PoslistCopy(0, &p2);
110328           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
110329         }
110330       }
110331       sqlite3_free(aTmp);
110332       break;
110333     }
110334   }
110335
110336   if( pnDoc ) *pnDoc = nDoc;
110337   *pnBuffer = (int)(p-aBuffer);
110338   return SQLITE_OK;
110339 }
110340
110341 /* 
110342 ** A pointer to an instance of this structure is used as the context 
110343 ** argument to sqlite3Fts3SegReaderIterate()
110344 */
110345 typedef struct TermSelect TermSelect;
110346 struct TermSelect {
110347   int isReqPos;
110348   char *aaOutput[16];             /* Malloc'd output buffer */
110349   int anOutput[16];               /* Size of output in bytes */
110350 };
110351
110352 /*
110353 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
110354 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
110355 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
110356 **
110357 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
110358 ** the responsibility of the caller to free any doclists left in the
110359 ** TermSelect.aaOutput[] array.
110360 */
110361 static int fts3TermSelectMerge(TermSelect *pTS){
110362   int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
110363   char *aOut = 0;
110364   int nOut = 0;
110365   int i;
110366
110367   /* Loop through the doclists in the aaOutput[] array. Merge them all
110368   ** into a single doclist.
110369   */
110370   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
110371     if( pTS->aaOutput[i] ){
110372       if( !aOut ){
110373         aOut = pTS->aaOutput[i];
110374         nOut = pTS->anOutput[i];
110375         pTS->aaOutput[i] = 0;
110376       }else{
110377         int nNew = nOut + pTS->anOutput[i];
110378         char *aNew = sqlite3_malloc(nNew);
110379         if( !aNew ){
110380           sqlite3_free(aOut);
110381           return SQLITE_NOMEM;
110382         }
110383         fts3DoclistMerge(mergetype, 0, 0,
110384             aNew, &nNew, pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, 0
110385         );
110386         sqlite3_free(pTS->aaOutput[i]);
110387         sqlite3_free(aOut);
110388         pTS->aaOutput[i] = 0;
110389         aOut = aNew;
110390         nOut = nNew;
110391       }
110392     }
110393   }
110394
110395   pTS->aaOutput[0] = aOut;
110396   pTS->anOutput[0] = nOut;
110397   return SQLITE_OK;
110398 }
110399
110400 /*
110401 ** This function is used as the sqlite3Fts3SegReaderIterate() callback when
110402 ** querying the full-text index for a doclist associated with a term or
110403 ** term-prefix.
110404 */
110405 static int fts3TermSelectCb(
110406   Fts3Table *p,                   /* Virtual table object */
110407   void *pContext,                 /* Pointer to TermSelect structure */
110408   char *zTerm,
110409   int nTerm,
110410   char *aDoclist,
110411   int nDoclist
110412 ){
110413   TermSelect *pTS = (TermSelect *)pContext;
110414
110415   UNUSED_PARAMETER(p);
110416   UNUSED_PARAMETER(zTerm);
110417   UNUSED_PARAMETER(nTerm);
110418
110419   if( pTS->aaOutput[0]==0 ){
110420     /* If this is the first term selected, copy the doclist to the output
110421     ** buffer using memcpy(). TODO: Add a way to transfer control of the
110422     ** aDoclist buffer from the caller so as to avoid the memcpy().
110423     */
110424     pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
110425     pTS->anOutput[0] = nDoclist;
110426     if( pTS->aaOutput[0] ){
110427       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
110428     }else{
110429       return SQLITE_NOMEM;
110430     }
110431   }else{
110432     int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
110433     char *aMerge = aDoclist;
110434     int nMerge = nDoclist;
110435     int iOut;
110436
110437     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
110438       char *aNew;
110439       int nNew;
110440       if( pTS->aaOutput[iOut]==0 ){
110441         assert( iOut>0 );
110442         pTS->aaOutput[iOut] = aMerge;
110443         pTS->anOutput[iOut] = nMerge;
110444         break;
110445       }
110446
110447       nNew = nMerge + pTS->anOutput[iOut];
110448       aNew = sqlite3_malloc(nNew);
110449       if( !aNew ){
110450         if( aMerge!=aDoclist ){
110451           sqlite3_free(aMerge);
110452         }
110453         return SQLITE_NOMEM;
110454       }
110455       fts3DoclistMerge(mergetype, 0, 0, aNew, &nNew, 
110456           pTS->aaOutput[iOut], pTS->anOutput[iOut], aMerge, nMerge, 0
110457       );
110458
110459       if( iOut>0 ) sqlite3_free(aMerge);
110460       sqlite3_free(pTS->aaOutput[iOut]);
110461       pTS->aaOutput[iOut] = 0;
110462
110463       aMerge = aNew;
110464       nMerge = nNew;
110465       if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
110466         pTS->aaOutput[iOut] = aMerge;
110467         pTS->anOutput[iOut] = nMerge;
110468       }
110469     }
110470   }
110471   return SQLITE_OK;
110472 }
110473
110474 static int fts3DeferredTermSelect(
110475   Fts3DeferredToken *pToken,      /* Phrase token */
110476   int isTermPos,                  /* True to include positions */
110477   int *pnOut,                     /* OUT: Size of list */
110478   char **ppOut                    /* OUT: Body of list */
110479 ){
110480   char *aSource;
110481   int nSource;
110482
110483   aSource = sqlite3Fts3DeferredDoclist(pToken, &nSource);
110484   if( !aSource ){
110485     *pnOut = 0;
110486     *ppOut = 0;
110487   }else if( isTermPos ){
110488     *ppOut = sqlite3_malloc(nSource);
110489     if( !*ppOut ) return SQLITE_NOMEM;
110490     memcpy(*ppOut, aSource, nSource);
110491     *pnOut = nSource;
110492   }else{
110493     sqlite3_int64 docid;
110494     *pnOut = sqlite3Fts3GetVarint(aSource, &docid);
110495     *ppOut = sqlite3_malloc(*pnOut);
110496     if( !*ppOut ) return SQLITE_NOMEM;
110497     sqlite3Fts3PutVarint(*ppOut, docid);
110498   }
110499
110500   return SQLITE_OK;
110501 }
110502
110503 /*
110504 ** An Fts3SegReaderArray is used to store an array of Fts3SegReader objects.
110505 ** Elements are added to the array using fts3SegReaderArrayAdd(). 
110506 */
110507 struct Fts3SegReaderArray {
110508   int nSegment;                   /* Number of valid entries in apSegment[] */
110509   int nAlloc;                     /* Allocated size of apSegment[] */
110510   int nCost;                      /* The cost of executing SegReaderIterate() */
110511   Fts3SegReader *apSegment[1];    /* Array of seg-reader objects */
110512 };
110513
110514
110515 /*
110516 ** Free an Fts3SegReaderArray object. Also free all seg-readers in the
110517 ** array (using sqlite3Fts3SegReaderFree()).
110518 */
110519 static void fts3SegReaderArrayFree(Fts3SegReaderArray *pArray){
110520   if( pArray ){
110521     int i;
110522     for(i=0; i<pArray->nSegment; i++){
110523       sqlite3Fts3SegReaderFree(pArray->apSegment[i]);
110524     }
110525     sqlite3_free(pArray);
110526   }
110527 }
110528
110529 static int fts3SegReaderArrayAdd(
110530   Fts3SegReaderArray **ppArray, 
110531   Fts3SegReader *pNew
110532 ){
110533   Fts3SegReaderArray *pArray = *ppArray;
110534
110535   if( !pArray || pArray->nAlloc==pArray->nSegment ){
110536     int nNew = (pArray ? pArray->nAlloc+16 : 16);
110537     pArray = (Fts3SegReaderArray *)sqlite3_realloc(pArray, 
110538         sizeof(Fts3SegReaderArray) + (nNew-1) * sizeof(Fts3SegReader*)
110539     );
110540     if( !pArray ){
110541       sqlite3Fts3SegReaderFree(pNew);
110542       return SQLITE_NOMEM;
110543     }
110544     if( nNew==16 ){
110545       pArray->nSegment = 0;
110546       pArray->nCost = 0;
110547     }
110548     pArray->nAlloc = nNew;
110549     *ppArray = pArray;
110550   }
110551
110552   pArray->apSegment[pArray->nSegment++] = pNew;
110553   return SQLITE_OK;
110554 }
110555
110556 static int fts3TermSegReaderArray(
110557   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
110558   const char *zTerm,              /* Term to query for */
110559   int nTerm,                      /* Size of zTerm in bytes */
110560   int isPrefix,                   /* True for a prefix search */
110561   Fts3SegReaderArray **ppArray    /* OUT: Allocated seg-reader array */
110562 ){
110563   Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
110564   int rc;                         /* Return code */
110565   Fts3SegReaderArray *pArray = 0; /* Array object to build */
110566   Fts3SegReader *pReader = 0;     /* Seg-reader to add to pArray */ 
110567   sqlite3_stmt *pStmt = 0;        /* SQL statement to scan %_segdir table */
110568   int iAge = 0;                   /* Used to assign ages to segments */
110569
110570   /* Allocate a seg-reader to scan the pending terms, if any. */
110571   rc = sqlite3Fts3SegReaderPending(p, zTerm, nTerm, isPrefix, &pReader);
110572   if( rc==SQLITE_OK && pReader ) {
110573     rc = fts3SegReaderArrayAdd(&pArray, pReader);
110574   }
110575
110576   /* Loop through the entire %_segdir table. For each segment, create a
110577   ** Fts3SegReader to iterate through the subset of the segment leaves
110578   ** that may contain a term that matches zTerm/nTerm. For non-prefix
110579   ** searches, this is always a single leaf. For prefix searches, this
110580   ** may be a contiguous block of leaves.
110581   */
110582   if( rc==SQLITE_OK ){
110583     rc = sqlite3Fts3AllSegdirs(p, &pStmt);
110584   }
110585   while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
110586     Fts3SegReader *pNew = 0;
110587     int nRoot = sqlite3_column_bytes(pStmt, 4);
110588     char const *zRoot = sqlite3_column_blob(pStmt, 4);
110589     if( sqlite3_column_int64(pStmt, 1)==0 ){
110590       /* The entire segment is stored on the root node (which must be a
110591       ** leaf). Do not bother inspecting any data in this case, just
110592       ** create a Fts3SegReader to scan the single leaf. 
110593       */
110594       rc = sqlite3Fts3SegReaderNew(iAge, 0, 0, 0, zRoot, nRoot, &pNew);
110595     }else{
110596       sqlite3_int64 i1;           /* First leaf that may contain zTerm */
110597       sqlite3_int64 i2;           /* Final leaf that may contain zTerm */
110598       rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &i1, (isPrefix?&i2:0));
110599       if( isPrefix==0 ) i2 = i1;
110600       if( rc==SQLITE_OK ){
110601         rc = sqlite3Fts3SegReaderNew(iAge, i1, i2, 0, 0, 0, &pNew);
110602       }
110603     }
110604     assert( (pNew==0)==(rc!=SQLITE_OK) );
110605
110606     /* If a new Fts3SegReader was allocated, add it to the array. */
110607     if( rc==SQLITE_OK ){
110608       rc = fts3SegReaderArrayAdd(&pArray, pNew);
110609     }
110610     if( rc==SQLITE_OK ){
110611       rc = sqlite3Fts3SegReaderCost(pCsr, pNew, &pArray->nCost);
110612     }
110613     iAge++;
110614   }
110615
110616   if( rc==SQLITE_DONE ){
110617     rc = sqlite3_reset(pStmt);
110618   }else{
110619     sqlite3_reset(pStmt);
110620   }
110621   if( rc!=SQLITE_OK ){
110622     fts3SegReaderArrayFree(pArray);
110623     pArray = 0;
110624   }
110625   *ppArray = pArray;
110626   return rc;
110627 }
110628
110629 /*
110630 ** This function retreives the doclist for the specified term (or term
110631 ** prefix) from the database. 
110632 **
110633 ** The returned doclist may be in one of two formats, depending on the 
110634 ** value of parameter isReqPos. If isReqPos is zero, then the doclist is
110635 ** a sorted list of delta-compressed docids (a bare doclist). If isReqPos
110636 ** is non-zero, then the returned list is in the same format as is stored 
110637 ** in the database without the found length specifier at the start of on-disk
110638 ** doclists.
110639 */
110640 static int fts3TermSelect(
110641   Fts3Table *p,                   /* Virtual table handle */
110642   Fts3PhraseToken *pTok,          /* Token to query for */
110643   int iColumn,                    /* Column to query (or -ve for all columns) */
110644   int isReqPos,                   /* True to include position lists in output */
110645   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
110646   char **ppOut                    /* OUT: Malloced result buffer */
110647 ){
110648   int rc;                         /* Return code */
110649   Fts3SegReaderArray *pArray;     /* Seg-reader array for this term */
110650   TermSelect tsc;               /* Context object for fts3TermSelectCb() */
110651   Fts3SegFilter filter;         /* Segment term filter configuration */
110652
110653   pArray = pTok->pArray;
110654   memset(&tsc, 0, sizeof(TermSelect));
110655   tsc.isReqPos = isReqPos;
110656
110657   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY 
110658         | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
110659         | (isReqPos ? FTS3_SEGMENT_REQUIRE_POS : 0)
110660         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
110661   filter.iCol = iColumn;
110662   filter.zTerm = pTok->z;
110663   filter.nTerm = pTok->n;
110664
110665   rc = sqlite3Fts3SegReaderIterate(p, pArray->apSegment, pArray->nSegment, 
110666       &filter, fts3TermSelectCb, (void *)&tsc
110667   );
110668   if( rc==SQLITE_OK ){
110669     rc = fts3TermSelectMerge(&tsc);
110670   }
110671
110672   if( rc==SQLITE_OK ){
110673     *ppOut = tsc.aaOutput[0];
110674     *pnOut = tsc.anOutput[0];
110675   }else{
110676     int i;
110677     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
110678       sqlite3_free(tsc.aaOutput[i]);
110679     }
110680   }
110681
110682   fts3SegReaderArrayFree(pArray);
110683   pTok->pArray = 0;
110684   return rc;
110685 }
110686
110687 /*
110688 ** This function counts the total number of docids in the doclist stored
110689 ** in buffer aList[], size nList bytes.
110690 **
110691 ** If the isPoslist argument is true, then it is assumed that the doclist
110692 ** contains a position-list following each docid. Otherwise, it is assumed
110693 ** that the doclist is simply a list of docids stored as delta encoded 
110694 ** varints.
110695 */
110696 static int fts3DoclistCountDocids(int isPoslist, char *aList, int nList){
110697   int nDoc = 0;                   /* Return value */
110698   if( aList ){
110699     char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
110700     char *p = aList;              /* Cursor */
110701     if( !isPoslist ){
110702       /* The number of docids in the list is the same as the number of 
110703       ** varints. In FTS3 a varint consists of a single byte with the 0x80 
110704       ** bit cleared and zero or more bytes with the 0x80 bit set. So to
110705       ** count the varints in the buffer, just count the number of bytes
110706       ** with the 0x80 bit clear.  */
110707       while( p<aEnd ) nDoc += (((*p++)&0x80)==0);
110708     }else{
110709       while( p<aEnd ){
110710         nDoc++;
110711         while( (*p++)&0x80 );     /* Skip docid varint */
110712         fts3PoslistCopy(0, &p);   /* Skip over position list */
110713       }
110714     }
110715   }
110716
110717   return nDoc;
110718 }
110719
110720 /*
110721 ** Call sqlite3Fts3DeferToken() for each token in the expression pExpr.
110722 */
110723 static int fts3DeferExpression(Fts3Cursor *pCsr, Fts3Expr *pExpr){
110724   int rc = SQLITE_OK;
110725   if( pExpr ){
110726     rc = fts3DeferExpression(pCsr, pExpr->pLeft);
110727     if( rc==SQLITE_OK ){
110728       rc = fts3DeferExpression(pCsr, pExpr->pRight);
110729     }
110730     if( pExpr->eType==FTSQUERY_PHRASE ){
110731       int iCol = pExpr->pPhrase->iColumn;
110732       int i;
110733       for(i=0; rc==SQLITE_OK && i<pExpr->pPhrase->nToken; i++){
110734         Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
110735         if( pToken->pDeferred==0 ){
110736           rc = sqlite3Fts3DeferToken(pCsr, pToken, iCol);
110737         }
110738       }
110739     }
110740   }
110741   return rc;
110742 }
110743
110744 /*
110745 ** This function removes the position information from a doclist. When
110746 ** called, buffer aList (size *pnList bytes) contains a doclist that includes
110747 ** position information. This function removes the position information so
110748 ** that aList contains only docids, and adjusts *pnList to reflect the new
110749 ** (possibly reduced) size of the doclist.
110750 */
110751 static void fts3DoclistStripPositions(
110752   char *aList,                    /* IN/OUT: Buffer containing doclist */
110753   int *pnList                     /* IN/OUT: Size of doclist in bytes */
110754 ){
110755   if( aList ){
110756     char *aEnd = &aList[*pnList]; /* Pointer to one byte after EOF */
110757     char *p = aList;              /* Input cursor */
110758     char *pOut = aList;           /* Output cursor */
110759   
110760     while( p<aEnd ){
110761       sqlite3_int64 delta;
110762       p += sqlite3Fts3GetVarint(p, &delta);
110763       fts3PoslistCopy(0, &p);
110764       pOut += sqlite3Fts3PutVarint(pOut, delta);
110765     }
110766
110767     *pnList = (int)(pOut - aList);
110768   }
110769 }
110770
110771 /* 
110772 ** Return a DocList corresponding to the phrase *pPhrase.
110773 **
110774 ** If this function returns SQLITE_OK, but *pnOut is set to a negative value,
110775 ** then no tokens in the phrase were looked up in the full-text index. This
110776 ** is only possible when this function is called from within xFilter(). The
110777 ** caller should assume that all documents match the phrase. The actual
110778 ** filtering will take place in xNext().
110779 */
110780 static int fts3PhraseSelect(
110781   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
110782   Fts3Phrase *pPhrase,            /* Phrase to return a doclist for */
110783   int isReqPos,                   /* True if output should contain positions */
110784   char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
110785   int *pnOut                      /* OUT: Size of buffer at *paOut */
110786 ){
110787   char *pOut = 0;
110788   int nOut = 0;
110789   int rc = SQLITE_OK;
110790   int ii;
110791   int iCol = pPhrase->iColumn;
110792   int isTermPos = (pPhrase->nToken>1 || isReqPos);
110793   Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
110794   int isFirst = 1;
110795
110796   int iPrevTok = 0;
110797   int nDoc = 0;
110798
110799   /* If this is an xFilter() evaluation, create a segment-reader for each
110800   ** phrase token. Or, if this is an xNext() or snippet/offsets/matchinfo
110801   ** evaluation, only create segment-readers if there are no Fts3DeferredToken
110802   ** objects attached to the phrase-tokens.
110803   */
110804   for(ii=0; ii<pPhrase->nToken; ii++){
110805     Fts3PhraseToken *pTok = &pPhrase->aToken[ii];
110806     if( pTok->pArray==0 ){
110807       if( (pCsr->eEvalmode==FTS3_EVAL_FILTER)
110808        || (pCsr->eEvalmode==FTS3_EVAL_NEXT && pCsr->pDeferred==0) 
110809        || (pCsr->eEvalmode==FTS3_EVAL_MATCHINFO && pTok->bFulltext) 
110810       ){
110811         rc = fts3TermSegReaderArray(
110812             pCsr, pTok->z, pTok->n, pTok->isPrefix, &pTok->pArray
110813         );
110814         if( rc!=SQLITE_OK ) return rc;
110815       }
110816     }
110817   }
110818
110819   for(ii=0; ii<pPhrase->nToken; ii++){
110820     Fts3PhraseToken *pTok;        /* Token to find doclist for */
110821     int iTok = 0;                 /* The token being queried this iteration */
110822     char *pList = 0;              /* Pointer to token doclist */
110823     int nList = 0;                /* Size of buffer at pList */
110824
110825     /* Select a token to process. If this is an xFilter() call, then tokens 
110826     ** are processed in order from least to most costly. Otherwise, tokens 
110827     ** are processed in the order in which they occur in the phrase.
110828     */
110829     if( pCsr->eEvalmode==FTS3_EVAL_MATCHINFO ){
110830       assert( isReqPos );
110831       iTok = ii;
110832       pTok = &pPhrase->aToken[iTok];
110833       if( pTok->bFulltext==0 ) continue;
110834     }else if( pCsr->eEvalmode==FTS3_EVAL_NEXT || isReqPos ){
110835       iTok = ii;
110836       pTok = &pPhrase->aToken[iTok];
110837     }else{
110838       int nMinCost = 0x7FFFFFFF;
110839       int jj;
110840
110841       /* Find the remaining token with the lowest cost. */
110842       for(jj=0; jj<pPhrase->nToken; jj++){
110843         Fts3SegReaderArray *pArray = pPhrase->aToken[jj].pArray;
110844         if( pArray && pArray->nCost<nMinCost ){
110845           iTok = jj;
110846           nMinCost = pArray->nCost;
110847         }
110848       }
110849       pTok = &pPhrase->aToken[iTok];
110850
110851       /* This branch is taken if it is determined that loading the doclist
110852       ** for the next token would require more IO than loading all documents
110853       ** currently identified by doclist pOut/nOut. No further doclists will
110854       ** be loaded from the full-text index for this phrase.
110855       */
110856       if( nMinCost>nDoc && ii>0 ){
110857         rc = fts3DeferExpression(pCsr, pCsr->pExpr);
110858         break;
110859       }
110860     }
110861
110862     if( pCsr->eEvalmode==FTS3_EVAL_NEXT && pTok->pDeferred ){
110863       rc = fts3DeferredTermSelect(pTok->pDeferred, isTermPos, &nList, &pList);
110864     }else{
110865       if( pTok->pArray ){
110866         rc = fts3TermSelect(p, pTok, iCol, isTermPos, &nList, &pList);
110867       }
110868       pTok->bFulltext = 1;
110869     }
110870     assert( rc!=SQLITE_OK || pCsr->eEvalmode || pTok->pArray==0 );
110871     if( rc!=SQLITE_OK ) break;
110872
110873     if( isFirst ){
110874       pOut = pList;
110875       nOut = nList;
110876       if( pCsr->eEvalmode==FTS3_EVAL_FILTER && pPhrase->nToken>1 ){
110877         nDoc = fts3DoclistCountDocids(1, pOut, nOut);
110878       }
110879       isFirst = 0;
110880       iPrevTok = iTok;
110881     }else{
110882       /* Merge the new term list and the current output. */
110883       char *aLeft, *aRight;
110884       int nLeft, nRight;
110885       int nDist;
110886       int mt;
110887
110888       /* If this is the final token of the phrase, and positions were not
110889       ** requested by the caller, use MERGE_PHRASE instead of POS_PHRASE.
110890       ** This drops the position information from the output list.
110891       */
110892       mt = MERGE_POS_PHRASE;
110893       if( ii==pPhrase->nToken-1 && !isReqPos ) mt = MERGE_PHRASE;
110894
110895       assert( iPrevTok!=iTok );
110896       if( iPrevTok<iTok ){
110897         aLeft = pOut;
110898         nLeft = nOut;
110899         aRight = pList;
110900         nRight = nList;
110901         nDist = iTok-iPrevTok;
110902         iPrevTok = iTok;
110903       }else{
110904         aRight = pOut;
110905         nRight = nOut;
110906         aLeft = pList;
110907         nLeft = nList;
110908         nDist = iPrevTok-iTok;
110909       }
110910       pOut = aRight;
110911       fts3DoclistMerge(
110912           mt, nDist, 0, pOut, &nOut, aLeft, nLeft, aRight, nRight, &nDoc
110913       );
110914       sqlite3_free(aLeft);
110915     }
110916     assert( nOut==0 || pOut!=0 );
110917   }
110918
110919   if( rc==SQLITE_OK ){
110920     if( ii!=pPhrase->nToken ){
110921       assert( pCsr->eEvalmode==FTS3_EVAL_FILTER && isReqPos==0 );
110922       fts3DoclistStripPositions(pOut, &nOut);
110923     }
110924     *paOut = pOut;
110925     *pnOut = nOut;
110926   }else{
110927     sqlite3_free(pOut);
110928   }
110929   return rc;
110930 }
110931
110932 /*
110933 ** This function merges two doclists according to the requirements of a
110934 ** NEAR operator.
110935 **
110936 ** Both input doclists must include position information. The output doclist 
110937 ** includes position information if the first argument to this function
110938 ** is MERGE_POS_NEAR, or does not if it is MERGE_NEAR.
110939 */
110940 static int fts3NearMerge(
110941   int mergetype,                  /* MERGE_POS_NEAR or MERGE_NEAR */
110942   int nNear,                      /* Parameter to NEAR operator */
110943   int nTokenLeft,                 /* Number of tokens in LHS phrase arg */
110944   char *aLeft,                    /* Doclist for LHS (incl. positions) */
110945   int nLeft,                      /* Size of LHS doclist in bytes */
110946   int nTokenRight,                /* As nTokenLeft */
110947   char *aRight,                   /* As aLeft */
110948   int nRight,                     /* As nRight */
110949   char **paOut,                   /* OUT: Results of merge (malloced) */
110950   int *pnOut                      /* OUT: Sized of output buffer */
110951 ){
110952   char *aOut;                     /* Buffer to write output doclist to */
110953   int rc;                         /* Return code */
110954
110955   assert( mergetype==MERGE_POS_NEAR || MERGE_NEAR );
110956
110957   aOut = sqlite3_malloc(nLeft+nRight+1);
110958   if( aOut==0 ){
110959     rc = SQLITE_NOMEM;
110960   }else{
110961     rc = fts3DoclistMerge(mergetype, nNear+nTokenRight, nNear+nTokenLeft, 
110962       aOut, pnOut, aLeft, nLeft, aRight, nRight, 0
110963     );
110964     if( rc!=SQLITE_OK ){
110965       sqlite3_free(aOut);
110966       aOut = 0;
110967     }
110968   }
110969
110970   *paOut = aOut;
110971   return rc;
110972 }
110973
110974 /*
110975 ** This function is used as part of the processing for the snippet() and
110976 ** offsets() functions.
110977 **
110978 ** Both pLeft and pRight are expression nodes of type FTSQUERY_PHRASE. Both
110979 ** have their respective doclists (including position information) loaded
110980 ** in Fts3Expr.aDoclist/nDoclist. This function removes all entries from
110981 ** each doclist that are not within nNear tokens of a corresponding entry
110982 ** in the other doclist.
110983 */
110984 SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *pLeft, Fts3Expr *pRight, int nNear){
110985   int rc;                         /* Return code */
110986
110987   assert( pLeft->eType==FTSQUERY_PHRASE );
110988   assert( pRight->eType==FTSQUERY_PHRASE );
110989   assert( pLeft->isLoaded && pRight->isLoaded );
110990
110991   if( pLeft->aDoclist==0 || pRight->aDoclist==0 ){
110992     sqlite3_free(pLeft->aDoclist);
110993     sqlite3_free(pRight->aDoclist);
110994     pRight->aDoclist = 0;
110995     pLeft->aDoclist = 0;
110996     rc = SQLITE_OK;
110997   }else{
110998     char *aOut;                   /* Buffer in which to assemble new doclist */
110999     int nOut;                     /* Size of buffer aOut in bytes */
111000
111001     rc = fts3NearMerge(MERGE_POS_NEAR, nNear, 
111002         pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
111003         pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
111004         &aOut, &nOut
111005     );
111006     if( rc!=SQLITE_OK ) return rc;
111007     sqlite3_free(pRight->aDoclist);
111008     pRight->aDoclist = aOut;
111009     pRight->nDoclist = nOut;
111010
111011     rc = fts3NearMerge(MERGE_POS_NEAR, nNear, 
111012         pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
111013         pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
111014         &aOut, &nOut
111015     );
111016     sqlite3_free(pLeft->aDoclist);
111017     pLeft->aDoclist = aOut;
111018     pLeft->nDoclist = nOut;
111019   }
111020   return rc;
111021 }
111022
111023
111024 /*
111025 ** Allocate an Fts3SegReaderArray for each token in the expression pExpr. 
111026 ** The allocated objects are stored in the Fts3PhraseToken.pArray member
111027 ** variables of each token structure.
111028 */
111029 static int fts3ExprAllocateSegReaders(
111030   Fts3Cursor *pCsr,               /* FTS3 table */
111031   Fts3Expr *pExpr,                /* Expression to create seg-readers for */
111032   int *pnExpr                     /* OUT: Number of AND'd expressions */
111033 ){
111034   int rc = SQLITE_OK;             /* Return code */
111035
111036   assert( pCsr->eEvalmode==FTS3_EVAL_FILTER );
111037   if( pnExpr && pExpr->eType!=FTSQUERY_AND ){
111038     (*pnExpr)++;
111039     pnExpr = 0;
111040   }
111041
111042   if( pExpr->eType==FTSQUERY_PHRASE ){
111043     Fts3Phrase *pPhrase = pExpr->pPhrase;
111044     int ii;
111045
111046     for(ii=0; rc==SQLITE_OK && ii<pPhrase->nToken; ii++){
111047       Fts3PhraseToken *pTok = &pPhrase->aToken[ii];
111048       if( pTok->pArray==0 ){
111049         rc = fts3TermSegReaderArray(
111050             pCsr, pTok->z, pTok->n, pTok->isPrefix, &pTok->pArray
111051         );
111052       }
111053     }
111054   }else{ 
111055     rc = fts3ExprAllocateSegReaders(pCsr, pExpr->pLeft, pnExpr);
111056     if( rc==SQLITE_OK ){
111057       rc = fts3ExprAllocateSegReaders(pCsr, pExpr->pRight, pnExpr);
111058     }
111059   }
111060   return rc;
111061 }
111062
111063 /*
111064 ** Free the Fts3SegReaderArray objects associated with each token in the
111065 ** expression pExpr. In other words, this function frees the resources
111066 ** allocated by fts3ExprAllocateSegReaders().
111067 */
111068 static void fts3ExprFreeSegReaders(Fts3Expr *pExpr){
111069   if( pExpr ){
111070     Fts3Phrase *pPhrase = pExpr->pPhrase;
111071     if( pPhrase ){
111072       int kk;
111073       for(kk=0; kk<pPhrase->nToken; kk++){
111074         fts3SegReaderArrayFree(pPhrase->aToken[kk].pArray);
111075         pPhrase->aToken[kk].pArray = 0;
111076       }
111077     }
111078     fts3ExprFreeSegReaders(pExpr->pLeft);
111079     fts3ExprFreeSegReaders(pExpr->pRight);
111080   }
111081 }
111082
111083 /*
111084 ** Return the sum of the costs of all tokens in the expression pExpr. This
111085 ** function must be called after Fts3SegReaderArrays have been allocated
111086 ** for all tokens using fts3ExprAllocateSegReaders().
111087 */
111088 static int fts3ExprCost(Fts3Expr *pExpr){
111089   int nCost;                      /* Return value */
111090   if( pExpr->eType==FTSQUERY_PHRASE ){
111091     Fts3Phrase *pPhrase = pExpr->pPhrase;
111092     int ii;
111093     nCost = 0;
111094     for(ii=0; ii<pPhrase->nToken; ii++){
111095       Fts3SegReaderArray *pArray = pPhrase->aToken[ii].pArray;
111096       if( pArray ){
111097         nCost += pPhrase->aToken[ii].pArray->nCost;
111098       }
111099     }
111100   }else{
111101     nCost = fts3ExprCost(pExpr->pLeft) + fts3ExprCost(pExpr->pRight);
111102   }
111103   return nCost;
111104 }
111105
111106 /*
111107 ** The following is a helper function (and type) for fts3EvalExpr(). It
111108 ** must be called after Fts3SegReaders have been allocated for every token
111109 ** in the expression. See the context it is called from in fts3EvalExpr()
111110 ** for further explanation.
111111 */
111112 typedef struct ExprAndCost ExprAndCost;
111113 struct ExprAndCost {
111114   Fts3Expr *pExpr;
111115   int nCost;
111116 };
111117 static void fts3ExprAssignCosts(
111118   Fts3Expr *pExpr,                /* Expression to create seg-readers for */
111119   ExprAndCost **ppExprCost        /* OUT: Write to *ppExprCost */
111120 ){
111121   if( pExpr->eType==FTSQUERY_AND ){
111122     fts3ExprAssignCosts(pExpr->pLeft, ppExprCost);
111123     fts3ExprAssignCosts(pExpr->pRight, ppExprCost);
111124   }else{
111125     (*ppExprCost)->pExpr = pExpr;
111126     (*ppExprCost)->nCost = fts3ExprCost(pExpr);
111127     (*ppExprCost)++;
111128   }
111129 }
111130
111131 /*
111132 ** Evaluate the full-text expression pExpr against FTS3 table pTab. Store
111133 ** the resulting doclist in *paOut and *pnOut. This routine mallocs for
111134 ** the space needed to store the output. The caller is responsible for
111135 ** freeing the space when it has finished.
111136 **
111137 ** This function is called in two distinct contexts:
111138 **
111139 **   * From within the virtual table xFilter() method. In this case, the
111140 **     output doclist contains entries for all rows in the table, based on
111141 **     data read from the full-text index.
111142 **
111143 **     In this case, if the query expression contains one or more tokens that 
111144 **     are very common, then the returned doclist may contain a superset of 
111145 **     the documents that actually match the expression.
111146 **
111147 **   * From within the virtual table xNext() method. This call is only made
111148 **     if the call from within xFilter() found that there were very common 
111149 **     tokens in the query expression and did return a superset of the 
111150 **     matching documents. In this case the returned doclist contains only
111151 **     entries that correspond to the current row of the table. Instead of
111152 **     reading the data for each token from the full-text index, the data is
111153 **     already available in-memory in the Fts3PhraseToken.pDeferred structures.
111154 **     See fts3EvalDeferred() for how it gets there.
111155 **
111156 ** In the first case above, Fts3Cursor.doDeferred==0. In the second (if it is
111157 ** required) Fts3Cursor.doDeferred==1.
111158 **
111159 ** If the SQLite invokes the snippet(), offsets() or matchinfo() function
111160 ** as part of a SELECT on an FTS3 table, this function is called on each
111161 ** individual phrase expression in the query. If there were very common tokens
111162 ** found in the xFilter() call, then this function is called once for phrase
111163 ** for each row visited, and the returned doclist contains entries for the
111164 ** current row only. Otherwise, if there were no very common tokens, then this
111165 ** function is called once only for each phrase in the query and the returned
111166 ** doclist contains entries for all rows of the table.
111167 **
111168 ** Fts3Cursor.doDeferred==1 when this function is called on phrases as a
111169 ** result of a snippet(), offsets() or matchinfo() invocation.
111170 */
111171 static int fts3EvalExpr(
111172   Fts3Cursor *p,                  /* Virtual table cursor handle */
111173   Fts3Expr *pExpr,                /* Parsed fts3 expression */
111174   char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
111175   int *pnOut,                     /* OUT: Size of buffer at *paOut */
111176   int isReqPos                    /* Require positions in output buffer */
111177 ){
111178   int rc = SQLITE_OK;             /* Return code */
111179
111180   /* Zero the output parameters. */
111181   *paOut = 0;
111182   *pnOut = 0;
111183
111184   if( pExpr ){
111185     assert( pExpr->eType==FTSQUERY_NEAR   || pExpr->eType==FTSQUERY_OR     
111186          || pExpr->eType==FTSQUERY_AND    || pExpr->eType==FTSQUERY_NOT
111187          || pExpr->eType==FTSQUERY_PHRASE
111188     );
111189     assert( pExpr->eType==FTSQUERY_PHRASE || isReqPos==0 );
111190
111191     if( pExpr->eType==FTSQUERY_PHRASE ){
111192       rc = fts3PhraseSelect(p, pExpr->pPhrase,
111193           isReqPos || (pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR),
111194           paOut, pnOut
111195       );
111196       fts3ExprFreeSegReaders(pExpr);
111197     }else if( p->eEvalmode==FTS3_EVAL_FILTER && pExpr->eType==FTSQUERY_AND ){
111198       ExprAndCost *aExpr = 0;     /* Array of AND'd expressions and costs */
111199       int nExpr = 0;              /* Size of aExpr[] */
111200       char *aRet = 0;             /* Doclist to return to caller */
111201       int nRet = 0;               /* Length of aRet[] in bytes */
111202       int nDoc = 0x7FFFFFFF;
111203
111204       assert( !isReqPos );
111205
111206       rc = fts3ExprAllocateSegReaders(p, pExpr, &nExpr);
111207       if( rc==SQLITE_OK ){
111208         assert( nExpr>1 );
111209         aExpr = sqlite3_malloc(sizeof(ExprAndCost) * nExpr);
111210         if( !aExpr ) rc = SQLITE_NOMEM;
111211       }
111212       if( rc==SQLITE_OK ){
111213         int ii;                   /* Used to iterate through expressions */
111214
111215         fts3ExprAssignCosts(pExpr, &aExpr);
111216         aExpr -= nExpr;
111217         for(ii=0; ii<nExpr; ii++){
111218           char *aNew;
111219           int nNew;
111220           int jj;
111221           ExprAndCost *pBest = 0;
111222   
111223           for(jj=0; jj<nExpr; jj++){
111224             ExprAndCost *pCand = &aExpr[jj];
111225             if( pCand->pExpr && (pBest==0 || pCand->nCost<pBest->nCost) ){
111226               pBest = pCand;
111227             }
111228           }
111229   
111230           if( pBest->nCost>nDoc ){
111231             rc = fts3DeferExpression(p, p->pExpr);
111232             break;
111233           }else{
111234             rc = fts3EvalExpr(p, pBest->pExpr, &aNew, &nNew, 0);
111235             if( rc!=SQLITE_OK ) break;
111236             pBest->pExpr = 0;
111237             if( ii==0 ){
111238               aRet = aNew;
111239               nRet = nNew;
111240               nDoc = fts3DoclistCountDocids(0, aRet, nRet);
111241             }else{
111242               fts3DoclistMerge(
111243                   MERGE_AND, 0, 0, aRet, &nRet, aRet, nRet, aNew, nNew, &nDoc
111244               );
111245               sqlite3_free(aNew);
111246             }
111247           }
111248         }
111249       }
111250
111251       if( rc==SQLITE_OK ){
111252         *paOut = aRet;
111253         *pnOut = nRet;
111254       }else{
111255         assert( *paOut==0 );
111256         sqlite3_free(aRet);
111257       }
111258       sqlite3_free(aExpr);
111259       fts3ExprFreeSegReaders(pExpr);
111260
111261     }else{
111262       char *aLeft;
111263       char *aRight;
111264       int nLeft;
111265       int nRight;
111266
111267       assert( pExpr->eType==FTSQUERY_NEAR 
111268            || pExpr->eType==FTSQUERY_OR
111269            || pExpr->eType==FTSQUERY_NOT
111270            || (pExpr->eType==FTSQUERY_AND && p->eEvalmode==FTS3_EVAL_NEXT)
111271       );
111272
111273       if( 0==(rc = fts3EvalExpr(p, pExpr->pRight, &aRight, &nRight, isReqPos))
111274        && 0==(rc = fts3EvalExpr(p, pExpr->pLeft, &aLeft, &nLeft, isReqPos))
111275       ){
111276         switch( pExpr->eType ){
111277           case FTSQUERY_NEAR: {
111278             Fts3Expr *pLeft;
111279             Fts3Expr *pRight;
111280             int mergetype = MERGE_NEAR;
111281             if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
111282               mergetype = MERGE_POS_NEAR;
111283             }
111284             pLeft = pExpr->pLeft;
111285             while( pLeft->eType==FTSQUERY_NEAR ){ 
111286               pLeft=pLeft->pRight;
111287             }
111288             pRight = pExpr->pRight;
111289             assert( pRight->eType==FTSQUERY_PHRASE );
111290             assert( pLeft->eType==FTSQUERY_PHRASE );
111291
111292             rc = fts3NearMerge(mergetype, pExpr->nNear, 
111293                 pLeft->pPhrase->nToken, aLeft, nLeft,
111294                 pRight->pPhrase->nToken, aRight, nRight,
111295                 paOut, pnOut
111296             );
111297             sqlite3_free(aLeft);
111298             break;
111299           }
111300
111301           case FTSQUERY_OR: {
111302             /* Allocate a buffer for the output. The maximum size is the
111303             ** sum of the sizes of the two input buffers. The +1 term is
111304             ** so that a buffer of zero bytes is never allocated - this can
111305             ** cause fts3DoclistMerge() to incorrectly return SQLITE_NOMEM.
111306             */
111307             char *aBuffer = sqlite3_malloc(nRight+nLeft+1);
111308             rc = fts3DoclistMerge(MERGE_OR, 0, 0, aBuffer, pnOut,
111309                 aLeft, nLeft, aRight, nRight, 0
111310             );
111311             *paOut = aBuffer;
111312             sqlite3_free(aLeft);
111313             break;
111314           }
111315
111316           default: {
111317             assert( FTSQUERY_NOT==MERGE_NOT && FTSQUERY_AND==MERGE_AND );
111318             fts3DoclistMerge(pExpr->eType, 0, 0, aLeft, pnOut,
111319                 aLeft, nLeft, aRight, nRight, 0
111320             );
111321             *paOut = aLeft;
111322             break;
111323           }
111324         }
111325       }
111326       sqlite3_free(aRight);
111327     }
111328   }
111329
111330   assert( rc==SQLITE_OK || *paOut==0 );
111331   return rc;
111332 }
111333
111334 /*
111335 ** This function is called from within xNext() for each row visited by
111336 ** an FTS3 query. If evaluating the FTS3 query expression within xFilter()
111337 ** was able to determine the exact set of matching rows, this function sets
111338 ** *pbRes to true and returns SQLITE_IO immediately.
111339 **
111340 ** Otherwise, if evaluating the query expression within xFilter() returned a
111341 ** superset of the matching documents instead of an exact set (this happens
111342 ** when the query includes very common tokens and it is deemed too expensive to
111343 ** load their doclists from disk), this function tests if the current row
111344 ** really does match the FTS3 query.
111345 **
111346 ** If an error occurs, an SQLite error code is returned. Otherwise, SQLITE_OK
111347 ** is returned and *pbRes is set to true if the current row matches the
111348 ** FTS3 query (and should be included in the results returned to SQLite), or
111349 ** false otherwise.
111350 */
111351 static int fts3EvalDeferred(
111352   Fts3Cursor *pCsr,               /* FTS3 cursor pointing at row to test */
111353   int *pbRes                      /* OUT: Set to true if row is a match */
111354 ){
111355   int rc = SQLITE_OK;
111356   if( pCsr->pDeferred==0 ){
111357     *pbRes = 1;
111358   }else{
111359     rc = fts3CursorSeek(0, pCsr);
111360     if( rc==SQLITE_OK ){
111361       sqlite3Fts3FreeDeferredDoclists(pCsr);
111362       rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
111363     }
111364     if( rc==SQLITE_OK ){
111365       char *a = 0;
111366       int n = 0;
111367       rc = fts3EvalExpr(pCsr, pCsr->pExpr, &a, &n, 0);
111368       assert( n>=0 );
111369       *pbRes = (n>0);
111370       sqlite3_free(a);
111371     }
111372   }
111373   return rc;
111374 }
111375
111376 /*
111377 ** Advance the cursor to the next row in the %_content table that
111378 ** matches the search criteria.  For a MATCH search, this will be
111379 ** the next row that matches. For a full-table scan, this will be
111380 ** simply the next row in the %_content table.  For a docid lookup,
111381 ** this routine simply sets the EOF flag.
111382 **
111383 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
111384 ** even if we reach end-of-file.  The fts3EofMethod() will be called
111385 ** subsequently to determine whether or not an EOF was hit.
111386 */
111387 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
111388   int res;
111389   int rc = SQLITE_OK;             /* Return code */
111390   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
111391
111392   pCsr->eEvalmode = FTS3_EVAL_NEXT;
111393   do {
111394     if( pCsr->aDoclist==0 ){
111395       if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
111396         pCsr->isEof = 1;
111397         rc = sqlite3_reset(pCsr->pStmt);
111398         break;
111399       }
111400       pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
111401     }else{
111402       if( pCsr->pNextId>=&pCsr->aDoclist[pCsr->nDoclist] ){
111403         pCsr->isEof = 1;
111404         break;
111405       }
111406       sqlite3_reset(pCsr->pStmt);
111407       fts3GetDeltaVarint(&pCsr->pNextId, &pCsr->iPrevId);
111408       pCsr->isRequireSeek = 1;
111409       pCsr->isMatchinfoNeeded = 1;
111410     }
111411   }while( SQLITE_OK==(rc = fts3EvalDeferred(pCsr, &res)) && res==0 );
111412
111413   return rc;
111414 }
111415
111416 /*
111417 ** This is the xFilter interface for the virtual table.  See
111418 ** the virtual table xFilter method documentation for additional
111419 ** information.
111420 **
111421 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
111422 ** the %_content table.
111423 **
111424 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
111425 ** in the %_content table.
111426 **
111427 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
111428 ** column on the left-hand side of the MATCH operator is column
111429 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
111430 ** side of the MATCH operator.
111431 */
111432 static int fts3FilterMethod(
111433   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
111434   int idxNum,                     /* Strategy index */
111435   const char *idxStr,             /* Unused */
111436   int nVal,                       /* Number of elements in apVal */
111437   sqlite3_value **apVal           /* Arguments for the indexing scheme */
111438 ){
111439   const char *azSql[] = {
111440     "SELECT * FROM %Q.'%q_content' WHERE docid = ?", /* non-full-table-scan */
111441     "SELECT * FROM %Q.'%q_content'",                 /* full-table-scan */
111442   };
111443   int rc;                         /* Return code */
111444   char *zSql;                     /* SQL statement used to access %_content */
111445   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
111446   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
111447
111448   UNUSED_PARAMETER(idxStr);
111449   UNUSED_PARAMETER(nVal);
111450
111451   assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
111452   assert( nVal==0 || nVal==1 );
111453   assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
111454   assert( p->pSegments==0 );
111455
111456   /* In case the cursor has been used before, clear it now. */
111457   sqlite3_finalize(pCsr->pStmt);
111458   sqlite3_free(pCsr->aDoclist);
111459   sqlite3Fts3ExprFree(pCsr->pExpr);
111460   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
111461
111462   if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
111463     int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
111464     const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
111465
111466     if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
111467       return SQLITE_NOMEM;
111468     }
111469
111470     rc = sqlite3Fts3ExprParse(p->pTokenizer, p->azColumn, p->nColumn, 
111471         iCol, zQuery, -1, &pCsr->pExpr
111472     );
111473     if( rc!=SQLITE_OK ){
111474       if( rc==SQLITE_ERROR ){
111475         p->base.zErrMsg = sqlite3_mprintf("malformed MATCH expression: [%s]",
111476                                           zQuery);
111477       }
111478       return rc;
111479     }
111480
111481     rc = sqlite3Fts3ReadLock(p);
111482     if( rc!=SQLITE_OK ) return rc;
111483
111484     rc = fts3EvalExpr(pCsr, pCsr->pExpr, &pCsr->aDoclist, &pCsr->nDoclist, 0);
111485     sqlite3Fts3SegmentsClose(p);
111486     if( rc!=SQLITE_OK ) return rc;
111487     pCsr->pNextId = pCsr->aDoclist;
111488     pCsr->iPrevId = 0;
111489   }
111490
111491   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
111492   ** statement loops through all rows of the %_content table. For a
111493   ** full-text query or docid lookup, the statement retrieves a single
111494   ** row by docid.
111495   */
111496   zSql = sqlite3_mprintf(azSql[idxNum==FTS3_FULLSCAN_SEARCH], p->zDb, p->zName);
111497   if( !zSql ){
111498     rc = SQLITE_NOMEM;
111499   }else{
111500     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
111501     sqlite3_free(zSql);
111502   }
111503   if( rc==SQLITE_OK && idxNum==FTS3_DOCID_SEARCH ){
111504     rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
111505   }
111506   pCsr->eSearch = (i16)idxNum;
111507
111508   if( rc!=SQLITE_OK ) return rc;
111509   return fts3NextMethod(pCursor);
111510 }
111511
111512 /* 
111513 ** This is the xEof method of the virtual table. SQLite calls this 
111514 ** routine to find out if it has reached the end of a result set.
111515 */
111516 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
111517   return ((Fts3Cursor *)pCursor)->isEof;
111518 }
111519
111520 /* 
111521 ** This is the xRowid method. The SQLite core calls this routine to
111522 ** retrieve the rowid for the current row of the result set. fts3
111523 ** exposes %_content.docid as the rowid for the virtual table. The
111524 ** rowid should be written to *pRowid.
111525 */
111526 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
111527   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
111528   if( pCsr->aDoclist ){
111529     *pRowid = pCsr->iPrevId;
111530   }else{
111531     /* This branch runs if the query is implemented using a full-table scan
111532     ** (not using the full-text index). In this case grab the rowid from the
111533     ** SELECT statement.
111534     */
111535     assert( pCsr->isRequireSeek==0 );
111536     *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
111537   }
111538   return SQLITE_OK;
111539 }
111540
111541 /* 
111542 ** This is the xColumn method, called by SQLite to request a value from
111543 ** the row that the supplied cursor currently points to.
111544 */
111545 static int fts3ColumnMethod(
111546   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
111547   sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
111548   int iCol                        /* Index of column to read value from */
111549 ){
111550   int rc;                         /* Return Code */
111551   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
111552   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
111553
111554   /* The column value supplied by SQLite must be in range. */
111555   assert( iCol>=0 && iCol<=p->nColumn+1 );
111556
111557   if( iCol==p->nColumn+1 ){
111558     /* This call is a request for the "docid" column. Since "docid" is an 
111559     ** alias for "rowid", use the xRowid() method to obtain the value.
111560     */
111561     sqlite3_int64 iRowid;
111562     rc = fts3RowidMethod(pCursor, &iRowid);
111563     sqlite3_result_int64(pContext, iRowid);
111564   }else if( iCol==p->nColumn ){
111565     /* The extra column whose name is the same as the table.
111566     ** Return a blob which is a pointer to the cursor.
111567     */
111568     sqlite3_result_blob(pContext, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
111569     rc = SQLITE_OK;
111570   }else{
111571     rc = fts3CursorSeek(0, pCsr);
111572     if( rc==SQLITE_OK ){
111573       sqlite3_result_value(pContext, sqlite3_column_value(pCsr->pStmt, iCol+1));
111574     }
111575   }
111576   return rc;
111577 }
111578
111579 /* 
111580 ** This function is the implementation of the xUpdate callback used by 
111581 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
111582 ** inserted, updated or deleted.
111583 */
111584 static int fts3UpdateMethod(
111585   sqlite3_vtab *pVtab,            /* Virtual table handle */
111586   int nArg,                       /* Size of argument array */
111587   sqlite3_value **apVal,          /* Array of arguments */
111588   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
111589 ){
111590   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
111591 }
111592
111593 /*
111594 ** Implementation of xSync() method. Flush the contents of the pending-terms
111595 ** hash-table to the database.
111596 */
111597 static int fts3SyncMethod(sqlite3_vtab *pVtab){
111598   int rc = sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
111599   sqlite3Fts3SegmentsClose((Fts3Table *)pVtab);
111600   return rc;
111601 }
111602
111603 /*
111604 ** Implementation of xBegin() method. This is a no-op.
111605 */
111606 static int fts3BeginMethod(sqlite3_vtab *pVtab){
111607   UNUSED_PARAMETER(pVtab);
111608   assert( ((Fts3Table *)pVtab)->nPendingData==0 );
111609   return SQLITE_OK;
111610 }
111611
111612 /*
111613 ** Implementation of xCommit() method. This is a no-op. The contents of
111614 ** the pending-terms hash-table have already been flushed into the database
111615 ** by fts3SyncMethod().
111616 */
111617 static int fts3CommitMethod(sqlite3_vtab *pVtab){
111618   UNUSED_PARAMETER(pVtab);
111619   assert( ((Fts3Table *)pVtab)->nPendingData==0 );
111620   return SQLITE_OK;
111621 }
111622
111623 /*
111624 ** Implementation of xRollback(). Discard the contents of the pending-terms
111625 ** hash-table. Any changes made to the database are reverted by SQLite.
111626 */
111627 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
111628   sqlite3Fts3PendingTermsClear((Fts3Table *)pVtab);
111629   return SQLITE_OK;
111630 }
111631
111632 /*
111633 ** Load the doclist associated with expression pExpr to pExpr->aDoclist.
111634 ** The loaded doclist contains positions as well as the document ids.
111635 ** This is used by the matchinfo(), snippet() and offsets() auxillary
111636 ** functions.
111637 */
111638 SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Cursor *pCsr, Fts3Expr *pExpr){
111639   int rc;
111640   assert( pExpr->eType==FTSQUERY_PHRASE && pExpr->pPhrase );
111641   assert( pCsr->eEvalmode==FTS3_EVAL_NEXT );
111642   rc = fts3EvalExpr(pCsr, pExpr, &pExpr->aDoclist, &pExpr->nDoclist, 1);
111643   return rc;
111644 }
111645
111646 SQLITE_PRIVATE int sqlite3Fts3ExprLoadFtDoclist(
111647   Fts3Cursor *pCsr, 
111648   Fts3Expr *pExpr,
111649   char **paDoclist,
111650   int *pnDoclist
111651 ){
111652   int rc;
111653   assert( pCsr->eEvalmode==FTS3_EVAL_NEXT );
111654   assert( pExpr->eType==FTSQUERY_PHRASE && pExpr->pPhrase );
111655   pCsr->eEvalmode = FTS3_EVAL_MATCHINFO;
111656   rc = fts3EvalExpr(pCsr, pExpr, paDoclist, pnDoclist, 1);
111657   pCsr->eEvalmode = FTS3_EVAL_NEXT;
111658   return rc;
111659 }
111660
111661 /*
111662 ** After ExprLoadDoclist() (see above) has been called, this function is
111663 ** used to iterate/search through the position lists that make up the doclist
111664 ** stored in pExpr->aDoclist.
111665 */
111666 SQLITE_PRIVATE char *sqlite3Fts3FindPositions(
111667   Fts3Expr *pExpr,                /* Access this expressions doclist */
111668   sqlite3_int64 iDocid,           /* Docid associated with requested pos-list */
111669   int iCol                        /* Column of requested pos-list */
111670 ){
111671   assert( pExpr->isLoaded );
111672   if( pExpr->aDoclist ){
111673     char *pEnd = &pExpr->aDoclist[pExpr->nDoclist];
111674     char *pCsr;
111675
111676     if( pExpr->pCurrent==0 ){
111677       pExpr->pCurrent = pExpr->aDoclist;
111678       pExpr->iCurrent = 0;
111679       pExpr->pCurrent += sqlite3Fts3GetVarint(pExpr->pCurrent,&pExpr->iCurrent);
111680     }
111681     pCsr = pExpr->pCurrent;
111682     assert( pCsr );
111683
111684     while( pCsr<pEnd ){
111685       if( pExpr->iCurrent<iDocid ){
111686         fts3PoslistCopy(0, &pCsr);
111687         if( pCsr<pEnd ){
111688           fts3GetDeltaVarint(&pCsr, &pExpr->iCurrent);
111689         }
111690         pExpr->pCurrent = pCsr;
111691       }else{
111692         if( pExpr->iCurrent==iDocid ){
111693           int iThis = 0;
111694           if( iCol<0 ){
111695             /* If iCol is negative, return a pointer to the start of the
111696             ** position-list (instead of a pointer to the start of a list
111697             ** of offsets associated with a specific column).
111698             */
111699             return pCsr;
111700           }
111701           while( iThis<iCol ){
111702             fts3ColumnlistCopy(0, &pCsr);
111703             if( *pCsr==0x00 ) return 0;
111704             pCsr++;
111705             pCsr += sqlite3Fts3GetVarint32(pCsr, &iThis);
111706           }
111707           if( iCol==iThis && (*pCsr&0xFE) ) return pCsr;
111708         }
111709         return 0;
111710       }
111711     }
111712   }
111713
111714   return 0;
111715 }
111716
111717 /*
111718 ** Helper function used by the implementation of the overloaded snippet(),
111719 ** offsets() and optimize() SQL functions.
111720 **
111721 ** If the value passed as the third argument is a blob of size
111722 ** sizeof(Fts3Cursor*), then the blob contents are copied to the 
111723 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
111724 ** message is written to context pContext and SQLITE_ERROR returned. The
111725 ** string passed via zFunc is used as part of the error message.
111726 */
111727 static int fts3FunctionArg(
111728   sqlite3_context *pContext,      /* SQL function call context */
111729   const char *zFunc,              /* Function name */
111730   sqlite3_value *pVal,            /* argv[0] passed to function */
111731   Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
111732 ){
111733   Fts3Cursor *pRet;
111734   if( sqlite3_value_type(pVal)!=SQLITE_BLOB 
111735    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
111736   ){
111737     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
111738     sqlite3_result_error(pContext, zErr, -1);
111739     sqlite3_free(zErr);
111740     return SQLITE_ERROR;
111741   }
111742   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
111743   *ppCsr = pRet;
111744   return SQLITE_OK;
111745 }
111746
111747 /*
111748 ** Implementation of the snippet() function for FTS3
111749 */
111750 static void fts3SnippetFunc(
111751   sqlite3_context *pContext,      /* SQLite function call context */
111752   int nVal,                       /* Size of apVal[] array */
111753   sqlite3_value **apVal           /* Array of arguments */
111754 ){
111755   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
111756   const char *zStart = "<b>";
111757   const char *zEnd = "</b>";
111758   const char *zEllipsis = "<b>...</b>";
111759   int iCol = -1;
111760   int nToken = 15;                /* Default number of tokens in snippet */
111761
111762   /* There must be at least one argument passed to this function (otherwise
111763   ** the non-overloaded version would have been called instead of this one).
111764   */
111765   assert( nVal>=1 );
111766
111767   if( nVal>6 ){
111768     sqlite3_result_error(pContext, 
111769         "wrong number of arguments to function snippet()", -1);
111770     return;
111771   }
111772   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
111773
111774   switch( nVal ){
111775     case 6: nToken = sqlite3_value_int(apVal[5]);
111776     case 5: iCol = sqlite3_value_int(apVal[4]);
111777     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
111778     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
111779     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
111780   }
111781   if( !zEllipsis || !zEnd || !zStart ){
111782     sqlite3_result_error_nomem(pContext);
111783   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
111784     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
111785   }
111786 }
111787
111788 /*
111789 ** Implementation of the offsets() function for FTS3
111790 */
111791 static void fts3OffsetsFunc(
111792   sqlite3_context *pContext,      /* SQLite function call context */
111793   int nVal,                       /* Size of argument array */
111794   sqlite3_value **apVal           /* Array of arguments */
111795 ){
111796   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
111797
111798   UNUSED_PARAMETER(nVal);
111799
111800   assert( nVal==1 );
111801   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
111802   assert( pCsr );
111803   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
111804     sqlite3Fts3Offsets(pContext, pCsr);
111805   }
111806 }
111807
111808 /* 
111809 ** Implementation of the special optimize() function for FTS3. This 
111810 ** function merges all segments in the database to a single segment.
111811 ** Example usage is:
111812 **
111813 **   SELECT optimize(t) FROM t LIMIT 1;
111814 **
111815 ** where 't' is the name of an FTS3 table.
111816 */
111817 static void fts3OptimizeFunc(
111818   sqlite3_context *pContext,      /* SQLite function call context */
111819   int nVal,                       /* Size of argument array */
111820   sqlite3_value **apVal           /* Array of arguments */
111821 ){
111822   int rc;                         /* Return code */
111823   Fts3Table *p;                   /* Virtual table handle */
111824   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
111825
111826   UNUSED_PARAMETER(nVal);
111827
111828   assert( nVal==1 );
111829   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
111830   p = (Fts3Table *)pCursor->base.pVtab;
111831   assert( p );
111832
111833   rc = sqlite3Fts3Optimize(p);
111834
111835   switch( rc ){
111836     case SQLITE_OK:
111837       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
111838       break;
111839     case SQLITE_DONE:
111840       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
111841       break;
111842     default:
111843       sqlite3_result_error_code(pContext, rc);
111844       break;
111845   }
111846 }
111847
111848 /*
111849 ** Implementation of the matchinfo() function for FTS3
111850 */
111851 static void fts3MatchinfoFunc(
111852   sqlite3_context *pContext,      /* SQLite function call context */
111853   int nVal,                       /* Size of argument array */
111854   sqlite3_value **apVal           /* Array of arguments */
111855 ){
111856   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
111857   assert( nVal==1 || nVal==2 );
111858   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
111859     const char *zArg = 0;
111860     if( nVal>1 ){
111861       zArg = (const char *)sqlite3_value_text(apVal[1]);
111862     }
111863     sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
111864   }
111865 }
111866
111867 /*
111868 ** This routine implements the xFindFunction method for the FTS3
111869 ** virtual table.
111870 */
111871 static int fts3FindFunctionMethod(
111872   sqlite3_vtab *pVtab,            /* Virtual table handle */
111873   int nArg,                       /* Number of SQL function arguments */
111874   const char *zName,              /* Name of SQL function */
111875   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
111876   void **ppArg                    /* Unused */
111877 ){
111878   struct Overloaded {
111879     const char *zName;
111880     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
111881   } aOverload[] = {
111882     { "snippet", fts3SnippetFunc },
111883     { "offsets", fts3OffsetsFunc },
111884     { "optimize", fts3OptimizeFunc },
111885     { "matchinfo", fts3MatchinfoFunc },
111886   };
111887   int i;                          /* Iterator variable */
111888
111889   UNUSED_PARAMETER(pVtab);
111890   UNUSED_PARAMETER(nArg);
111891   UNUSED_PARAMETER(ppArg);
111892
111893   for(i=0; i<SizeofArray(aOverload); i++){
111894     if( strcmp(zName, aOverload[i].zName)==0 ){
111895       *pxFunc = aOverload[i].xFunc;
111896       return 1;
111897     }
111898   }
111899
111900   /* No function of the specified name was found. Return 0. */
111901   return 0;
111902 }
111903
111904 /*
111905 ** Implementation of FTS3 xRename method. Rename an fts3 table.
111906 */
111907 static int fts3RenameMethod(
111908   sqlite3_vtab *pVtab,            /* Virtual table handle */
111909   const char *zName               /* New name of table */
111910 ){
111911   Fts3Table *p = (Fts3Table *)pVtab;
111912   sqlite3 *db = p->db;            /* Database connection */
111913   int rc;                         /* Return Code */
111914
111915   rc = sqlite3Fts3PendingTermsFlush(p);
111916   if( rc!=SQLITE_OK ){
111917     return rc;
111918   }
111919
111920   fts3DbExec(&rc, db,
111921     "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
111922     p->zDb, p->zName, zName
111923   );
111924   if( p->bHasDocsize ){
111925     fts3DbExec(&rc, db,
111926       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
111927       p->zDb, p->zName, zName
111928     );
111929   }
111930   if( p->bHasStat ){
111931     fts3DbExec(&rc, db,
111932       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
111933       p->zDb, p->zName, zName
111934     );
111935   }
111936   fts3DbExec(&rc, db,
111937     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
111938     p->zDb, p->zName, zName
111939   );
111940   fts3DbExec(&rc, db,
111941     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
111942     p->zDb, p->zName, zName
111943   );
111944   return rc;
111945 }
111946
111947 static const sqlite3_module fts3Module = {
111948   /* iVersion      */ 0,
111949   /* xCreate       */ fts3CreateMethod,
111950   /* xConnect      */ fts3ConnectMethod,
111951   /* xBestIndex    */ fts3BestIndexMethod,
111952   /* xDisconnect   */ fts3DisconnectMethod,
111953   /* xDestroy      */ fts3DestroyMethod,
111954   /* xOpen         */ fts3OpenMethod,
111955   /* xClose        */ fts3CloseMethod,
111956   /* xFilter       */ fts3FilterMethod,
111957   /* xNext         */ fts3NextMethod,
111958   /* xEof          */ fts3EofMethod,
111959   /* xColumn       */ fts3ColumnMethod,
111960   /* xRowid        */ fts3RowidMethod,
111961   /* xUpdate       */ fts3UpdateMethod,
111962   /* xBegin        */ fts3BeginMethod,
111963   /* xSync         */ fts3SyncMethod,
111964   /* xCommit       */ fts3CommitMethod,
111965   /* xRollback     */ fts3RollbackMethod,
111966   /* xFindFunction */ fts3FindFunctionMethod,
111967   /* xRename */       fts3RenameMethod,
111968 };
111969
111970 /*
111971 ** This function is registered as the module destructor (called when an
111972 ** FTS3 enabled database connection is closed). It frees the memory
111973 ** allocated for the tokenizer hash table.
111974 */
111975 static void hashDestroy(void *p){
111976   Fts3Hash *pHash = (Fts3Hash *)p;
111977   sqlite3Fts3HashClear(pHash);
111978   sqlite3_free(pHash);
111979 }
111980
111981 /*
111982 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are 
111983 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
111984 ** respectively. The following three forward declarations are for functions
111985 ** declared in these files used to retrieve the respective implementations.
111986 **
111987 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
111988 ** to by the argument to point to the "simple" tokenizer implementation.
111989 ** And so on.
111990 */
111991 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
111992 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
111993 #ifdef SQLITE_ENABLE_ICU
111994 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
111995 #endif
111996
111997 /*
111998 ** Initialise the fts3 extension. If this extension is built as part
111999 ** of the sqlite library, then this function is called directly by
112000 ** SQLite. If fts3 is built as a dynamically loadable extension, this
112001 ** function is called by the sqlite3_extension_init() entry point.
112002 */
112003 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
112004   int rc = SQLITE_OK;
112005   Fts3Hash *pHash = 0;
112006   const sqlite3_tokenizer_module *pSimple = 0;
112007   const sqlite3_tokenizer_module *pPorter = 0;
112008
112009 #ifdef SQLITE_ENABLE_ICU
112010   const sqlite3_tokenizer_module *pIcu = 0;
112011   sqlite3Fts3IcuTokenizerModule(&pIcu);
112012 #endif
112013
112014   sqlite3Fts3SimpleTokenizerModule(&pSimple);
112015   sqlite3Fts3PorterTokenizerModule(&pPorter);
112016
112017   /* Allocate and initialise the hash-table used to store tokenizers. */
112018   pHash = sqlite3_malloc(sizeof(Fts3Hash));
112019   if( !pHash ){
112020     rc = SQLITE_NOMEM;
112021   }else{
112022     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
112023   }
112024
112025   /* Load the built-in tokenizers into the hash table */
112026   if( rc==SQLITE_OK ){
112027     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
112028      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
112029 #ifdef SQLITE_ENABLE_ICU
112030      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
112031 #endif
112032     ){
112033       rc = SQLITE_NOMEM;
112034     }
112035   }
112036
112037 #ifdef SQLITE_TEST
112038   if( rc==SQLITE_OK ){
112039     rc = sqlite3Fts3ExprInitTestInterface(db);
112040   }
112041 #endif
112042
112043   /* Create the virtual table wrapper around the hash-table and overload 
112044   ** the two scalar functions. If this is successful, register the
112045   ** module with sqlite.
112046   */
112047   if( SQLITE_OK==rc 
112048    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
112049    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
112050    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
112051    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
112052    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
112053    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
112054   ){
112055     rc = sqlite3_create_module_v2(
112056         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
112057     );
112058     if( rc==SQLITE_OK ){
112059       rc = sqlite3_create_module_v2(
112060           db, "fts4", &fts3Module, (void *)pHash, 0
112061       );
112062     }
112063     return rc;
112064   }
112065
112066   /* An error has occurred. Delete the hash table and return the error code. */
112067   assert( rc!=SQLITE_OK );
112068   if( pHash ){
112069     sqlite3Fts3HashClear(pHash);
112070     sqlite3_free(pHash);
112071   }
112072   return rc;
112073 }
112074
112075 #if !SQLITE_CORE
112076 SQLITE_API int sqlite3_extension_init(
112077   sqlite3 *db, 
112078   char **pzErrMsg,
112079   const sqlite3_api_routines *pApi
112080 ){
112081   SQLITE_EXTENSION_INIT2(pApi)
112082   return sqlite3Fts3Init(db);
112083 }
112084 #endif
112085
112086 #endif
112087
112088 /************** End of fts3.c ************************************************/
112089 /************** Begin file fts3_expr.c ***************************************/
112090 /*
112091 ** 2008 Nov 28
112092 **
112093 ** The author disclaims copyright to this source code.  In place of
112094 ** a legal notice, here is a blessing:
112095 **
112096 **    May you do good and not evil.
112097 **    May you find forgiveness for yourself and forgive others.
112098 **    May you share freely, never taking more than you give.
112099 **
112100 ******************************************************************************
112101 **
112102 ** This module contains code that implements a parser for fts3 query strings
112103 ** (the right-hand argument to the MATCH operator). Because the supported 
112104 ** syntax is relatively simple, the whole tokenizer/parser system is
112105 ** hand-coded. 
112106 */
112107 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
112108
112109 /*
112110 ** By default, this module parses the legacy syntax that has been 
112111 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
112112 ** is defined, then it uses the new syntax. The differences between
112113 ** the new and the old syntaxes are:
112114 **
112115 **  a) The new syntax supports parenthesis. The old does not.
112116 **
112117 **  b) The new syntax supports the AND and NOT operators. The old does not.
112118 **
112119 **  c) The old syntax supports the "-" token qualifier. This is not 
112120 **     supported by the new syntax (it is replaced by the NOT operator).
112121 **
112122 **  d) When using the old syntax, the OR operator has a greater precedence
112123 **     than an implicit AND. When using the new, both implicity and explicit
112124 **     AND operators have a higher precedence than OR.
112125 **
112126 ** If compiled with SQLITE_TEST defined, then this module exports the
112127 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
112128 ** to zero causes the module to use the old syntax. If it is set to 
112129 ** non-zero the new syntax is activated. This is so both syntaxes can
112130 ** be tested using a single build of testfixture.
112131 **
112132 ** The following describes the syntax supported by the fts3 MATCH
112133 ** operator in a similar format to that used by the lemon parser
112134 ** generator. This module does not use actually lemon, it uses a
112135 ** custom parser.
112136 **
112137 **   query ::= andexpr (OR andexpr)*.
112138 **
112139 **   andexpr ::= notexpr (AND? notexpr)*.
112140 **
112141 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
112142 **   notexpr ::= LP query RP.
112143 **
112144 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
112145 **
112146 **   distance_opt ::= .
112147 **   distance_opt ::= / INTEGER.
112148 **
112149 **   phrase ::= TOKEN.
112150 **   phrase ::= COLUMN:TOKEN.
112151 **   phrase ::= "TOKEN TOKEN TOKEN...".
112152 */
112153
112154 #ifdef SQLITE_TEST
112155 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
112156 #else
112157 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS 
112158 #  define sqlite3_fts3_enable_parentheses 1
112159 # else
112160 #  define sqlite3_fts3_enable_parentheses 0
112161 # endif
112162 #endif
112163
112164 /*
112165 ** Default span for NEAR operators.
112166 */
112167 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
112168
112169
112170 typedef struct ParseContext ParseContext;
112171 struct ParseContext {
112172   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
112173   const char **azCol;                 /* Array of column names for fts3 table */
112174   int nCol;                           /* Number of entries in azCol[] */
112175   int iDefaultCol;                    /* Default column to query */
112176   sqlite3_context *pCtx;              /* Write error message here */
112177   int nNest;                          /* Number of nested brackets */
112178 };
112179
112180 /*
112181 ** This function is equivalent to the standard isspace() function. 
112182 **
112183 ** The standard isspace() can be awkward to use safely, because although it
112184 ** is defined to accept an argument of type int, its behaviour when passed
112185 ** an integer that falls outside of the range of the unsigned char type
112186 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
112187 ** is defined to accept an argument of type char, and always returns 0 for
112188 ** any values that fall outside of the range of the unsigned char type (i.e.
112189 ** negative values).
112190 */
112191 static int fts3isspace(char c){
112192   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
112193 }
112194
112195 /*
112196 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
112197 ** zero the memory before returning a pointer to it. If unsuccessful, 
112198 ** return NULL.
112199 */
112200 static void *fts3MallocZero(int nByte){
112201   void *pRet = sqlite3_malloc(nByte);
112202   if( pRet ) memset(pRet, 0, nByte);
112203   return pRet;
112204 }
112205
112206
112207 /*
112208 ** Extract the next token from buffer z (length n) using the tokenizer
112209 ** and other information (column names etc.) in pParse. Create an Fts3Expr
112210 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
112211 ** single token and set *ppExpr to point to it. If the end of the buffer is
112212 ** reached before a token is found, set *ppExpr to zero. It is the
112213 ** responsibility of the caller to eventually deallocate the allocated 
112214 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
112215 **
112216 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
112217 ** fails.
112218 */
112219 static int getNextToken(
112220   ParseContext *pParse,                   /* fts3 query parse context */
112221   int iCol,                               /* Value for Fts3Phrase.iColumn */
112222   const char *z, int n,                   /* Input string */
112223   Fts3Expr **ppExpr,                      /* OUT: expression */
112224   int *pnConsumed                         /* OUT: Number of bytes consumed */
112225 ){
112226   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
112227   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
112228   int rc;
112229   sqlite3_tokenizer_cursor *pCursor;
112230   Fts3Expr *pRet = 0;
112231   int nConsumed = 0;
112232
112233   rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
112234   if( rc==SQLITE_OK ){
112235     const char *zToken;
112236     int nToken, iStart, iEnd, iPosition;
112237     int nByte;                               /* total space to allocate */
112238
112239     pCursor->pTokenizer = pTokenizer;
112240     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
112241
112242     if( rc==SQLITE_OK ){
112243       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
112244       pRet = (Fts3Expr *)fts3MallocZero(nByte);
112245       if( !pRet ){
112246         rc = SQLITE_NOMEM;
112247       }else{
112248         pRet->eType = FTSQUERY_PHRASE;
112249         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
112250         pRet->pPhrase->nToken = 1;
112251         pRet->pPhrase->iColumn = iCol;
112252         pRet->pPhrase->aToken[0].n = nToken;
112253         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
112254         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
112255
112256         if( iEnd<n && z[iEnd]=='*' ){
112257           pRet->pPhrase->aToken[0].isPrefix = 1;
112258           iEnd++;
112259         }
112260         if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
112261           pRet->pPhrase->isNot = 1;
112262         }
112263       }
112264       nConsumed = iEnd;
112265     }
112266
112267     pModule->xClose(pCursor);
112268   }
112269   
112270   *pnConsumed = nConsumed;
112271   *ppExpr = pRet;
112272   return rc;
112273 }
112274
112275
112276 /*
112277 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
112278 ** then free the old allocation.
112279 */
112280 static void *fts3ReallocOrFree(void *pOrig, int nNew){
112281   void *pRet = sqlite3_realloc(pOrig, nNew);
112282   if( !pRet ){
112283     sqlite3_free(pOrig);
112284   }
112285   return pRet;
112286 }
112287
112288 /*
112289 ** Buffer zInput, length nInput, contains the contents of a quoted string
112290 ** that appeared as part of an fts3 query expression. Neither quote character
112291 ** is included in the buffer. This function attempts to tokenize the entire
112292 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE 
112293 ** containing the results.
112294 **
112295 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
112296 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
112297 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
112298 ** to 0.
112299 */
112300 static int getNextString(
112301   ParseContext *pParse,                   /* fts3 query parse context */
112302   const char *zInput, int nInput,         /* Input string */
112303   Fts3Expr **ppExpr                       /* OUT: expression */
112304 ){
112305   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
112306   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
112307   int rc;
112308   Fts3Expr *p = 0;
112309   sqlite3_tokenizer_cursor *pCursor = 0;
112310   char *zTemp = 0;
112311   int nTemp = 0;
112312
112313   rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
112314   if( rc==SQLITE_OK ){
112315     int ii;
112316     pCursor->pTokenizer = pTokenizer;
112317     for(ii=0; rc==SQLITE_OK; ii++){
112318       const char *zToken;
112319       int nToken, iBegin, iEnd, iPos;
112320       rc = pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
112321       if( rc==SQLITE_OK ){
112322         int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
112323         p = fts3ReallocOrFree(p, nByte+ii*sizeof(Fts3PhraseToken));
112324         zTemp = fts3ReallocOrFree(zTemp, nTemp + nToken);
112325         if( !p || !zTemp ){
112326           goto no_mem;
112327         }
112328         if( ii==0 ){
112329           memset(p, 0, nByte);
112330           p->pPhrase = (Fts3Phrase *)&p[1];
112331         }
112332         p->pPhrase = (Fts3Phrase *)&p[1];
112333         memset(&p->pPhrase->aToken[ii], 0, sizeof(Fts3PhraseToken));
112334         p->pPhrase->nToken = ii+1;
112335         p->pPhrase->aToken[ii].n = nToken;
112336         memcpy(&zTemp[nTemp], zToken, nToken);
112337         nTemp += nToken;
112338         if( iEnd<nInput && zInput[iEnd]=='*' ){
112339           p->pPhrase->aToken[ii].isPrefix = 1;
112340         }else{
112341           p->pPhrase->aToken[ii].isPrefix = 0;
112342         }
112343       }
112344     }
112345
112346     pModule->xClose(pCursor);
112347     pCursor = 0;
112348   }
112349
112350   if( rc==SQLITE_DONE ){
112351     int jj;
112352     char *zNew = NULL;
112353     int nNew = 0;
112354     int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
112355     nByte += (p?(p->pPhrase->nToken-1):0) * sizeof(Fts3PhraseToken);
112356     p = fts3ReallocOrFree(p, nByte + nTemp);
112357     if( !p ){
112358       goto no_mem;
112359     }
112360     if( zTemp ){
112361       zNew = &(((char *)p)[nByte]);
112362       memcpy(zNew, zTemp, nTemp);
112363     }else{
112364       memset(p, 0, nByte+nTemp);
112365     }
112366     p->pPhrase = (Fts3Phrase *)&p[1];
112367     for(jj=0; jj<p->pPhrase->nToken; jj++){
112368       p->pPhrase->aToken[jj].z = &zNew[nNew];
112369       nNew += p->pPhrase->aToken[jj].n;
112370     }
112371     sqlite3_free(zTemp);
112372     p->eType = FTSQUERY_PHRASE;
112373     p->pPhrase->iColumn = pParse->iDefaultCol;
112374     rc = SQLITE_OK;
112375   }
112376
112377   *ppExpr = p;
112378   return rc;
112379 no_mem:
112380
112381   if( pCursor ){
112382     pModule->xClose(pCursor);
112383   }
112384   sqlite3_free(zTemp);
112385   sqlite3_free(p);
112386   *ppExpr = 0;
112387   return SQLITE_NOMEM;
112388 }
112389
112390 /*
112391 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
112392 ** call fts3ExprParse(). So this forward declaration is required.
112393 */
112394 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
112395
112396 /*
112397 ** The output variable *ppExpr is populated with an allocated Fts3Expr 
112398 ** structure, or set to 0 if the end of the input buffer is reached.
112399 **
112400 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
112401 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
112402 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
112403 */
112404 static int getNextNode(
112405   ParseContext *pParse,                   /* fts3 query parse context */
112406   const char *z, int n,                   /* Input string */
112407   Fts3Expr **ppExpr,                      /* OUT: expression */
112408   int *pnConsumed                         /* OUT: Number of bytes consumed */
112409 ){
112410   static const struct Fts3Keyword {
112411     char *z;                              /* Keyword text */
112412     unsigned char n;                      /* Length of the keyword */
112413     unsigned char parenOnly;              /* Only valid in paren mode */
112414     unsigned char eType;                  /* Keyword code */
112415   } aKeyword[] = {
112416     { "OR" ,  2, 0, FTSQUERY_OR   },
112417     { "AND",  3, 1, FTSQUERY_AND  },
112418     { "NOT",  3, 1, FTSQUERY_NOT  },
112419     { "NEAR", 4, 0, FTSQUERY_NEAR }
112420   };
112421   int ii;
112422   int iCol;
112423   int iColLen;
112424   int rc;
112425   Fts3Expr *pRet = 0;
112426
112427   const char *zInput = z;
112428   int nInput = n;
112429
112430   /* Skip over any whitespace before checking for a keyword, an open or
112431   ** close bracket, or a quoted string. 
112432   */
112433   while( nInput>0 && fts3isspace(*zInput) ){
112434     nInput--;
112435     zInput++;
112436   }
112437   if( nInput==0 ){
112438     return SQLITE_DONE;
112439   }
112440
112441   /* See if we are dealing with a keyword. */
112442   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
112443     const struct Fts3Keyword *pKey = &aKeyword[ii];
112444
112445     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
112446       continue;
112447     }
112448
112449     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
112450       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
112451       int nKey = pKey->n;
112452       char cNext;
112453
112454       /* If this is a "NEAR" keyword, check for an explicit nearness. */
112455       if( pKey->eType==FTSQUERY_NEAR ){
112456         assert( nKey==4 );
112457         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
112458           nNear = 0;
112459           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
112460             nNear = nNear * 10 + (zInput[nKey] - '0');
112461           }
112462         }
112463       }
112464
112465       /* At this point this is probably a keyword. But for that to be true,
112466       ** the next byte must contain either whitespace, an open or close
112467       ** parenthesis, a quote character, or EOF. 
112468       */
112469       cNext = zInput[nKey];
112470       if( fts3isspace(cNext) 
112471        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
112472       ){
112473         pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
112474         if( !pRet ){
112475           return SQLITE_NOMEM;
112476         }
112477         pRet->eType = pKey->eType;
112478         pRet->nNear = nNear;
112479         *ppExpr = pRet;
112480         *pnConsumed = (int)((zInput - z) + nKey);
112481         return SQLITE_OK;
112482       }
112483
112484       /* Turns out that wasn't a keyword after all. This happens if the
112485       ** user has supplied a token such as "ORacle". Continue.
112486       */
112487     }
112488   }
112489
112490   /* Check for an open bracket. */
112491   if( sqlite3_fts3_enable_parentheses ){
112492     if( *zInput=='(' ){
112493       int nConsumed;
112494       pParse->nNest++;
112495       rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
112496       if( rc==SQLITE_OK && !*ppExpr ){
112497         rc = SQLITE_DONE;
112498       }
112499       *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
112500       return rc;
112501     }
112502   
112503     /* Check for a close bracket. */
112504     if( *zInput==')' ){
112505       pParse->nNest--;
112506       *pnConsumed = (int)((zInput - z) + 1);
112507       return SQLITE_DONE;
112508     }
112509   }
112510
112511   /* See if we are dealing with a quoted phrase. If this is the case, then
112512   ** search for the closing quote and pass the whole string to getNextString()
112513   ** for processing. This is easy to do, as fts3 has no syntax for escaping
112514   ** a quote character embedded in a string.
112515   */
112516   if( *zInput=='"' ){
112517     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
112518     *pnConsumed = (int)((zInput - z) + ii + 1);
112519     if( ii==nInput ){
112520       return SQLITE_ERROR;
112521     }
112522     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
112523   }
112524
112525
112526   /* If control flows to this point, this must be a regular token, or 
112527   ** the end of the input. Read a regular token using the sqlite3_tokenizer
112528   ** interface. Before doing so, figure out if there is an explicit
112529   ** column specifier for the token. 
112530   **
112531   ** TODO: Strangely, it is not possible to associate a column specifier
112532   ** with a quoted phrase, only with a single token. Not sure if this was
112533   ** an implementation artifact or an intentional decision when fts3 was
112534   ** first implemented. Whichever it was, this module duplicates the 
112535   ** limitation.
112536   */
112537   iCol = pParse->iDefaultCol;
112538   iColLen = 0;
112539   for(ii=0; ii<pParse->nCol; ii++){
112540     const char *zStr = pParse->azCol[ii];
112541     int nStr = (int)strlen(zStr);
112542     if( nInput>nStr && zInput[nStr]==':' 
112543      && sqlite3_strnicmp(zStr, zInput, nStr)==0 
112544     ){
112545       iCol = ii;
112546       iColLen = (int)((zInput - z) + nStr + 1);
112547       break;
112548     }
112549   }
112550   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
112551   *pnConsumed += iColLen;
112552   return rc;
112553 }
112554
112555 /*
112556 ** The argument is an Fts3Expr structure for a binary operator (any type
112557 ** except an FTSQUERY_PHRASE). Return an integer value representing the
112558 ** precedence of the operator. Lower values have a higher precedence (i.e.
112559 ** group more tightly). For example, in the C language, the == operator
112560 ** groups more tightly than ||, and would therefore have a higher precedence.
112561 **
112562 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
112563 ** is defined), the order of the operators in precedence from highest to
112564 ** lowest is:
112565 **
112566 **   NEAR
112567 **   NOT
112568 **   AND (including implicit ANDs)
112569 **   OR
112570 **
112571 ** Note that when using the old query syntax, the OR operator has a higher
112572 ** precedence than the AND operator.
112573 */
112574 static int opPrecedence(Fts3Expr *p){
112575   assert( p->eType!=FTSQUERY_PHRASE );
112576   if( sqlite3_fts3_enable_parentheses ){
112577     return p->eType;
112578   }else if( p->eType==FTSQUERY_NEAR ){
112579     return 1;
112580   }else if( p->eType==FTSQUERY_OR ){
112581     return 2;
112582   }
112583   assert( p->eType==FTSQUERY_AND );
112584   return 3;
112585 }
112586
112587 /*
112588 ** Argument ppHead contains a pointer to the current head of a query 
112589 ** expression tree being parsed. pPrev is the expression node most recently
112590 ** inserted into the tree. This function adds pNew, which is always a binary
112591 ** operator node, into the expression tree based on the relative precedence
112592 ** of pNew and the existing nodes of the tree. This may result in the head
112593 ** of the tree changing, in which case *ppHead is set to the new root node.
112594 */
112595 static void insertBinaryOperator(
112596   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
112597   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
112598   Fts3Expr *pNew           /* New binary node to insert into expression tree */
112599 ){
112600   Fts3Expr *pSplit = pPrev;
112601   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
112602     pSplit = pSplit->pParent;
112603   }
112604
112605   if( pSplit->pParent ){
112606     assert( pSplit->pParent->pRight==pSplit );
112607     pSplit->pParent->pRight = pNew;
112608     pNew->pParent = pSplit->pParent;
112609   }else{
112610     *ppHead = pNew;
112611   }
112612   pNew->pLeft = pSplit;
112613   pSplit->pParent = pNew;
112614 }
112615
112616 /*
112617 ** Parse the fts3 query expression found in buffer z, length n. This function
112618 ** returns either when the end of the buffer is reached or an unmatched 
112619 ** closing bracket - ')' - is encountered.
112620 **
112621 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
112622 ** parsed form of the expression and *pnConsumed is set to the number of
112623 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
112624 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
112625 */
112626 static int fts3ExprParse(
112627   ParseContext *pParse,                   /* fts3 query parse context */
112628   const char *z, int n,                   /* Text of MATCH query */
112629   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
112630   int *pnConsumed                         /* OUT: Number of bytes consumed */
112631 ){
112632   Fts3Expr *pRet = 0;
112633   Fts3Expr *pPrev = 0;
112634   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
112635   int nIn = n;
112636   const char *zIn = z;
112637   int rc = SQLITE_OK;
112638   int isRequirePhrase = 1;
112639
112640   while( rc==SQLITE_OK ){
112641     Fts3Expr *p = 0;
112642     int nByte = 0;
112643     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
112644     if( rc==SQLITE_OK ){
112645       int isPhrase;
112646
112647       if( !sqlite3_fts3_enable_parentheses 
112648        && p->eType==FTSQUERY_PHRASE && p->pPhrase->isNot 
112649       ){
112650         /* Create an implicit NOT operator. */
112651         Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
112652         if( !pNot ){
112653           sqlite3Fts3ExprFree(p);
112654           rc = SQLITE_NOMEM;
112655           goto exprparse_out;
112656         }
112657         pNot->eType = FTSQUERY_NOT;
112658         pNot->pRight = p;
112659         if( pNotBranch ){
112660           pNot->pLeft = pNotBranch;
112661         }
112662         pNotBranch = pNot;
112663         p = pPrev;
112664       }else{
112665         int eType = p->eType;
112666         assert( eType!=FTSQUERY_PHRASE || !p->pPhrase->isNot );
112667         isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
112668
112669         /* The isRequirePhrase variable is set to true if a phrase or
112670         ** an expression contained in parenthesis is required. If a
112671         ** binary operator (AND, OR, NOT or NEAR) is encounted when
112672         ** isRequirePhrase is set, this is a syntax error.
112673         */
112674         if( !isPhrase && isRequirePhrase ){
112675           sqlite3Fts3ExprFree(p);
112676           rc = SQLITE_ERROR;
112677           goto exprparse_out;
112678         }
112679   
112680         if( isPhrase && !isRequirePhrase ){
112681           /* Insert an implicit AND operator. */
112682           Fts3Expr *pAnd;
112683           assert( pRet && pPrev );
112684           pAnd = fts3MallocZero(sizeof(Fts3Expr));
112685           if( !pAnd ){
112686             sqlite3Fts3ExprFree(p);
112687             rc = SQLITE_NOMEM;
112688             goto exprparse_out;
112689           }
112690           pAnd->eType = FTSQUERY_AND;
112691           insertBinaryOperator(&pRet, pPrev, pAnd);
112692           pPrev = pAnd;
112693         }
112694
112695         /* This test catches attempts to make either operand of a NEAR
112696         ** operator something other than a phrase. For example, either of
112697         ** the following:
112698         **
112699         **    (bracketed expression) NEAR phrase
112700         **    phrase NEAR (bracketed expression)
112701         **
112702         ** Return an error in either case.
112703         */
112704         if( pPrev && (
112705             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
112706          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
112707         )){
112708           sqlite3Fts3ExprFree(p);
112709           rc = SQLITE_ERROR;
112710           goto exprparse_out;
112711         }
112712   
112713         if( isPhrase ){
112714           if( pRet ){
112715             assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
112716             pPrev->pRight = p;
112717             p->pParent = pPrev;
112718           }else{
112719             pRet = p;
112720           }
112721         }else{
112722           insertBinaryOperator(&pRet, pPrev, p);
112723         }
112724         isRequirePhrase = !isPhrase;
112725       }
112726       assert( nByte>0 );
112727     }
112728     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
112729     nIn -= nByte;
112730     zIn += nByte;
112731     pPrev = p;
112732   }
112733
112734   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
112735     rc = SQLITE_ERROR;
112736   }
112737
112738   if( rc==SQLITE_DONE ){
112739     rc = SQLITE_OK;
112740     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
112741       if( !pRet ){
112742         rc = SQLITE_ERROR;
112743       }else{
112744         Fts3Expr *pIter = pNotBranch;
112745         while( pIter->pLeft ){
112746           pIter = pIter->pLeft;
112747         }
112748         pIter->pLeft = pRet;
112749         pRet = pNotBranch;
112750       }
112751     }
112752   }
112753   *pnConsumed = n - nIn;
112754
112755 exprparse_out:
112756   if( rc!=SQLITE_OK ){
112757     sqlite3Fts3ExprFree(pRet);
112758     sqlite3Fts3ExprFree(pNotBranch);
112759     pRet = 0;
112760   }
112761   *ppExpr = pRet;
112762   return rc;
112763 }
112764
112765 /*
112766 ** Parameters z and n contain a pointer to and length of a buffer containing
112767 ** an fts3 query expression, respectively. This function attempts to parse the
112768 ** query expression and create a tree of Fts3Expr structures representing the
112769 ** parsed expression. If successful, *ppExpr is set to point to the head
112770 ** of the parsed expression tree and SQLITE_OK is returned. If an error
112771 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
112772 ** error) is returned and *ppExpr is set to 0.
112773 **
112774 ** If parameter n is a negative number, then z is assumed to point to a
112775 ** nul-terminated string and the length is determined using strlen().
112776 **
112777 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
112778 ** use to normalize query tokens while parsing the expression. The azCol[]
112779 ** array, which is assumed to contain nCol entries, should contain the names
112780 ** of each column in the target fts3 table, in order from left to right. 
112781 ** Column names must be nul-terminated strings.
112782 **
112783 ** The iDefaultCol parameter should be passed the index of the table column
112784 ** that appears on the left-hand-side of the MATCH operator (the default
112785 ** column to match against for tokens for which a column name is not explicitly
112786 ** specified as part of the query string), or -1 if tokens may by default
112787 ** match any table column.
112788 */
112789 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
112790   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
112791   char **azCol,                       /* Array of column names for fts3 table */
112792   int nCol,                           /* Number of entries in azCol[] */
112793   int iDefaultCol,                    /* Default column to query */
112794   const char *z, int n,               /* Text of MATCH query */
112795   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
112796 ){
112797   int nParsed;
112798   int rc;
112799   ParseContext sParse;
112800   sParse.pTokenizer = pTokenizer;
112801   sParse.azCol = (const char **)azCol;
112802   sParse.nCol = nCol;
112803   sParse.iDefaultCol = iDefaultCol;
112804   sParse.nNest = 0;
112805   if( z==0 ){
112806     *ppExpr = 0;
112807     return SQLITE_OK;
112808   }
112809   if( n<0 ){
112810     n = (int)strlen(z);
112811   }
112812   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
112813
112814   /* Check for mismatched parenthesis */
112815   if( rc==SQLITE_OK && sParse.nNest ){
112816     rc = SQLITE_ERROR;
112817     sqlite3Fts3ExprFree(*ppExpr);
112818     *ppExpr = 0;
112819   }
112820
112821   return rc;
112822 }
112823
112824 /*
112825 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
112826 */
112827 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
112828   if( p ){
112829     sqlite3Fts3ExprFree(p->pLeft);
112830     sqlite3Fts3ExprFree(p->pRight);
112831     sqlite3_free(p->aDoclist);
112832     sqlite3_free(p);
112833   }
112834 }
112835
112836 /****************************************************************************
112837 *****************************************************************************
112838 ** Everything after this point is just test code.
112839 */
112840
112841 #ifdef SQLITE_TEST
112842
112843
112844 /*
112845 ** Function to query the hash-table of tokenizers (see README.tokenizers).
112846 */
112847 static int queryTestTokenizer(
112848   sqlite3 *db, 
112849   const char *zName,  
112850   const sqlite3_tokenizer_module **pp
112851 ){
112852   int rc;
112853   sqlite3_stmt *pStmt;
112854   const char zSql[] = "SELECT fts3_tokenizer(?)";
112855
112856   *pp = 0;
112857   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
112858   if( rc!=SQLITE_OK ){
112859     return rc;
112860   }
112861
112862   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
112863   if( SQLITE_ROW==sqlite3_step(pStmt) ){
112864     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
112865       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
112866     }
112867   }
112868
112869   return sqlite3_finalize(pStmt);
112870 }
112871
112872 /*
112873 ** Return a pointer to a buffer containing a text representation of the
112874 ** expression passed as the first argument. The buffer is obtained from
112875 ** sqlite3_malloc(). It is the responsibility of the caller to use 
112876 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
112877 ** NULL is returned.
112878 **
112879 ** If the second argument is not NULL, then its contents are prepended to 
112880 ** the returned expression text and then freed using sqlite3_free().
112881 */
112882 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
112883   switch( pExpr->eType ){
112884     case FTSQUERY_PHRASE: {
112885       Fts3Phrase *pPhrase = pExpr->pPhrase;
112886       int i;
112887       zBuf = sqlite3_mprintf(
112888           "%zPHRASE %d %d", zBuf, pPhrase->iColumn, pPhrase->isNot);
112889       for(i=0; zBuf && i<pPhrase->nToken; i++){
112890         zBuf = sqlite3_mprintf("%z %.*s%s", zBuf, 
112891             pPhrase->aToken[i].n, pPhrase->aToken[i].z,
112892             (pPhrase->aToken[i].isPrefix?"+":"")
112893         );
112894       }
112895       return zBuf;
112896     }
112897
112898     case FTSQUERY_NEAR:
112899       zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
112900       break;
112901     case FTSQUERY_NOT:
112902       zBuf = sqlite3_mprintf("%zNOT ", zBuf);
112903       break;
112904     case FTSQUERY_AND:
112905       zBuf = sqlite3_mprintf("%zAND ", zBuf);
112906       break;
112907     case FTSQUERY_OR:
112908       zBuf = sqlite3_mprintf("%zOR ", zBuf);
112909       break;
112910   }
112911
112912   if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
112913   if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
112914   if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
112915
112916   if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
112917   if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
112918
112919   return zBuf;
112920 }
112921
112922 /*
112923 ** This is the implementation of a scalar SQL function used to test the 
112924 ** expression parser. It should be called as follows:
112925 **
112926 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
112927 **
112928 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
112929 ** to parse the query expression (see README.tokenizers). The second argument
112930 ** is the query expression to parse. Each subsequent argument is the name
112931 ** of a column of the fts3 table that the query expression may refer to.
112932 ** For example:
112933 **
112934 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
112935 */
112936 static void fts3ExprTest(
112937   sqlite3_context *context,
112938   int argc,
112939   sqlite3_value **argv
112940 ){
112941   sqlite3_tokenizer_module const *pModule = 0;
112942   sqlite3_tokenizer *pTokenizer = 0;
112943   int rc;
112944   char **azCol = 0;
112945   const char *zExpr;
112946   int nExpr;
112947   int nCol;
112948   int ii;
112949   Fts3Expr *pExpr;
112950   char *zBuf = 0;
112951   sqlite3 *db = sqlite3_context_db_handle(context);
112952
112953   if( argc<3 ){
112954     sqlite3_result_error(context, 
112955         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
112956     );
112957     return;
112958   }
112959
112960   rc = queryTestTokenizer(db,
112961                           (const char *)sqlite3_value_text(argv[0]), &pModule);
112962   if( rc==SQLITE_NOMEM ){
112963     sqlite3_result_error_nomem(context);
112964     goto exprtest_out;
112965   }else if( !pModule ){
112966     sqlite3_result_error(context, "No such tokenizer module", -1);
112967     goto exprtest_out;
112968   }
112969
112970   rc = pModule->xCreate(0, 0, &pTokenizer);
112971   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
112972   if( rc==SQLITE_NOMEM ){
112973     sqlite3_result_error_nomem(context);
112974     goto exprtest_out;
112975   }
112976   pTokenizer->pModule = pModule;
112977
112978   zExpr = (const char *)sqlite3_value_text(argv[1]);
112979   nExpr = sqlite3_value_bytes(argv[1]);
112980   nCol = argc-2;
112981   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
112982   if( !azCol ){
112983     sqlite3_result_error_nomem(context);
112984     goto exprtest_out;
112985   }
112986   for(ii=0; ii<nCol; ii++){
112987     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
112988   }
112989
112990   rc = sqlite3Fts3ExprParse(
112991       pTokenizer, azCol, nCol, nCol, zExpr, nExpr, &pExpr
112992   );
112993   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
112994     sqlite3_result_error(context, "Error parsing expression", -1);
112995   }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
112996     sqlite3_result_error_nomem(context);
112997   }else{
112998     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
112999     sqlite3_free(zBuf);
113000   }
113001
113002   sqlite3Fts3ExprFree(pExpr);
113003
113004 exprtest_out:
113005   if( pModule && pTokenizer ){
113006     rc = pModule->xDestroy(pTokenizer);
113007   }
113008   sqlite3_free(azCol);
113009 }
113010
113011 /*
113012 ** Register the query expression parser test function fts3_exprtest() 
113013 ** with database connection db. 
113014 */
113015 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
113016   return sqlite3_create_function(
113017       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
113018   );
113019 }
113020
113021 #endif
113022 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
113023
113024 /************** End of fts3_expr.c *******************************************/
113025 /************** Begin file fts3_hash.c ***************************************/
113026 /*
113027 ** 2001 September 22
113028 **
113029 ** The author disclaims copyright to this source code.  In place of
113030 ** a legal notice, here is a blessing:
113031 **
113032 **    May you do good and not evil.
113033 **    May you find forgiveness for yourself and forgive others.
113034 **    May you share freely, never taking more than you give.
113035 **
113036 *************************************************************************
113037 ** This is the implementation of generic hash-tables used in SQLite.
113038 ** We've modified it slightly to serve as a standalone hash table
113039 ** implementation for the full-text indexing module.
113040 */
113041
113042 /*
113043 ** The code in this file is only compiled if:
113044 **
113045 **     * The FTS3 module is being built as an extension
113046 **       (in which case SQLITE_CORE is not defined), or
113047 **
113048 **     * The FTS3 module is being built into the core of
113049 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
113050 */
113051 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
113052
113053
113054
113055 /*
113056 ** Malloc and Free functions
113057 */
113058 static void *fts3HashMalloc(int n){
113059   void *p = sqlite3_malloc(n);
113060   if( p ){
113061     memset(p, 0, n);
113062   }
113063   return p;
113064 }
113065 static void fts3HashFree(void *p){
113066   sqlite3_free(p);
113067 }
113068
113069 /* Turn bulk memory into a hash table object by initializing the
113070 ** fields of the Hash structure.
113071 **
113072 ** "pNew" is a pointer to the hash table that is to be initialized.
113073 ** keyClass is one of the constants 
113074 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
113075 ** determines what kind of key the hash table will use.  "copyKey" is
113076 ** true if the hash table should make its own private copy of keys and
113077 ** false if it should just use the supplied pointer.
113078 */
113079 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
113080   assert( pNew!=0 );
113081   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
113082   pNew->keyClass = keyClass;
113083   pNew->copyKey = copyKey;
113084   pNew->first = 0;
113085   pNew->count = 0;
113086   pNew->htsize = 0;
113087   pNew->ht = 0;
113088 }
113089
113090 /* Remove all entries from a hash table.  Reclaim all memory.
113091 ** Call this routine to delete a hash table or to reset a hash table
113092 ** to the empty state.
113093 */
113094 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
113095   Fts3HashElem *elem;         /* For looping over all elements of the table */
113096
113097   assert( pH!=0 );
113098   elem = pH->first;
113099   pH->first = 0;
113100   fts3HashFree(pH->ht);
113101   pH->ht = 0;
113102   pH->htsize = 0;
113103   while( elem ){
113104     Fts3HashElem *next_elem = elem->next;
113105     if( pH->copyKey && elem->pKey ){
113106       fts3HashFree(elem->pKey);
113107     }
113108     fts3HashFree(elem);
113109     elem = next_elem;
113110   }
113111   pH->count = 0;
113112 }
113113
113114 /*
113115 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
113116 */
113117 static int fts3StrHash(const void *pKey, int nKey){
113118   const char *z = (const char *)pKey;
113119   int h = 0;
113120   if( nKey<=0 ) nKey = (int) strlen(z);
113121   while( nKey > 0  ){
113122     h = (h<<3) ^ h ^ *z++;
113123     nKey--;
113124   }
113125   return h & 0x7fffffff;
113126 }
113127 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
113128   if( n1!=n2 ) return 1;
113129   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
113130 }
113131
113132 /*
113133 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
113134 */
113135 static int fts3BinHash(const void *pKey, int nKey){
113136   int h = 0;
113137   const char *z = (const char *)pKey;
113138   while( nKey-- > 0 ){
113139     h = (h<<3) ^ h ^ *(z++);
113140   }
113141   return h & 0x7fffffff;
113142 }
113143 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
113144   if( n1!=n2 ) return 1;
113145   return memcmp(pKey1,pKey2,n1);
113146 }
113147
113148 /*
113149 ** Return a pointer to the appropriate hash function given the key class.
113150 **
113151 ** The C syntax in this function definition may be unfamilar to some 
113152 ** programmers, so we provide the following additional explanation:
113153 **
113154 ** The name of the function is "ftsHashFunction".  The function takes a
113155 ** single parameter "keyClass".  The return value of ftsHashFunction()
113156 ** is a pointer to another function.  Specifically, the return value
113157 ** of ftsHashFunction() is a pointer to a function that takes two parameters
113158 ** with types "const void*" and "int" and returns an "int".
113159 */
113160 static int (*ftsHashFunction(int keyClass))(const void*,int){
113161   if( keyClass==FTS3_HASH_STRING ){
113162     return &fts3StrHash;
113163   }else{
113164     assert( keyClass==FTS3_HASH_BINARY );
113165     return &fts3BinHash;
113166   }
113167 }
113168
113169 /*
113170 ** Return a pointer to the appropriate hash function given the key class.
113171 **
113172 ** For help in interpreted the obscure C code in the function definition,
113173 ** see the header comment on the previous function.
113174 */
113175 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
113176   if( keyClass==FTS3_HASH_STRING ){
113177     return &fts3StrCompare;
113178   }else{
113179     assert( keyClass==FTS3_HASH_BINARY );
113180     return &fts3BinCompare;
113181   }
113182 }
113183
113184 /* Link an element into the hash table
113185 */
113186 static void fts3HashInsertElement(
113187   Fts3Hash *pH,            /* The complete hash table */
113188   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
113189   Fts3HashElem *pNew       /* The element to be inserted */
113190 ){
113191   Fts3HashElem *pHead;     /* First element already in pEntry */
113192   pHead = pEntry->chain;
113193   if( pHead ){
113194     pNew->next = pHead;
113195     pNew->prev = pHead->prev;
113196     if( pHead->prev ){ pHead->prev->next = pNew; }
113197     else             { pH->first = pNew; }
113198     pHead->prev = pNew;
113199   }else{
113200     pNew->next = pH->first;
113201     if( pH->first ){ pH->first->prev = pNew; }
113202     pNew->prev = 0;
113203     pH->first = pNew;
113204   }
113205   pEntry->count++;
113206   pEntry->chain = pNew;
113207 }
113208
113209
113210 /* Resize the hash table so that it cantains "new_size" buckets.
113211 ** "new_size" must be a power of 2.  The hash table might fail 
113212 ** to resize if sqliteMalloc() fails.
113213 **
113214 ** Return non-zero if a memory allocation error occurs.
113215 */
113216 static int fts3Rehash(Fts3Hash *pH, int new_size){
113217   struct _fts3ht *new_ht;          /* The new hash table */
113218   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
113219   int (*xHash)(const void*,int);   /* The hash function */
113220
113221   assert( (new_size & (new_size-1))==0 );
113222   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
113223   if( new_ht==0 ) return 1;
113224   fts3HashFree(pH->ht);
113225   pH->ht = new_ht;
113226   pH->htsize = new_size;
113227   xHash = ftsHashFunction(pH->keyClass);
113228   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
113229     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
113230     next_elem = elem->next;
113231     fts3HashInsertElement(pH, &new_ht[h], elem);
113232   }
113233   return 0;
113234 }
113235
113236 /* This function (for internal use only) locates an element in an
113237 ** hash table that matches the given key.  The hash for this key has
113238 ** already been computed and is passed as the 4th parameter.
113239 */
113240 static Fts3HashElem *fts3FindElementByHash(
113241   const Fts3Hash *pH, /* The pH to be searched */
113242   const void *pKey,   /* The key we are searching for */
113243   int nKey,
113244   int h               /* The hash for this key. */
113245 ){
113246   Fts3HashElem *elem;            /* Used to loop thru the element list */
113247   int count;                     /* Number of elements left to test */
113248   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
113249
113250   if( pH->ht ){
113251     struct _fts3ht *pEntry = &pH->ht[h];
113252     elem = pEntry->chain;
113253     count = pEntry->count;
113254     xCompare = ftsCompareFunction(pH->keyClass);
113255     while( count-- && elem ){
113256       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
113257         return elem;
113258       }
113259       elem = elem->next;
113260     }
113261   }
113262   return 0;
113263 }
113264
113265 /* Remove a single entry from the hash table given a pointer to that
113266 ** element and a hash on the element's key.
113267 */
113268 static void fts3RemoveElementByHash(
113269   Fts3Hash *pH,         /* The pH containing "elem" */
113270   Fts3HashElem* elem,   /* The element to be removed from the pH */
113271   int h                 /* Hash value for the element */
113272 ){
113273   struct _fts3ht *pEntry;
113274   if( elem->prev ){
113275     elem->prev->next = elem->next; 
113276   }else{
113277     pH->first = elem->next;
113278   }
113279   if( elem->next ){
113280     elem->next->prev = elem->prev;
113281   }
113282   pEntry = &pH->ht[h];
113283   if( pEntry->chain==elem ){
113284     pEntry->chain = elem->next;
113285   }
113286   pEntry->count--;
113287   if( pEntry->count<=0 ){
113288     pEntry->chain = 0;
113289   }
113290   if( pH->copyKey && elem->pKey ){
113291     fts3HashFree(elem->pKey);
113292   }
113293   fts3HashFree( elem );
113294   pH->count--;
113295   if( pH->count<=0 ){
113296     assert( pH->first==0 );
113297     assert( pH->count==0 );
113298     fts3HashClear(pH);
113299   }
113300 }
113301
113302 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
113303   const Fts3Hash *pH, 
113304   const void *pKey, 
113305   int nKey
113306 ){
113307   int h;                          /* A hash on key */
113308   int (*xHash)(const void*,int);  /* The hash function */
113309
113310   if( pH==0 || pH->ht==0 ) return 0;
113311   xHash = ftsHashFunction(pH->keyClass);
113312   assert( xHash!=0 );
113313   h = (*xHash)(pKey,nKey);
113314   assert( (pH->htsize & (pH->htsize-1))==0 );
113315   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
113316 }
113317
113318 /* 
113319 ** Attempt to locate an element of the hash table pH with a key
113320 ** that matches pKey,nKey.  Return the data for this element if it is
113321 ** found, or NULL if there is no match.
113322 */
113323 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
113324   Fts3HashElem *pElem;            /* The element that matches key (if any) */
113325
113326   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
113327   return pElem ? pElem->data : 0;
113328 }
113329
113330 /* Insert an element into the hash table pH.  The key is pKey,nKey
113331 ** and the data is "data".
113332 **
113333 ** If no element exists with a matching key, then a new
113334 ** element is created.  A copy of the key is made if the copyKey
113335 ** flag is set.  NULL is returned.
113336 **
113337 ** If another element already exists with the same key, then the
113338 ** new data replaces the old data and the old data is returned.
113339 ** The key is not copied in this instance.  If a malloc fails, then
113340 ** the new data is returned and the hash table is unchanged.
113341 **
113342 ** If the "data" parameter to this function is NULL, then the
113343 ** element corresponding to "key" is removed from the hash table.
113344 */
113345 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
113346   Fts3Hash *pH,        /* The hash table to insert into */
113347   const void *pKey,    /* The key */
113348   int nKey,            /* Number of bytes in the key */
113349   void *data           /* The data */
113350 ){
113351   int hraw;                 /* Raw hash value of the key */
113352   int h;                    /* the hash of the key modulo hash table size */
113353   Fts3HashElem *elem;       /* Used to loop thru the element list */
113354   Fts3HashElem *new_elem;   /* New element added to the pH */
113355   int (*xHash)(const void*,int);  /* The hash function */
113356
113357   assert( pH!=0 );
113358   xHash = ftsHashFunction(pH->keyClass);
113359   assert( xHash!=0 );
113360   hraw = (*xHash)(pKey, nKey);
113361   assert( (pH->htsize & (pH->htsize-1))==0 );
113362   h = hraw & (pH->htsize-1);
113363   elem = fts3FindElementByHash(pH,pKey,nKey,h);
113364   if( elem ){
113365     void *old_data = elem->data;
113366     if( data==0 ){
113367       fts3RemoveElementByHash(pH,elem,h);
113368     }else{
113369       elem->data = data;
113370     }
113371     return old_data;
113372   }
113373   if( data==0 ) return 0;
113374   if( (pH->htsize==0 && fts3Rehash(pH,8))
113375    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
113376   ){
113377     pH->count = 0;
113378     return data;
113379   }
113380   assert( pH->htsize>0 );
113381   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
113382   if( new_elem==0 ) return data;
113383   if( pH->copyKey && pKey!=0 ){
113384     new_elem->pKey = fts3HashMalloc( nKey );
113385     if( new_elem->pKey==0 ){
113386       fts3HashFree(new_elem);
113387       return data;
113388     }
113389     memcpy((void*)new_elem->pKey, pKey, nKey);
113390   }else{
113391     new_elem->pKey = (void*)pKey;
113392   }
113393   new_elem->nKey = nKey;
113394   pH->count++;
113395   assert( pH->htsize>0 );
113396   assert( (pH->htsize & (pH->htsize-1))==0 );
113397   h = hraw & (pH->htsize-1);
113398   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
113399   new_elem->data = data;
113400   return 0;
113401 }
113402
113403 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
113404
113405 /************** End of fts3_hash.c *******************************************/
113406 /************** Begin file fts3_porter.c *************************************/
113407 /*
113408 ** 2006 September 30
113409 **
113410 ** The author disclaims copyright to this source code.  In place of
113411 ** a legal notice, here is a blessing:
113412 **
113413 **    May you do good and not evil.
113414 **    May you find forgiveness for yourself and forgive others.
113415 **    May you share freely, never taking more than you give.
113416 **
113417 *************************************************************************
113418 ** Implementation of the full-text-search tokenizer that implements
113419 ** a Porter stemmer.
113420 */
113421
113422 /*
113423 ** The code in this file is only compiled if:
113424 **
113425 **     * The FTS3 module is being built as an extension
113426 **       (in which case SQLITE_CORE is not defined), or
113427 **
113428 **     * The FTS3 module is being built into the core of
113429 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
113430 */
113431 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
113432
113433
113434
113435
113436 /*
113437 ** Class derived from sqlite3_tokenizer
113438 */
113439 typedef struct porter_tokenizer {
113440   sqlite3_tokenizer base;      /* Base class */
113441 } porter_tokenizer;
113442
113443 /*
113444 ** Class derived from sqlit3_tokenizer_cursor
113445 */
113446 typedef struct porter_tokenizer_cursor {
113447   sqlite3_tokenizer_cursor base;
113448   const char *zInput;          /* input we are tokenizing */
113449   int nInput;                  /* size of the input */
113450   int iOffset;                 /* current position in zInput */
113451   int iToken;                  /* index of next token to be returned */
113452   char *zToken;                /* storage for current token */
113453   int nAllocated;              /* space allocated to zToken buffer */
113454 } porter_tokenizer_cursor;
113455
113456
113457 /*
113458 ** Create a new tokenizer instance.
113459 */
113460 static int porterCreate(
113461   int argc, const char * const *argv,
113462   sqlite3_tokenizer **ppTokenizer
113463 ){
113464   porter_tokenizer *t;
113465
113466   UNUSED_PARAMETER(argc);
113467   UNUSED_PARAMETER(argv);
113468
113469   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
113470   if( t==NULL ) return SQLITE_NOMEM;
113471   memset(t, 0, sizeof(*t));
113472   *ppTokenizer = &t->base;
113473   return SQLITE_OK;
113474 }
113475
113476 /*
113477 ** Destroy a tokenizer
113478 */
113479 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
113480   sqlite3_free(pTokenizer);
113481   return SQLITE_OK;
113482 }
113483
113484 /*
113485 ** Prepare to begin tokenizing a particular string.  The input
113486 ** string to be tokenized is zInput[0..nInput-1].  A cursor
113487 ** used to incrementally tokenize this string is returned in 
113488 ** *ppCursor.
113489 */
113490 static int porterOpen(
113491   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
113492   const char *zInput, int nInput,        /* String to be tokenized */
113493   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
113494 ){
113495   porter_tokenizer_cursor *c;
113496
113497   UNUSED_PARAMETER(pTokenizer);
113498
113499   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
113500   if( c==NULL ) return SQLITE_NOMEM;
113501
113502   c->zInput = zInput;
113503   if( zInput==0 ){
113504     c->nInput = 0;
113505   }else if( nInput<0 ){
113506     c->nInput = (int)strlen(zInput);
113507   }else{
113508     c->nInput = nInput;
113509   }
113510   c->iOffset = 0;                 /* start tokenizing at the beginning */
113511   c->iToken = 0;
113512   c->zToken = NULL;               /* no space allocated, yet. */
113513   c->nAllocated = 0;
113514
113515   *ppCursor = &c->base;
113516   return SQLITE_OK;
113517 }
113518
113519 /*
113520 ** Close a tokenization cursor previously opened by a call to
113521 ** porterOpen() above.
113522 */
113523 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
113524   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
113525   sqlite3_free(c->zToken);
113526   sqlite3_free(c);
113527   return SQLITE_OK;
113528 }
113529 /*
113530 ** Vowel or consonant
113531 */
113532 static const char cType[] = {
113533    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
113534    1, 1, 1, 2, 1
113535 };
113536
113537 /*
113538 ** isConsonant() and isVowel() determine if their first character in
113539 ** the string they point to is a consonant or a vowel, according
113540 ** to Porter ruls.  
113541 **
113542 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
113543 ** 'Y' is a consonant unless it follows another consonant,
113544 ** in which case it is a vowel.
113545 **
113546 ** In these routine, the letters are in reverse order.  So the 'y' rule
113547 ** is that 'y' is a consonant unless it is followed by another
113548 ** consonent.
113549 */
113550 static int isVowel(const char*);
113551 static int isConsonant(const char *z){
113552   int j;
113553   char x = *z;
113554   if( x==0 ) return 0;
113555   assert( x>='a' && x<='z' );
113556   j = cType[x-'a'];
113557   if( j<2 ) return j;
113558   return z[1]==0 || isVowel(z + 1);
113559 }
113560 static int isVowel(const char *z){
113561   int j;
113562   char x = *z;
113563   if( x==0 ) return 0;
113564   assert( x>='a' && x<='z' );
113565   j = cType[x-'a'];
113566   if( j<2 ) return 1-j;
113567   return isConsonant(z + 1);
113568 }
113569
113570 /*
113571 ** Let any sequence of one or more vowels be represented by V and let
113572 ** C be sequence of one or more consonants.  Then every word can be
113573 ** represented as:
113574 **
113575 **           [C] (VC){m} [V]
113576 **
113577 ** In prose:  A word is an optional consonant followed by zero or
113578 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
113579 ** number of vowel consonant pairs.  This routine computes the value
113580 ** of m for the first i bytes of a word.
113581 **
113582 ** Return true if the m-value for z is 1 or more.  In other words,
113583 ** return true if z contains at least one vowel that is followed
113584 ** by a consonant.
113585 **
113586 ** In this routine z[] is in reverse order.  So we are really looking
113587 ** for an instance of of a consonant followed by a vowel.
113588 */
113589 static int m_gt_0(const char *z){
113590   while( isVowel(z) ){ z++; }
113591   if( *z==0 ) return 0;
113592   while( isConsonant(z) ){ z++; }
113593   return *z!=0;
113594 }
113595
113596 /* Like mgt0 above except we are looking for a value of m which is
113597 ** exactly 1
113598 */
113599 static int m_eq_1(const char *z){
113600   while( isVowel(z) ){ z++; }
113601   if( *z==0 ) return 0;
113602   while( isConsonant(z) ){ z++; }
113603   if( *z==0 ) return 0;
113604   while( isVowel(z) ){ z++; }
113605   if( *z==0 ) return 1;
113606   while( isConsonant(z) ){ z++; }
113607   return *z==0;
113608 }
113609
113610 /* Like mgt0 above except we are looking for a value of m>1 instead
113611 ** or m>0
113612 */
113613 static int m_gt_1(const char *z){
113614   while( isVowel(z) ){ z++; }
113615   if( *z==0 ) return 0;
113616   while( isConsonant(z) ){ z++; }
113617   if( *z==0 ) return 0;
113618   while( isVowel(z) ){ z++; }
113619   if( *z==0 ) return 0;
113620   while( isConsonant(z) ){ z++; }
113621   return *z!=0;
113622 }
113623
113624 /*
113625 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
113626 */
113627 static int hasVowel(const char *z){
113628   while( isConsonant(z) ){ z++; }
113629   return *z!=0;
113630 }
113631
113632 /*
113633 ** Return TRUE if the word ends in a double consonant.
113634 **
113635 ** The text is reversed here. So we are really looking at
113636 ** the first two characters of z[].
113637 */
113638 static int doubleConsonant(const char *z){
113639   return isConsonant(z) && z[0]==z[1];
113640 }
113641
113642 /*
113643 ** Return TRUE if the word ends with three letters which
113644 ** are consonant-vowel-consonent and where the final consonant
113645 ** is not 'w', 'x', or 'y'.
113646 **
113647 ** The word is reversed here.  So we are really checking the
113648 ** first three letters and the first one cannot be in [wxy].
113649 */
113650 static int star_oh(const char *z){
113651   return
113652     isConsonant(z) &&
113653     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
113654     isVowel(z+1) &&
113655     isConsonant(z+2);
113656 }
113657
113658 /*
113659 ** If the word ends with zFrom and xCond() is true for the stem
113660 ** of the word that preceeds the zFrom ending, then change the 
113661 ** ending to zTo.
113662 **
113663 ** The input word *pz and zFrom are both in reverse order.  zTo
113664 ** is in normal order. 
113665 **
113666 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
113667 ** match.  Not that TRUE is returned even if xCond() fails and
113668 ** no substitution occurs.
113669 */
113670 static int stem(
113671   char **pz,             /* The word being stemmed (Reversed) */
113672   const char *zFrom,     /* If the ending matches this... (Reversed) */
113673   const char *zTo,       /* ... change the ending to this (not reversed) */
113674   int (*xCond)(const char*)   /* Condition that must be true */
113675 ){
113676   char *z = *pz;
113677   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
113678   if( *zFrom!=0 ) return 0;
113679   if( xCond && !xCond(z) ) return 1;
113680   while( *zTo ){
113681     *(--z) = *(zTo++);
113682   }
113683   *pz = z;
113684   return 1;
113685 }
113686
113687 /*
113688 ** This is the fallback stemmer used when the porter stemmer is
113689 ** inappropriate.  The input word is copied into the output with
113690 ** US-ASCII case folding.  If the input word is too long (more
113691 ** than 20 bytes if it contains no digits or more than 6 bytes if
113692 ** it contains digits) then word is truncated to 20 or 6 bytes
113693 ** by taking 10 or 3 bytes from the beginning and end.
113694 */
113695 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
113696   int i, mx, j;
113697   int hasDigit = 0;
113698   for(i=0; i<nIn; i++){
113699     char c = zIn[i];
113700     if( c>='A' && c<='Z' ){
113701       zOut[i] = c - 'A' + 'a';
113702     }else{
113703       if( c>='0' && c<='9' ) hasDigit = 1;
113704       zOut[i] = c;
113705     }
113706   }
113707   mx = hasDigit ? 3 : 10;
113708   if( nIn>mx*2 ){
113709     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
113710       zOut[j] = zOut[i];
113711     }
113712     i = j;
113713   }
113714   zOut[i] = 0;
113715   *pnOut = i;
113716 }
113717
113718
113719 /*
113720 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
113721 ** zOut is at least big enough to hold nIn bytes.  Write the actual
113722 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
113723 **
113724 ** Any upper-case characters in the US-ASCII character set ([A-Z])
113725 ** are converted to lower case.  Upper-case UTF characters are
113726 ** unchanged.
113727 **
113728 ** Words that are longer than about 20 bytes are stemmed by retaining
113729 ** a few bytes from the beginning and the end of the word.  If the
113730 ** word contains digits, 3 bytes are taken from the beginning and
113731 ** 3 bytes from the end.  For long words without digits, 10 bytes
113732 ** are taken from each end.  US-ASCII case folding still applies.
113733 ** 
113734 ** If the input word contains not digits but does characters not 
113735 ** in [a-zA-Z] then no stemming is attempted and this routine just 
113736 ** copies the input into the input into the output with US-ASCII
113737 ** case folding.
113738 **
113739 ** Stemming never increases the length of the word.  So there is
113740 ** no chance of overflowing the zOut buffer.
113741 */
113742 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
113743   int i, j;
113744   char zReverse[28];
113745   char *z, *z2;
113746   if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
113747     /* The word is too big or too small for the porter stemmer.
113748     ** Fallback to the copy stemmer */
113749     copy_stemmer(zIn, nIn, zOut, pnOut);
113750     return;
113751   }
113752   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
113753     char c = zIn[i];
113754     if( c>='A' && c<='Z' ){
113755       zReverse[j] = c + 'a' - 'A';
113756     }else if( c>='a' && c<='z' ){
113757       zReverse[j] = c;
113758     }else{
113759       /* The use of a character not in [a-zA-Z] means that we fallback
113760       ** to the copy stemmer */
113761       copy_stemmer(zIn, nIn, zOut, pnOut);
113762       return;
113763     }
113764   }
113765   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
113766   z = &zReverse[j+1];
113767
113768
113769   /* Step 1a */
113770   if( z[0]=='s' ){
113771     if(
113772      !stem(&z, "sess", "ss", 0) &&
113773      !stem(&z, "sei", "i", 0)  &&
113774      !stem(&z, "ss", "ss", 0)
113775     ){
113776       z++;
113777     }
113778   }
113779
113780   /* Step 1b */  
113781   z2 = z;
113782   if( stem(&z, "dee", "ee", m_gt_0) ){
113783     /* Do nothing.  The work was all in the test */
113784   }else if( 
113785      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
113786       && z!=z2
113787   ){
113788      if( stem(&z, "ta", "ate", 0) ||
113789          stem(&z, "lb", "ble", 0) ||
113790          stem(&z, "zi", "ize", 0) ){
113791        /* Do nothing.  The work was all in the test */
113792      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
113793        z++;
113794      }else if( m_eq_1(z) && star_oh(z) ){
113795        *(--z) = 'e';
113796      }
113797   }
113798
113799   /* Step 1c */
113800   if( z[0]=='y' && hasVowel(z+1) ){
113801     z[0] = 'i';
113802   }
113803
113804   /* Step 2 */
113805   switch( z[1] ){
113806    case 'a':
113807      stem(&z, "lanoita", "ate", m_gt_0) ||
113808      stem(&z, "lanoit", "tion", m_gt_0);
113809      break;
113810    case 'c':
113811      stem(&z, "icne", "ence", m_gt_0) ||
113812      stem(&z, "icna", "ance", m_gt_0);
113813      break;
113814    case 'e':
113815      stem(&z, "rezi", "ize", m_gt_0);
113816      break;
113817    case 'g':
113818      stem(&z, "igol", "log", m_gt_0);
113819      break;
113820    case 'l':
113821      stem(&z, "ilb", "ble", m_gt_0) ||
113822      stem(&z, "illa", "al", m_gt_0) ||
113823      stem(&z, "iltne", "ent", m_gt_0) ||
113824      stem(&z, "ile", "e", m_gt_0) ||
113825      stem(&z, "ilsuo", "ous", m_gt_0);
113826      break;
113827    case 'o':
113828      stem(&z, "noitazi", "ize", m_gt_0) ||
113829      stem(&z, "noita", "ate", m_gt_0) ||
113830      stem(&z, "rota", "ate", m_gt_0);
113831      break;
113832    case 's':
113833      stem(&z, "msila", "al", m_gt_0) ||
113834      stem(&z, "ssenevi", "ive", m_gt_0) ||
113835      stem(&z, "ssenluf", "ful", m_gt_0) ||
113836      stem(&z, "ssensuo", "ous", m_gt_0);
113837      break;
113838    case 't':
113839      stem(&z, "itila", "al", m_gt_0) ||
113840      stem(&z, "itivi", "ive", m_gt_0) ||
113841      stem(&z, "itilib", "ble", m_gt_0);
113842      break;
113843   }
113844
113845   /* Step 3 */
113846   switch( z[0] ){
113847    case 'e':
113848      stem(&z, "etaci", "ic", m_gt_0) ||
113849      stem(&z, "evita", "", m_gt_0)   ||
113850      stem(&z, "ezila", "al", m_gt_0);
113851      break;
113852    case 'i':
113853      stem(&z, "itici", "ic", m_gt_0);
113854      break;
113855    case 'l':
113856      stem(&z, "laci", "ic", m_gt_0) ||
113857      stem(&z, "luf", "", m_gt_0);
113858      break;
113859    case 's':
113860      stem(&z, "ssen", "", m_gt_0);
113861      break;
113862   }
113863
113864   /* Step 4 */
113865   switch( z[1] ){
113866    case 'a':
113867      if( z[0]=='l' && m_gt_1(z+2) ){
113868        z += 2;
113869      }
113870      break;
113871    case 'c':
113872      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
113873        z += 4;
113874      }
113875      break;
113876    case 'e':
113877      if( z[0]=='r' && m_gt_1(z+2) ){
113878        z += 2;
113879      }
113880      break;
113881    case 'i':
113882      if( z[0]=='c' && m_gt_1(z+2) ){
113883        z += 2;
113884      }
113885      break;
113886    case 'l':
113887      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
113888        z += 4;
113889      }
113890      break;
113891    case 'n':
113892      if( z[0]=='t' ){
113893        if( z[2]=='a' ){
113894          if( m_gt_1(z+3) ){
113895            z += 3;
113896          }
113897        }else if( z[2]=='e' ){
113898          stem(&z, "tneme", "", m_gt_1) ||
113899          stem(&z, "tnem", "", m_gt_1) ||
113900          stem(&z, "tne", "", m_gt_1);
113901        }
113902      }
113903      break;
113904    case 'o':
113905      if( z[0]=='u' ){
113906        if( m_gt_1(z+2) ){
113907          z += 2;
113908        }
113909      }else if( z[3]=='s' || z[3]=='t' ){
113910        stem(&z, "noi", "", m_gt_1);
113911      }
113912      break;
113913    case 's':
113914      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
113915        z += 3;
113916      }
113917      break;
113918    case 't':
113919      stem(&z, "eta", "", m_gt_1) ||
113920      stem(&z, "iti", "", m_gt_1);
113921      break;
113922    case 'u':
113923      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
113924        z += 3;
113925      }
113926      break;
113927    case 'v':
113928    case 'z':
113929      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
113930        z += 3;
113931      }
113932      break;
113933   }
113934
113935   /* Step 5a */
113936   if( z[0]=='e' ){
113937     if( m_gt_1(z+1) ){
113938       z++;
113939     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
113940       z++;
113941     }
113942   }
113943
113944   /* Step 5b */
113945   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
113946     z++;
113947   }
113948
113949   /* z[] is now the stemmed word in reverse order.  Flip it back
113950   ** around into forward order and return.
113951   */
113952   *pnOut = i = (int)strlen(z);
113953   zOut[i] = 0;
113954   while( *z ){
113955     zOut[--i] = *(z++);
113956   }
113957 }
113958
113959 /*
113960 ** Characters that can be part of a token.  We assume any character
113961 ** whose value is greater than 0x80 (any UTF character) can be
113962 ** part of a token.  In other words, delimiters all must have
113963 ** values of 0x7f or lower.
113964 */
113965 static const char porterIdChar[] = {
113966 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
113967     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
113968     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
113969     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
113970     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
113971     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
113972 };
113973 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
113974
113975 /*
113976 ** Extract the next token from a tokenization cursor.  The cursor must
113977 ** have been opened by a prior call to porterOpen().
113978 */
113979 static int porterNext(
113980   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
113981   const char **pzToken,               /* OUT: *pzToken is the token text */
113982   int *pnBytes,                       /* OUT: Number of bytes in token */
113983   int *piStartOffset,                 /* OUT: Starting offset of token */
113984   int *piEndOffset,                   /* OUT: Ending offset of token */
113985   int *piPosition                     /* OUT: Position integer of token */
113986 ){
113987   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
113988   const char *z = c->zInput;
113989
113990   while( c->iOffset<c->nInput ){
113991     int iStartOffset, ch;
113992
113993     /* Scan past delimiter characters */
113994     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
113995       c->iOffset++;
113996     }
113997
113998     /* Count non-delimiter characters. */
113999     iStartOffset = c->iOffset;
114000     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
114001       c->iOffset++;
114002     }
114003
114004     if( c->iOffset>iStartOffset ){
114005       int n = c->iOffset-iStartOffset;
114006       if( n>c->nAllocated ){
114007         char *pNew;
114008         c->nAllocated = n+20;
114009         pNew = sqlite3_realloc(c->zToken, c->nAllocated);
114010         if( !pNew ) return SQLITE_NOMEM;
114011         c->zToken = pNew;
114012       }
114013       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
114014       *pzToken = c->zToken;
114015       *piStartOffset = iStartOffset;
114016       *piEndOffset = c->iOffset;
114017       *piPosition = c->iToken++;
114018       return SQLITE_OK;
114019     }
114020   }
114021   return SQLITE_DONE;
114022 }
114023
114024 /*
114025 ** The set of routines that implement the porter-stemmer tokenizer
114026 */
114027 static const sqlite3_tokenizer_module porterTokenizerModule = {
114028   0,
114029   porterCreate,
114030   porterDestroy,
114031   porterOpen,
114032   porterClose,
114033   porterNext,
114034 };
114035
114036 /*
114037 ** Allocate a new porter tokenizer.  Return a pointer to the new
114038 ** tokenizer in *ppModule
114039 */
114040 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
114041   sqlite3_tokenizer_module const**ppModule
114042 ){
114043   *ppModule = &porterTokenizerModule;
114044 }
114045
114046 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
114047
114048 /************** End of fts3_porter.c *****************************************/
114049 /************** Begin file fts3_tokenizer.c **********************************/
114050 /*
114051 ** 2007 June 22
114052 **
114053 ** The author disclaims copyright to this source code.  In place of
114054 ** a legal notice, here is a blessing:
114055 **
114056 **    May you do good and not evil.
114057 **    May you find forgiveness for yourself and forgive others.
114058 **    May you share freely, never taking more than you give.
114059 **
114060 ******************************************************************************
114061 **
114062 ** This is part of an SQLite module implementing full-text search.
114063 ** This particular file implements the generic tokenizer interface.
114064 */
114065
114066 /*
114067 ** The code in this file is only compiled if:
114068 **
114069 **     * The FTS3 module is being built as an extension
114070 **       (in which case SQLITE_CORE is not defined), or
114071 **
114072 **     * The FTS3 module is being built into the core of
114073 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
114074 */
114075 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
114076
114077 #ifndef SQLITE_CORE
114078   SQLITE_EXTENSION_INIT1
114079 #endif
114080
114081
114082 /*
114083 ** Implementation of the SQL scalar function for accessing the underlying 
114084 ** hash table. This function may be called as follows:
114085 **
114086 **   SELECT <function-name>(<key-name>);
114087 **   SELECT <function-name>(<key-name>, <pointer>);
114088 **
114089 ** where <function-name> is the name passed as the second argument
114090 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
114091 **
114092 ** If the <pointer> argument is specified, it must be a blob value
114093 ** containing a pointer to be stored as the hash data corresponding
114094 ** to the string <key-name>. If <pointer> is not specified, then
114095 ** the string <key-name> must already exist in the has table. Otherwise,
114096 ** an error is returned.
114097 **
114098 ** Whether or not the <pointer> argument is specified, the value returned
114099 ** is a blob containing the pointer stored as the hash data corresponding
114100 ** to string <key-name> (after the hash-table is updated, if applicable).
114101 */
114102 static void scalarFunc(
114103   sqlite3_context *context,
114104   int argc,
114105   sqlite3_value **argv
114106 ){
114107   Fts3Hash *pHash;
114108   void *pPtr = 0;
114109   const unsigned char *zName;
114110   int nName;
114111
114112   assert( argc==1 || argc==2 );
114113
114114   pHash = (Fts3Hash *)sqlite3_user_data(context);
114115
114116   zName = sqlite3_value_text(argv[0]);
114117   nName = sqlite3_value_bytes(argv[0])+1;
114118
114119   if( argc==2 ){
114120     void *pOld;
114121     int n = sqlite3_value_bytes(argv[1]);
114122     if( n!=sizeof(pPtr) ){
114123       sqlite3_result_error(context, "argument type mismatch", -1);
114124       return;
114125     }
114126     pPtr = *(void **)sqlite3_value_blob(argv[1]);
114127     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
114128     if( pOld==pPtr ){
114129       sqlite3_result_error(context, "out of memory", -1);
114130       return;
114131     }
114132   }else{
114133     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
114134     if( !pPtr ){
114135       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
114136       sqlite3_result_error(context, zErr, -1);
114137       sqlite3_free(zErr);
114138       return;
114139     }
114140   }
114141
114142   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
114143 }
114144
114145 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
114146   static const char isFtsIdChar[] = {
114147       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
114148       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
114149       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
114150       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
114151       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
114152       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
114153       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
114154       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
114155   };
114156   return (c&0x80 || isFtsIdChar[(int)(c)]);
114157 }
114158
114159 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
114160   const char *z1;
114161   const char *z2 = 0;
114162
114163   /* Find the start of the next token. */
114164   z1 = zStr;
114165   while( z2==0 ){
114166     char c = *z1;
114167     switch( c ){
114168       case '\0': return 0;        /* No more tokens here */
114169       case '\'':
114170       case '"':
114171       case '`': {
114172         z2 = z1;
114173         while( *++z2 && (*z2!=c || *++z2==c) );
114174         break;
114175       }
114176       case '[':
114177         z2 = &z1[1];
114178         while( *z2 && z2[0]!=']' ) z2++;
114179         if( *z2 ) z2++;
114180         break;
114181
114182       default:
114183         if( sqlite3Fts3IsIdChar(*z1) ){
114184           z2 = &z1[1];
114185           while( sqlite3Fts3IsIdChar(*z2) ) z2++;
114186         }else{
114187           z1++;
114188         }
114189     }
114190   }
114191
114192   *pn = (int)(z2-z1);
114193   return z1;
114194 }
114195
114196 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
114197   Fts3Hash *pHash,                /* Tokenizer hash table */
114198   const char *zArg,               /* Tokenizer name */
114199   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
114200   char **pzErr                    /* OUT: Set to malloced error message */
114201 ){
114202   int rc;
114203   char *z = (char *)zArg;
114204   int n;
114205   char *zCopy;
114206   char *zEnd;                     /* Pointer to nul-term of zCopy */
114207   sqlite3_tokenizer_module *m;
114208
114209   zCopy = sqlite3_mprintf("%s", zArg);
114210   if( !zCopy ) return SQLITE_NOMEM;
114211   zEnd = &zCopy[strlen(zCopy)];
114212
114213   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
114214   z[n] = '\0';
114215   sqlite3Fts3Dequote(z);
114216
114217   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
114218   if( !m ){
114219     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
114220     rc = SQLITE_ERROR;
114221   }else{
114222     char const **aArg = 0;
114223     int iArg = 0;
114224     z = &z[n+1];
114225     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
114226       int nNew = sizeof(char *)*(iArg+1);
114227       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
114228       if( !aNew ){
114229         sqlite3_free(zCopy);
114230         sqlite3_free((void *)aArg);
114231         return SQLITE_NOMEM;
114232       }
114233       aArg = aNew;
114234       aArg[iArg++] = z;
114235       z[n] = '\0';
114236       sqlite3Fts3Dequote(z);
114237       z = &z[n+1];
114238     }
114239     rc = m->xCreate(iArg, aArg, ppTok);
114240     assert( rc!=SQLITE_OK || *ppTok );
114241     if( rc!=SQLITE_OK ){
114242       *pzErr = sqlite3_mprintf("unknown tokenizer");
114243     }else{
114244       (*ppTok)->pModule = m; 
114245     }
114246     sqlite3_free((void *)aArg);
114247   }
114248
114249   sqlite3_free(zCopy);
114250   return rc;
114251 }
114252
114253
114254 #ifdef SQLITE_TEST
114255
114256
114257 /*
114258 ** Implementation of a special SQL scalar function for testing tokenizers 
114259 ** designed to be used in concert with the Tcl testing framework. This
114260 ** function must be called with two arguments:
114261 **
114262 **   SELECT <function-name>(<key-name>, <input-string>);
114263 **   SELECT <function-name>(<key-name>, <pointer>);
114264 **
114265 ** where <function-name> is the name passed as the second argument
114266 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
114267 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
114268 **
114269 ** The return value is a string that may be interpreted as a Tcl
114270 ** list. For each token in the <input-string>, three elements are
114271 ** added to the returned list. The first is the token position, the 
114272 ** second is the token text (folded, stemmed, etc.) and the third is the
114273 ** substring of <input-string> associated with the token. For example, 
114274 ** using the built-in "simple" tokenizer:
114275 **
114276 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
114277 **
114278 ** will return the string:
114279 **
114280 **   "{0 i I 1 dont don't 2 see see 3 how how}"
114281 **   
114282 */
114283 static void testFunc(
114284   sqlite3_context *context,
114285   int argc,
114286   sqlite3_value **argv
114287 ){
114288   Fts3Hash *pHash;
114289   sqlite3_tokenizer_module *p;
114290   sqlite3_tokenizer *pTokenizer = 0;
114291   sqlite3_tokenizer_cursor *pCsr = 0;
114292
114293   const char *zErr = 0;
114294
114295   const char *zName;
114296   int nName;
114297   const char *zInput;
114298   int nInput;
114299
114300   const char *zArg = 0;
114301
114302   const char *zToken;
114303   int nToken;
114304   int iStart;
114305   int iEnd;
114306   int iPos;
114307
114308   Tcl_Obj *pRet;
114309
114310   assert( argc==2 || argc==3 );
114311
114312   nName = sqlite3_value_bytes(argv[0]);
114313   zName = (const char *)sqlite3_value_text(argv[0]);
114314   nInput = sqlite3_value_bytes(argv[argc-1]);
114315   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
114316
114317   if( argc==3 ){
114318     zArg = (const char *)sqlite3_value_text(argv[1]);
114319   }
114320
114321   pHash = (Fts3Hash *)sqlite3_user_data(context);
114322   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
114323
114324   if( !p ){
114325     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
114326     sqlite3_result_error(context, zErr, -1);
114327     sqlite3_free(zErr);
114328     return;
114329   }
114330
114331   pRet = Tcl_NewObj();
114332   Tcl_IncrRefCount(pRet);
114333
114334   if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
114335     zErr = "error in xCreate()";
114336     goto finish;
114337   }
114338   pTokenizer->pModule = p;
114339   if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
114340     zErr = "error in xOpen()";
114341     goto finish;
114342   }
114343   pCsr->pTokenizer = pTokenizer;
114344
114345   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
114346     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
114347     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
114348     zToken = &zInput[iStart];
114349     nToken = iEnd-iStart;
114350     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
114351   }
114352
114353   if( SQLITE_OK!=p->xClose(pCsr) ){
114354     zErr = "error in xClose()";
114355     goto finish;
114356   }
114357   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
114358     zErr = "error in xDestroy()";
114359     goto finish;
114360   }
114361
114362 finish:
114363   if( zErr ){
114364     sqlite3_result_error(context, zErr, -1);
114365   }else{
114366     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
114367   }
114368   Tcl_DecrRefCount(pRet);
114369 }
114370
114371 static
114372 int registerTokenizer(
114373   sqlite3 *db, 
114374   char *zName, 
114375   const sqlite3_tokenizer_module *p
114376 ){
114377   int rc;
114378   sqlite3_stmt *pStmt;
114379   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
114380
114381   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
114382   if( rc!=SQLITE_OK ){
114383     return rc;
114384   }
114385
114386   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
114387   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
114388   sqlite3_step(pStmt);
114389
114390   return sqlite3_finalize(pStmt);
114391 }
114392
114393 static
114394 int queryTokenizer(
114395   sqlite3 *db, 
114396   char *zName,  
114397   const sqlite3_tokenizer_module **pp
114398 ){
114399   int rc;
114400   sqlite3_stmt *pStmt;
114401   const char zSql[] = "SELECT fts3_tokenizer(?)";
114402
114403   *pp = 0;
114404   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
114405   if( rc!=SQLITE_OK ){
114406     return rc;
114407   }
114408
114409   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
114410   if( SQLITE_ROW==sqlite3_step(pStmt) ){
114411     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
114412       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
114413     }
114414   }
114415
114416   return sqlite3_finalize(pStmt);
114417 }
114418
114419 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
114420
114421 /*
114422 ** Implementation of the scalar function fts3_tokenizer_internal_test().
114423 ** This function is used for testing only, it is not included in the
114424 ** build unless SQLITE_TEST is defined.
114425 **
114426 ** The purpose of this is to test that the fts3_tokenizer() function
114427 ** can be used as designed by the C-code in the queryTokenizer and
114428 ** registerTokenizer() functions above. These two functions are repeated
114429 ** in the README.tokenizer file as an example, so it is important to
114430 ** test them.
114431 **
114432 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
114433 ** function with no arguments. An assert() will fail if a problem is
114434 ** detected. i.e.:
114435 **
114436 **     SELECT fts3_tokenizer_internal_test();
114437 **
114438 */
114439 static void intTestFunc(
114440   sqlite3_context *context,
114441   int argc,
114442   sqlite3_value **argv
114443 ){
114444   int rc;
114445   const sqlite3_tokenizer_module *p1;
114446   const sqlite3_tokenizer_module *p2;
114447   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
114448
114449   UNUSED_PARAMETER(argc);
114450   UNUSED_PARAMETER(argv);
114451
114452   /* Test the query function */
114453   sqlite3Fts3SimpleTokenizerModule(&p1);
114454   rc = queryTokenizer(db, "simple", &p2);
114455   assert( rc==SQLITE_OK );
114456   assert( p1==p2 );
114457   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
114458   assert( rc==SQLITE_ERROR );
114459   assert( p2==0 );
114460   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
114461
114462   /* Test the storage function */
114463   rc = registerTokenizer(db, "nosuchtokenizer", p1);
114464   assert( rc==SQLITE_OK );
114465   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
114466   assert( rc==SQLITE_OK );
114467   assert( p2==p1 );
114468
114469   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
114470 }
114471
114472 #endif
114473
114474 /*
114475 ** Set up SQL objects in database db used to access the contents of
114476 ** the hash table pointed to by argument pHash. The hash table must
114477 ** been initialised to use string keys, and to take a private copy 
114478 ** of the key when a value is inserted. i.e. by a call similar to:
114479 **
114480 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
114481 **
114482 ** This function adds a scalar function (see header comment above
114483 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
114484 ** defined at compilation time, a temporary virtual table (see header 
114485 ** comment above struct HashTableVtab) to the database schema. Both 
114486 ** provide read/write access to the contents of *pHash.
114487 **
114488 ** The third argument to this function, zName, is used as the name
114489 ** of both the scalar and, if created, the virtual table.
114490 */
114491 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
114492   sqlite3 *db, 
114493   Fts3Hash *pHash, 
114494   const char *zName
114495 ){
114496   int rc = SQLITE_OK;
114497   void *p = (void *)pHash;
114498   const int any = SQLITE_ANY;
114499
114500 #ifdef SQLITE_TEST
114501   char *zTest = 0;
114502   char *zTest2 = 0;
114503   void *pdb = (void *)db;
114504   zTest = sqlite3_mprintf("%s_test", zName);
114505   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
114506   if( !zTest || !zTest2 ){
114507     rc = SQLITE_NOMEM;
114508   }
114509 #endif
114510
114511   if( SQLITE_OK==rc ){
114512     rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
114513   }
114514   if( SQLITE_OK==rc ){
114515     rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
114516   }
114517 #ifdef SQLITE_TEST
114518   if( SQLITE_OK==rc ){
114519     rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0);
114520   }
114521   if( SQLITE_OK==rc ){
114522     rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0);
114523   }
114524   if( SQLITE_OK==rc ){
114525     rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
114526   }
114527 #endif
114528
114529 #ifdef SQLITE_TEST
114530   sqlite3_free(zTest);
114531   sqlite3_free(zTest2);
114532 #endif
114533
114534   return rc;
114535 }
114536
114537 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
114538
114539 /************** End of fts3_tokenizer.c **************************************/
114540 /************** Begin file fts3_tokenizer1.c *********************************/
114541 /*
114542 ** 2006 Oct 10
114543 **
114544 ** The author disclaims copyright to this source code.  In place of
114545 ** a legal notice, here is a blessing:
114546 **
114547 **    May you do good and not evil.
114548 **    May you find forgiveness for yourself and forgive others.
114549 **    May you share freely, never taking more than you give.
114550 **
114551 ******************************************************************************
114552 **
114553 ** Implementation of the "simple" full-text-search tokenizer.
114554 */
114555
114556 /*
114557 ** The code in this file is only compiled if:
114558 **
114559 **     * The FTS3 module is being built as an extension
114560 **       (in which case SQLITE_CORE is not defined), or
114561 **
114562 **     * The FTS3 module is being built into the core of
114563 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
114564 */
114565 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
114566
114567
114568
114569
114570 typedef struct simple_tokenizer {
114571   sqlite3_tokenizer base;
114572   char delim[128];             /* flag ASCII delimiters */
114573 } simple_tokenizer;
114574
114575 typedef struct simple_tokenizer_cursor {
114576   sqlite3_tokenizer_cursor base;
114577   const char *pInput;          /* input we are tokenizing */
114578   int nBytes;                  /* size of the input */
114579   int iOffset;                 /* current position in pInput */
114580   int iToken;                  /* index of next token to be returned */
114581   char *pToken;                /* storage for current token */
114582   int nTokenAllocated;         /* space allocated to zToken buffer */
114583 } simple_tokenizer_cursor;
114584
114585
114586 static int simpleDelim(simple_tokenizer *t, unsigned char c){
114587   return c<0x80 && t->delim[c];
114588 }
114589 static int fts3_isalnum(int x){
114590   return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
114591 }
114592
114593 /*
114594 ** Create a new tokenizer instance.
114595 */
114596 static int simpleCreate(
114597   int argc, const char * const *argv,
114598   sqlite3_tokenizer **ppTokenizer
114599 ){
114600   simple_tokenizer *t;
114601
114602   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
114603   if( t==NULL ) return SQLITE_NOMEM;
114604   memset(t, 0, sizeof(*t));
114605
114606   /* TODO(shess) Delimiters need to remain the same from run to run,
114607   ** else we need to reindex.  One solution would be a meta-table to
114608   ** track such information in the database, then we'd only want this
114609   ** information on the initial create.
114610   */
114611   if( argc>1 ){
114612     int i, n = (int)strlen(argv[1]);
114613     for(i=0; i<n; i++){
114614       unsigned char ch = argv[1][i];
114615       /* We explicitly don't support UTF-8 delimiters for now. */
114616       if( ch>=0x80 ){
114617         sqlite3_free(t);
114618         return SQLITE_ERROR;
114619       }
114620       t->delim[ch] = 1;
114621     }
114622   } else {
114623     /* Mark non-alphanumeric ASCII characters as delimiters */
114624     int i;
114625     for(i=1; i<0x80; i++){
114626       t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
114627     }
114628   }
114629
114630   *ppTokenizer = &t->base;
114631   return SQLITE_OK;
114632 }
114633
114634 /*
114635 ** Destroy a tokenizer
114636 */
114637 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
114638   sqlite3_free(pTokenizer);
114639   return SQLITE_OK;
114640 }
114641
114642 /*
114643 ** Prepare to begin tokenizing a particular string.  The input
114644 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
114645 ** used to incrementally tokenize this string is returned in 
114646 ** *ppCursor.
114647 */
114648 static int simpleOpen(
114649   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
114650   const char *pInput, int nBytes,        /* String to be tokenized */
114651   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
114652 ){
114653   simple_tokenizer_cursor *c;
114654
114655   UNUSED_PARAMETER(pTokenizer);
114656
114657   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
114658   if( c==NULL ) return SQLITE_NOMEM;
114659
114660   c->pInput = pInput;
114661   if( pInput==0 ){
114662     c->nBytes = 0;
114663   }else if( nBytes<0 ){
114664     c->nBytes = (int)strlen(pInput);
114665   }else{
114666     c->nBytes = nBytes;
114667   }
114668   c->iOffset = 0;                 /* start tokenizing at the beginning */
114669   c->iToken = 0;
114670   c->pToken = NULL;               /* no space allocated, yet. */
114671   c->nTokenAllocated = 0;
114672
114673   *ppCursor = &c->base;
114674   return SQLITE_OK;
114675 }
114676
114677 /*
114678 ** Close a tokenization cursor previously opened by a call to
114679 ** simpleOpen() above.
114680 */
114681 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
114682   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
114683   sqlite3_free(c->pToken);
114684   sqlite3_free(c);
114685   return SQLITE_OK;
114686 }
114687
114688 /*
114689 ** Extract the next token from a tokenization cursor.  The cursor must
114690 ** have been opened by a prior call to simpleOpen().
114691 */
114692 static int simpleNext(
114693   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
114694   const char **ppToken,               /* OUT: *ppToken is the token text */
114695   int *pnBytes,                       /* OUT: Number of bytes in token */
114696   int *piStartOffset,                 /* OUT: Starting offset of token */
114697   int *piEndOffset,                   /* OUT: Ending offset of token */
114698   int *piPosition                     /* OUT: Position integer of token */
114699 ){
114700   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
114701   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
114702   unsigned char *p = (unsigned char *)c->pInput;
114703
114704   while( c->iOffset<c->nBytes ){
114705     int iStartOffset;
114706
114707     /* Scan past delimiter characters */
114708     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
114709       c->iOffset++;
114710     }
114711
114712     /* Count non-delimiter characters. */
114713     iStartOffset = c->iOffset;
114714     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
114715       c->iOffset++;
114716     }
114717
114718     if( c->iOffset>iStartOffset ){
114719       int i, n = c->iOffset-iStartOffset;
114720       if( n>c->nTokenAllocated ){
114721         char *pNew;
114722         c->nTokenAllocated = n+20;
114723         pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
114724         if( !pNew ) return SQLITE_NOMEM;
114725         c->pToken = pNew;
114726       }
114727       for(i=0; i<n; i++){
114728         /* TODO(shess) This needs expansion to handle UTF-8
114729         ** case-insensitivity.
114730         */
114731         unsigned char ch = p[iStartOffset+i];
114732         c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
114733       }
114734       *ppToken = c->pToken;
114735       *pnBytes = n;
114736       *piStartOffset = iStartOffset;
114737       *piEndOffset = c->iOffset;
114738       *piPosition = c->iToken++;
114739
114740       return SQLITE_OK;
114741     }
114742   }
114743   return SQLITE_DONE;
114744 }
114745
114746 /*
114747 ** The set of routines that implement the simple tokenizer
114748 */
114749 static const sqlite3_tokenizer_module simpleTokenizerModule = {
114750   0,
114751   simpleCreate,
114752   simpleDestroy,
114753   simpleOpen,
114754   simpleClose,
114755   simpleNext,
114756 };
114757
114758 /*
114759 ** Allocate a new simple tokenizer.  Return a pointer to the new
114760 ** tokenizer in *ppModule
114761 */
114762 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
114763   sqlite3_tokenizer_module const**ppModule
114764 ){
114765   *ppModule = &simpleTokenizerModule;
114766 }
114767
114768 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
114769
114770 /************** End of fts3_tokenizer1.c *************************************/
114771 /************** Begin file fts3_write.c **************************************/
114772 /*
114773 ** 2009 Oct 23
114774 **
114775 ** The author disclaims copyright to this source code.  In place of
114776 ** a legal notice, here is a blessing:
114777 **
114778 **    May you do good and not evil.
114779 **    May you find forgiveness for yourself and forgive others.
114780 **    May you share freely, never taking more than you give.
114781 **
114782 ******************************************************************************
114783 **
114784 ** This file is part of the SQLite FTS3 extension module. Specifically,
114785 ** this file contains code to insert, update and delete rows from FTS3
114786 ** tables. It also contains code to merge FTS3 b-tree segments. Some
114787 ** of the sub-routines used to merge segments are also used by the query 
114788 ** code in fts3.c.
114789 */
114790
114791 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
114792
114793
114794 /*
114795 ** When full-text index nodes are loaded from disk, the buffer that they
114796 ** are loaded into has the following number of bytes of padding at the end 
114797 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
114798 ** of 920 bytes is allocated for it.
114799 **
114800 ** This means that if we have a pointer into a buffer containing node data,
114801 ** it is always safe to read up to two varints from it without risking an
114802 ** overread, even if the node data is corrupted.
114803 */
114804 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
114805
114806 typedef struct PendingList PendingList;
114807 typedef struct SegmentNode SegmentNode;
114808 typedef struct SegmentWriter SegmentWriter;
114809
114810 /*
114811 ** Data structure used while accumulating terms in the pending-terms hash
114812 ** table. The hash table entry maps from term (a string) to a malloc'd
114813 ** instance of this structure.
114814 */
114815 struct PendingList {
114816   int nData;
114817   char *aData;
114818   int nSpace;
114819   sqlite3_int64 iLastDocid;
114820   sqlite3_int64 iLastCol;
114821   sqlite3_int64 iLastPos;
114822 };
114823
114824
114825 /*
114826 ** Each cursor has a (possibly empty) linked list of the following objects.
114827 */
114828 struct Fts3DeferredToken {
114829   Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
114830   int iCol;                       /* Column token must occur in */
114831   Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
114832   PendingList *pList;             /* Doclist is assembled here */
114833 };
114834
114835 /*
114836 ** An instance of this structure is used to iterate through the terms on
114837 ** a contiguous set of segment b-tree leaf nodes. Although the details of
114838 ** this structure are only manipulated by code in this file, opaque handles
114839 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
114840 ** terms when querying the full-text index. See functions:
114841 **
114842 **   sqlite3Fts3SegReaderNew()
114843 **   sqlite3Fts3SegReaderFree()
114844 **   sqlite3Fts3SegReaderCost()
114845 **   sqlite3Fts3SegReaderIterate()
114846 **
114847 ** Methods used to manipulate Fts3SegReader structures:
114848 **
114849 **   fts3SegReaderNext()
114850 **   fts3SegReaderFirstDocid()
114851 **   fts3SegReaderNextDocid()
114852 */
114853 struct Fts3SegReader {
114854   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
114855
114856   sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
114857   sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
114858   sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
114859   sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
114860
114861   char *aNode;                    /* Pointer to node data (or NULL) */
114862   int nNode;                      /* Size of buffer at aNode (or 0) */
114863   Fts3HashElem **ppNextElem;
114864
114865   /* Variables set by fts3SegReaderNext(). These may be read directly
114866   ** by the caller. They are valid from the time SegmentReaderNew() returns
114867   ** until SegmentReaderNext() returns something other than SQLITE_OK
114868   ** (i.e. SQLITE_DONE).
114869   */
114870   int nTerm;                      /* Number of bytes in current term */
114871   char *zTerm;                    /* Pointer to current term */
114872   int nTermAlloc;                 /* Allocated size of zTerm buffer */
114873   char *aDoclist;                 /* Pointer to doclist of current entry */
114874   int nDoclist;                   /* Size of doclist in current entry */
114875
114876   /* The following variables are used to iterate through the current doclist */
114877   char *pOffsetList;
114878   sqlite3_int64 iDocid;
114879 };
114880
114881 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
114882 #define fts3SegReaderIsRootOnly(p) ((p)->aNode==(char *)&(p)[1])
114883
114884 /*
114885 ** An instance of this structure is used to create a segment b-tree in the
114886 ** database. The internal details of this type are only accessed by the
114887 ** following functions:
114888 **
114889 **   fts3SegWriterAdd()
114890 **   fts3SegWriterFlush()
114891 **   fts3SegWriterFree()
114892 */
114893 struct SegmentWriter {
114894   SegmentNode *pTree;             /* Pointer to interior tree structure */
114895   sqlite3_int64 iFirst;           /* First slot in %_segments written */
114896   sqlite3_int64 iFree;            /* Next free slot in %_segments */
114897   char *zTerm;                    /* Pointer to previous term buffer */
114898   int nTerm;                      /* Number of bytes in zTerm */
114899   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
114900   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
114901   int nSize;                      /* Size of allocation at aData */
114902   int nData;                      /* Bytes of data in aData */
114903   char *aData;                    /* Pointer to block from malloc() */
114904 };
114905
114906 /*
114907 ** Type SegmentNode is used by the following three functions to create
114908 ** the interior part of the segment b+-tree structures (everything except
114909 ** the leaf nodes). These functions and type are only ever used by code
114910 ** within the fts3SegWriterXXX() family of functions described above.
114911 **
114912 **   fts3NodeAddTerm()
114913 **   fts3NodeWrite()
114914 **   fts3NodeFree()
114915 */
114916 struct SegmentNode {
114917   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
114918   SegmentNode *pRight;            /* Pointer to right-sibling */
114919   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
114920   int nEntry;                     /* Number of terms written to node so far */
114921   char *zTerm;                    /* Pointer to previous term buffer */
114922   int nTerm;                      /* Number of bytes in zTerm */
114923   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
114924   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
114925   int nData;                      /* Bytes of valid data so far */
114926   char *aData;                    /* Node data */
114927 };
114928
114929 /*
114930 ** Valid values for the second argument to fts3SqlStmt().
114931 */
114932 #define SQL_DELETE_CONTENT             0
114933 #define SQL_IS_EMPTY                   1
114934 #define SQL_DELETE_ALL_CONTENT         2 
114935 #define SQL_DELETE_ALL_SEGMENTS        3
114936 #define SQL_DELETE_ALL_SEGDIR          4
114937 #define SQL_DELETE_ALL_DOCSIZE         5
114938 #define SQL_DELETE_ALL_STAT            6
114939 #define SQL_SELECT_CONTENT_BY_ROWID    7
114940 #define SQL_NEXT_SEGMENT_INDEX         8
114941 #define SQL_INSERT_SEGMENTS            9
114942 #define SQL_NEXT_SEGMENTS_ID          10
114943 #define SQL_INSERT_SEGDIR             11
114944 #define SQL_SELECT_LEVEL              12
114945 #define SQL_SELECT_ALL_LEVEL          13
114946 #define SQL_SELECT_LEVEL_COUNT        14
114947 #define SQL_SELECT_SEGDIR_COUNT_MAX   15
114948 #define SQL_DELETE_SEGDIR_BY_LEVEL    16
114949 #define SQL_DELETE_SEGMENTS_RANGE     17
114950 #define SQL_CONTENT_INSERT            18
114951 #define SQL_DELETE_DOCSIZE            19
114952 #define SQL_REPLACE_DOCSIZE           20
114953 #define SQL_SELECT_DOCSIZE            21
114954 #define SQL_SELECT_DOCTOTAL           22
114955 #define SQL_REPLACE_DOCTOTAL          23
114956
114957 /*
114958 ** This function is used to obtain an SQLite prepared statement handle
114959 ** for the statement identified by the second argument. If successful,
114960 ** *pp is set to the requested statement handle and SQLITE_OK returned.
114961 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
114962 **
114963 ** If argument apVal is not NULL, then it must point to an array with
114964 ** at least as many entries as the requested statement has bound 
114965 ** parameters. The values are bound to the statements parameters before
114966 ** returning.
114967 */
114968 static int fts3SqlStmt(
114969   Fts3Table *p,                   /* Virtual table handle */
114970   int eStmt,                      /* One of the SQL_XXX constants above */
114971   sqlite3_stmt **pp,              /* OUT: Statement handle */
114972   sqlite3_value **apVal           /* Values to bind to statement */
114973 ){
114974   const char *azSql[] = {
114975 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
114976 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
114977 /* 2  */  "DELETE FROM %Q.'%q_content'",
114978 /* 3  */  "DELETE FROM %Q.'%q_segments'",
114979 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
114980 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
114981 /* 6  */  "DELETE FROM %Q.'%q_stat'",
114982 /* 7  */  "SELECT * FROM %Q.'%q_content' WHERE rowid=?",
114983 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
114984 /* 9  */  "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
114985 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
114986 /* 11 */  "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
114987
114988           /* Return segments in order from oldest to newest.*/ 
114989 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
114990             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
114991 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
114992             "FROM %Q.'%q_segdir' ORDER BY level DESC, idx ASC",
114993
114994 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
114995 /* 15 */  "SELECT count(*), max(level) FROM %Q.'%q_segdir'",
114996
114997 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
114998 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
114999 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%z)",
115000 /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
115001 /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
115002 /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
115003 /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=0",
115004 /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(0,?)",
115005   };
115006   int rc = SQLITE_OK;
115007   sqlite3_stmt *pStmt;
115008
115009   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
115010   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
115011   
115012   pStmt = p->aStmt[eStmt];
115013   if( !pStmt ){
115014     char *zSql;
115015     if( eStmt==SQL_CONTENT_INSERT ){
115016       int i;                      /* Iterator variable */  
115017       char *zVarlist;             /* The "?, ?, ..." string */
115018       zVarlist = (char *)sqlite3_malloc(2*p->nColumn+2);
115019       if( !zVarlist ){
115020         *pp = 0;
115021         return SQLITE_NOMEM;
115022       }
115023       zVarlist[0] = '?';
115024       zVarlist[p->nColumn*2+1] = '\0';
115025       for(i=1; i<=p->nColumn; i++){
115026         zVarlist[i*2-1] = ',';
115027         zVarlist[i*2] = '?';
115028       }
115029       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, zVarlist);
115030     }else{
115031       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
115032     }
115033     if( !zSql ){
115034       rc = SQLITE_NOMEM;
115035     }else{
115036       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
115037       sqlite3_free(zSql);
115038       assert( rc==SQLITE_OK || pStmt==0 );
115039       p->aStmt[eStmt] = pStmt;
115040     }
115041   }
115042   if( apVal ){
115043     int i;
115044     int nParam = sqlite3_bind_parameter_count(pStmt);
115045     for(i=0; rc==SQLITE_OK && i<nParam; i++){
115046       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
115047     }
115048   }
115049   *pp = pStmt;
115050   return rc;
115051 }
115052
115053 static int fts3SelectDocsize(
115054   Fts3Table *pTab,                /* FTS3 table handle */
115055   int eStmt,                      /* Either SQL_SELECT_DOCSIZE or DOCTOTAL */
115056   sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
115057   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
115058 ){
115059   sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
115060   int rc;                         /* Return code */
115061
115062   assert( eStmt==SQL_SELECT_DOCSIZE || eStmt==SQL_SELECT_DOCTOTAL );
115063
115064   rc = fts3SqlStmt(pTab, eStmt, &pStmt, 0);
115065   if( rc==SQLITE_OK ){
115066     if( eStmt==SQL_SELECT_DOCSIZE ){
115067       sqlite3_bind_int64(pStmt, 1, iDocid);
115068     }
115069     rc = sqlite3_step(pStmt);
115070     if( rc!=SQLITE_ROW ){
115071       rc = sqlite3_reset(pStmt);
115072       if( rc==SQLITE_OK ) rc = SQLITE_CORRUPT;
115073       pStmt = 0;
115074     }else{
115075       rc = SQLITE_OK;
115076     }
115077   }
115078
115079   *ppStmt = pStmt;
115080   return rc;
115081 }
115082
115083 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
115084   Fts3Table *pTab,                /* Fts3 table handle */
115085   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
115086 ){
115087   return fts3SelectDocsize(pTab, SQL_SELECT_DOCTOTAL, 0, ppStmt);
115088 }
115089
115090 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
115091   Fts3Table *pTab,                /* Fts3 table handle */
115092   sqlite3_int64 iDocid,           /* Docid to read size data for */
115093   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
115094 ){
115095   return fts3SelectDocsize(pTab, SQL_SELECT_DOCSIZE, iDocid, ppStmt);
115096 }
115097
115098 /*
115099 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
115100 ** array apVal[] to the SQL statement identified by eStmt, the statement
115101 ** is executed.
115102 **
115103 ** Returns SQLITE_OK if the statement is successfully executed, or an
115104 ** SQLite error code otherwise.
115105 */
115106 static void fts3SqlExec(
115107   int *pRC,                /* Result code */
115108   Fts3Table *p,            /* The FTS3 table */
115109   int eStmt,               /* Index of statement to evaluate */
115110   sqlite3_value **apVal    /* Parameters to bind */
115111 ){
115112   sqlite3_stmt *pStmt;
115113   int rc;
115114   if( *pRC ) return;
115115   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal); 
115116   if( rc==SQLITE_OK ){
115117     sqlite3_step(pStmt);
115118     rc = sqlite3_reset(pStmt);
115119   }
115120   *pRC = rc;
115121 }
115122
115123
115124 /*
115125 ** This function ensures that the caller has obtained a shared-cache
115126 ** table-lock on the %_content table. This is required before reading
115127 ** data from the fts3 table. If this lock is not acquired first, then
115128 ** the caller may end up holding read-locks on the %_segments and %_segdir
115129 ** tables, but no read-lock on the %_content table. If this happens 
115130 ** a second connection will be able to write to the fts3 table, but
115131 ** attempting to commit those writes might return SQLITE_LOCKED or
115132 ** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain 
115133 ** write-locks on the %_segments and %_segdir ** tables). 
115134 **
115135 ** We try to avoid this because if FTS3 returns any error when committing
115136 ** a transaction, the whole transaction will be rolled back. And this is
115137 ** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
115138 ** still happen if the user reads data directly from the %_segments or
115139 ** %_segdir tables instead of going through FTS3 though.
115140 */
115141 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
115142   int rc;                         /* Return code */
115143   sqlite3_stmt *pStmt;            /* Statement used to obtain lock */
115144
115145   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
115146   if( rc==SQLITE_OK ){
115147     sqlite3_bind_null(pStmt, 1);
115148     sqlite3_step(pStmt);
115149     rc = sqlite3_reset(pStmt);
115150   }
115151   return rc;
115152 }
115153
115154 /*
115155 ** Set *ppStmt to a statement handle that may be used to iterate through
115156 ** all rows in the %_segdir table, from oldest to newest. If successful,
115157 ** return SQLITE_OK. If an error occurs while preparing the statement, 
115158 ** return an SQLite error code.
115159 **
115160 ** There is only ever one instance of this SQL statement compiled for
115161 ** each FTS3 table.
115162 **
115163 ** The statement returns the following columns from the %_segdir table:
115164 **
115165 **   0: idx
115166 **   1: start_block
115167 **   2: leaves_end_block
115168 **   3: end_block
115169 **   4: root
115170 */
115171 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table *p, sqlite3_stmt **ppStmt){
115172   return fts3SqlStmt(p, SQL_SELECT_ALL_LEVEL, ppStmt, 0);
115173 }
115174
115175
115176 /*
115177 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
115178 ** if successful, or an SQLite error code otherwise.
115179 **
115180 ** This function also serves to allocate the PendingList structure itself.
115181 ** For example, to create a new PendingList structure containing two
115182 ** varints:
115183 **
115184 **   PendingList *p = 0;
115185 **   fts3PendingListAppendVarint(&p, 1);
115186 **   fts3PendingListAppendVarint(&p, 2);
115187 */
115188 static int fts3PendingListAppendVarint(
115189   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
115190   sqlite3_int64 i                 /* Value to append to data */
115191 ){
115192   PendingList *p = *pp;
115193
115194   /* Allocate or grow the PendingList as required. */
115195   if( !p ){
115196     p = sqlite3_malloc(sizeof(*p) + 100);
115197     if( !p ){
115198       return SQLITE_NOMEM;
115199     }
115200     p->nSpace = 100;
115201     p->aData = (char *)&p[1];
115202     p->nData = 0;
115203   }
115204   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
115205     int nNew = p->nSpace * 2;
115206     p = sqlite3_realloc(p, sizeof(*p) + nNew);
115207     if( !p ){
115208       sqlite3_free(*pp);
115209       *pp = 0;
115210       return SQLITE_NOMEM;
115211     }
115212     p->nSpace = nNew;
115213     p->aData = (char *)&p[1];
115214   }
115215
115216   /* Append the new serialized varint to the end of the list. */
115217   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
115218   p->aData[p->nData] = '\0';
115219   *pp = p;
115220   return SQLITE_OK;
115221 }
115222
115223 /*
115224 ** Add a docid/column/position entry to a PendingList structure. Non-zero
115225 ** is returned if the structure is sqlite3_realloced as part of adding
115226 ** the entry. Otherwise, zero.
115227 **
115228 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
115229 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
115230 ** it is set to SQLITE_OK.
115231 */
115232 static int fts3PendingListAppend(
115233   PendingList **pp,               /* IN/OUT: PendingList structure */
115234   sqlite3_int64 iDocid,           /* Docid for entry to add */
115235   sqlite3_int64 iCol,             /* Column for entry to add */
115236   sqlite3_int64 iPos,             /* Position of term for entry to add */
115237   int *pRc                        /* OUT: Return code */
115238 ){
115239   PendingList *p = *pp;
115240   int rc = SQLITE_OK;
115241
115242   assert( !p || p->iLastDocid<=iDocid );
115243
115244   if( !p || p->iLastDocid!=iDocid ){
115245     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
115246     if( p ){
115247       assert( p->nData<p->nSpace );
115248       assert( p->aData[p->nData]==0 );
115249       p->nData++;
115250     }
115251     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
115252       goto pendinglistappend_out;
115253     }
115254     p->iLastCol = -1;
115255     p->iLastPos = 0;
115256     p->iLastDocid = iDocid;
115257   }
115258   if( iCol>0 && p->iLastCol!=iCol ){
115259     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
115260      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
115261     ){
115262       goto pendinglistappend_out;
115263     }
115264     p->iLastCol = iCol;
115265     p->iLastPos = 0;
115266   }
115267   if( iCol>=0 ){
115268     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
115269     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
115270     if( rc==SQLITE_OK ){
115271       p->iLastPos = iPos;
115272     }
115273   }
115274
115275  pendinglistappend_out:
115276   *pRc = rc;
115277   if( p!=*pp ){
115278     *pp = p;
115279     return 1;
115280   }
115281   return 0;
115282 }
115283
115284 /*
115285 ** Tokenize the nul-terminated string zText and add all tokens to the
115286 ** pending-terms hash-table. The docid used is that currently stored in
115287 ** p->iPrevDocid, and the column is specified by argument iCol.
115288 **
115289 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
115290 */
115291 static int fts3PendingTermsAdd(
115292   Fts3Table *p,                   /* Table into which text will be inserted */
115293   const char *zText,              /* Text of document to be inserted */
115294   int iCol,                       /* Column into which text is being inserted */
115295   u32 *pnWord                     /* OUT: Number of tokens inserted */
115296 ){
115297   int rc;
115298   int iStart;
115299   int iEnd;
115300   int iPos;
115301   int nWord = 0;
115302
115303   char const *zToken;
115304   int nToken;
115305
115306   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
115307   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
115308   sqlite3_tokenizer_cursor *pCsr;
115309   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
115310       const char**,int*,int*,int*,int*);
115311
115312   assert( pTokenizer && pModule );
115313
115314   rc = pModule->xOpen(pTokenizer, zText, -1, &pCsr);
115315   if( rc!=SQLITE_OK ){
115316     return rc;
115317   }
115318   pCsr->pTokenizer = pTokenizer;
115319
115320   xNext = pModule->xNext;
115321   while( SQLITE_OK==rc
115322       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
115323   ){
115324     PendingList *pList;
115325  
115326     if( iPos>=nWord ) nWord = iPos+1;
115327
115328     /* Positions cannot be negative; we use -1 as a terminator internally.
115329     ** Tokens must have a non-zero length.
115330     */
115331     if( iPos<0 || !zToken || nToken<=0 ){
115332       rc = SQLITE_ERROR;
115333       break;
115334     }
115335
115336     pList = (PendingList *)fts3HashFind(&p->pendingTerms, zToken, nToken);
115337     if( pList ){
115338       p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
115339     }
115340     if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
115341       if( pList==fts3HashInsert(&p->pendingTerms, zToken, nToken, pList) ){
115342         /* Malloc failed while inserting the new entry. This can only 
115343         ** happen if there was no previous entry for this token.
115344         */
115345         assert( 0==fts3HashFind(&p->pendingTerms, zToken, nToken) );
115346         sqlite3_free(pList);
115347         rc = SQLITE_NOMEM;
115348       }
115349     }
115350     if( rc==SQLITE_OK ){
115351       p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
115352     }
115353   }
115354
115355   pModule->xClose(pCsr);
115356   *pnWord = nWord;
115357   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
115358 }
115359
115360 /* 
115361 ** Calling this function indicates that subsequent calls to 
115362 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
115363 ** contents of the document with docid iDocid.
115364 */
115365 static int fts3PendingTermsDocid(Fts3Table *p, sqlite_int64 iDocid){
115366   /* TODO(shess) Explore whether partially flushing the buffer on
115367   ** forced-flush would provide better performance.  I suspect that if
115368   ** we ordered the doclists by size and flushed the largest until the
115369   ** buffer was half empty, that would let the less frequent terms
115370   ** generate longer doclists.
115371   */
115372   if( iDocid<=p->iPrevDocid || p->nPendingData>p->nMaxPendingData ){
115373     int rc = sqlite3Fts3PendingTermsFlush(p);
115374     if( rc!=SQLITE_OK ) return rc;
115375   }
115376   p->iPrevDocid = iDocid;
115377   return SQLITE_OK;
115378 }
115379
115380 /*
115381 ** Discard the contents of the pending-terms hash table. 
115382 */
115383 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
115384   Fts3HashElem *pElem;
115385   for(pElem=fts3HashFirst(&p->pendingTerms); pElem; pElem=fts3HashNext(pElem)){
115386     sqlite3_free(fts3HashData(pElem));
115387   }
115388   fts3HashClear(&p->pendingTerms);
115389   p->nPendingData = 0;
115390 }
115391
115392 /*
115393 ** This function is called by the xUpdate() method as part of an INSERT
115394 ** operation. It adds entries for each term in the new record to the
115395 ** pendingTerms hash table.
115396 **
115397 ** Argument apVal is the same as the similarly named argument passed to
115398 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
115399 */
115400 static int fts3InsertTerms(Fts3Table *p, sqlite3_value **apVal, u32 *aSz){
115401   int i;                          /* Iterator variable */
115402   for(i=2; i<p->nColumn+2; i++){
115403     const char *zText = (const char *)sqlite3_value_text(apVal[i]);
115404     if( zText ){
115405       int rc = fts3PendingTermsAdd(p, zText, i-2, &aSz[i-2]);
115406       if( rc!=SQLITE_OK ){
115407         return rc;
115408       }
115409     }
115410     aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
115411   }
115412   return SQLITE_OK;
115413 }
115414
115415 /*
115416 ** This function is called by the xUpdate() method for an INSERT operation.
115417 ** The apVal parameter is passed a copy of the apVal argument passed by
115418 ** SQLite to the xUpdate() method. i.e:
115419 **
115420 **   apVal[0]                Not used for INSERT.
115421 **   apVal[1]                rowid
115422 **   apVal[2]                Left-most user-defined column
115423 **   ...
115424 **   apVal[p->nColumn+1]     Right-most user-defined column
115425 **   apVal[p->nColumn+2]     Hidden column with same name as table
115426 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
115427 */
115428 static int fts3InsertData(
115429   Fts3Table *p,                   /* Full-text table */
115430   sqlite3_value **apVal,          /* Array of values to insert */
115431   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
115432 ){
115433   int rc;                         /* Return code */
115434   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
115435
115436   /* Locate the statement handle used to insert data into the %_content
115437   ** table. The SQL for this statement is:
115438   **
115439   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
115440   **
115441   ** The statement features N '?' variables, where N is the number of user
115442   ** defined columns in the FTS3 table, plus one for the docid field.
115443   */
115444   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
115445   if( rc!=SQLITE_OK ){
115446     return rc;
115447   }
115448
115449   /* There is a quirk here. The users INSERT statement may have specified
115450   ** a value for the "rowid" field, for the "docid" field, or for both.
115451   ** Which is a problem, since "rowid" and "docid" are aliases for the
115452   ** same value. For example:
115453   **
115454   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
115455   **
115456   ** In FTS3, this is an error. It is an error to specify non-NULL values
115457   ** for both docid and some other rowid alias.
115458   */
115459   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
115460     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
115461      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
115462     ){
115463       /* A rowid/docid conflict. */
115464       return SQLITE_ERROR;
115465     }
115466     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
115467     if( rc!=SQLITE_OK ) return rc;
115468   }
115469
115470   /* Execute the statement to insert the record. Set *piDocid to the 
115471   ** new docid value. 
115472   */
115473   sqlite3_step(pContentInsert);
115474   rc = sqlite3_reset(pContentInsert);
115475
115476   *piDocid = sqlite3_last_insert_rowid(p->db);
115477   return rc;
115478 }
115479
115480
115481
115482 /*
115483 ** Remove all data from the FTS3 table. Clear the hash table containing
115484 ** pending terms.
115485 */
115486 static int fts3DeleteAll(Fts3Table *p){
115487   int rc = SQLITE_OK;             /* Return code */
115488
115489   /* Discard the contents of the pending-terms hash table. */
115490   sqlite3Fts3PendingTermsClear(p);
115491
115492   /* Delete everything from the %_content, %_segments and %_segdir tables. */
115493   fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
115494   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
115495   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
115496   if( p->bHasDocsize ){
115497     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
115498   }
115499   if( p->bHasStat ){
115500     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
115501   }
115502   return rc;
115503 }
115504
115505 /*
115506 ** The first element in the apVal[] array is assumed to contain the docid
115507 ** (an integer) of a row about to be deleted. Remove all terms from the
115508 ** full-text index.
115509 */
115510 static void fts3DeleteTerms( 
115511   int *pRC,               /* Result code */
115512   Fts3Table *p,           /* The FTS table to delete from */
115513   sqlite3_value **apVal,  /* apVal[] contains the docid to be deleted */
115514   u32 *aSz                /* Sizes of deleted document written here */
115515 ){
115516   int rc;
115517   sqlite3_stmt *pSelect;
115518
115519   if( *pRC ) return;
115520   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, apVal);
115521   if( rc==SQLITE_OK ){
115522     if( SQLITE_ROW==sqlite3_step(pSelect) ){
115523       int i;
115524       for(i=1; i<=p->nColumn; i++){
115525         const char *zText = (const char *)sqlite3_column_text(pSelect, i);
115526         rc = fts3PendingTermsAdd(p, zText, -1, &aSz[i-1]);
115527         if( rc!=SQLITE_OK ){
115528           sqlite3_reset(pSelect);
115529           *pRC = rc;
115530           return;
115531         }
115532         aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
115533       }
115534     }
115535     rc = sqlite3_reset(pSelect);
115536   }else{
115537     sqlite3_reset(pSelect);
115538   }
115539   *pRC = rc;
115540 }
115541
115542 /*
115543 ** Forward declaration to account for the circular dependency between
115544 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
115545 */
115546 static int fts3SegmentMerge(Fts3Table *, int);
115547
115548 /* 
115549 ** This function allocates a new level iLevel index in the segdir table.
115550 ** Usually, indexes are allocated within a level sequentially starting
115551 ** with 0, so the allocated index is one greater than the value returned
115552 ** by:
115553 **
115554 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
115555 **
115556 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
115557 ** level, they are merged into a single level (iLevel+1) segment and the 
115558 ** allocated index is 0.
115559 **
115560 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
115561 ** returned. Otherwise, an SQLite error code is returned.
115562 */
115563 static int fts3AllocateSegdirIdx(Fts3Table *p, int iLevel, int *piIdx){
115564   int rc;                         /* Return Code */
115565   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
115566   int iNext = 0;                  /* Result of query pNextIdx */
115567
115568   /* Set variable iNext to the next available segdir index at level iLevel. */
115569   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
115570   if( rc==SQLITE_OK ){
115571     sqlite3_bind_int(pNextIdx, 1, iLevel);
115572     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
115573       iNext = sqlite3_column_int(pNextIdx, 0);
115574     }
115575     rc = sqlite3_reset(pNextIdx);
115576   }
115577
115578   if( rc==SQLITE_OK ){
115579     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
115580     ** full, merge all segments in level iLevel into a single iLevel+1
115581     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
115582     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
115583     */
115584     if( iNext>=FTS3_MERGE_COUNT ){
115585       rc = fts3SegmentMerge(p, iLevel);
115586       *piIdx = 0;
115587     }else{
115588       *piIdx = iNext;
115589     }
115590   }
115591
115592   return rc;
115593 }
115594
115595 /*
115596 ** The %_segments table is declared as follows:
115597 **
115598 **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
115599 **
115600 ** This function reads data from a single row of the %_segments table. The
115601 ** specific row is identified by the iBlockid parameter. If paBlob is not
115602 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
115603 ** with the contents of the blob stored in the "block" column of the 
115604 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
115605 ** to the size of the blob in bytes before returning.
115606 **
115607 ** If an error occurs, or the table does not contain the specified row,
115608 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
115609 ** paBlob is non-NULL, then it is the responsibility of the caller to
115610 ** eventually free the returned buffer.
115611 **
115612 ** This function may leave an open sqlite3_blob* handle in the
115613 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
115614 ** to this function. The handle may be closed by calling the
115615 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
115616 ** performance improvement, but the blob handle should always be closed
115617 ** before control is returned to the user (to prevent a lock being held
115618 ** on the database file for longer than necessary). Thus, any virtual table
115619 ** method (xFilter etc.) that may directly or indirectly call this function
115620 ** must call sqlite3Fts3SegmentsClose() before returning.
115621 */
115622 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
115623   Fts3Table *p,                   /* FTS3 table handle */
115624   sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
115625   char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
115626   int *pnBlob                     /* OUT: Size of blob data */
115627 ){
115628   int rc;                         /* Return code */
115629
115630   /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
115631   assert( pnBlob);
115632
115633   if( p->pSegments ){
115634     rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
115635   }else{
115636     if( 0==p->zSegmentsTbl ){
115637       p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
115638       if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
115639     }
115640     rc = sqlite3_blob_open(
115641        p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
115642     );
115643   }
115644
115645   if( rc==SQLITE_OK ){
115646     int nByte = sqlite3_blob_bytes(p->pSegments);
115647     if( paBlob ){
115648       char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
115649       if( !aByte ){
115650         rc = SQLITE_NOMEM;
115651       }else{
115652         rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
115653         memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
115654         if( rc!=SQLITE_OK ){
115655           sqlite3_free(aByte);
115656           aByte = 0;
115657         }
115658       }
115659       *paBlob = aByte;
115660     }
115661     *pnBlob = nByte;
115662   }
115663
115664   return rc;
115665 }
115666
115667 /*
115668 ** Close the blob handle at p->pSegments, if it is open. See comments above
115669 ** the sqlite3Fts3ReadBlock() function for details.
115670 */
115671 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
115672   sqlite3_blob_close(p->pSegments);
115673   p->pSegments = 0;
115674 }
115675
115676 /*
115677 ** Move the iterator passed as the first argument to the next term in the
115678 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
115679 ** SQLITE_DONE. Otherwise, an SQLite error code.
115680 */
115681 static int fts3SegReaderNext(Fts3Table *p, Fts3SegReader *pReader){
115682   char *pNext;                    /* Cursor variable */
115683   int nPrefix;                    /* Number of bytes in term prefix */
115684   int nSuffix;                    /* Number of bytes in term suffix */
115685
115686   if( !pReader->aDoclist ){
115687     pNext = pReader->aNode;
115688   }else{
115689     pNext = &pReader->aDoclist[pReader->nDoclist];
115690   }
115691
115692   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
115693     int rc;                       /* Return code from Fts3ReadBlock() */
115694
115695     if( fts3SegReaderIsPending(pReader) ){
115696       Fts3HashElem *pElem = *(pReader->ppNextElem);
115697       if( pElem==0 ){
115698         pReader->aNode = 0;
115699       }else{
115700         PendingList *pList = (PendingList *)fts3HashData(pElem);
115701         pReader->zTerm = (char *)fts3HashKey(pElem);
115702         pReader->nTerm = fts3HashKeysize(pElem);
115703         pReader->nNode = pReader->nDoclist = pList->nData + 1;
115704         pReader->aNode = pReader->aDoclist = pList->aData;
115705         pReader->ppNextElem++;
115706         assert( pReader->aNode );
115707       }
115708       return SQLITE_OK;
115709     }
115710
115711     if( !fts3SegReaderIsRootOnly(pReader) ){
115712       sqlite3_free(pReader->aNode);
115713     }
115714     pReader->aNode = 0;
115715
115716     /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf 
115717     ** blocks have already been traversed.  */
115718     assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
115719     if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
115720       return SQLITE_OK;
115721     }
115722
115723     rc = sqlite3Fts3ReadBlock(
115724         p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode
115725     );
115726     if( rc!=SQLITE_OK ) return rc;
115727     pNext = pReader->aNode;
115728   }
115729   
115730   /* Because of the FTS3_NODE_PADDING bytes of padding, the following is 
115731   ** safe (no risk of overread) even if the node data is corrupted.  
115732   */
115733   pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
115734   pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
115735   if( nPrefix<0 || nSuffix<=0 
115736    || &pNext[nSuffix]>&pReader->aNode[pReader->nNode] 
115737   ){
115738     return SQLITE_CORRUPT;
115739   }
115740
115741   if( nPrefix+nSuffix>pReader->nTermAlloc ){
115742     int nNew = (nPrefix+nSuffix)*2;
115743     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
115744     if( !zNew ){
115745       return SQLITE_NOMEM;
115746     }
115747     pReader->zTerm = zNew;
115748     pReader->nTermAlloc = nNew;
115749   }
115750   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
115751   pReader->nTerm = nPrefix+nSuffix;
115752   pNext += nSuffix;
115753   pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
115754   pReader->aDoclist = pNext;
115755   pReader->pOffsetList = 0;
115756
115757   /* Check that the doclist does not appear to extend past the end of the
115758   ** b-tree node. And that the final byte of the doclist is 0x00. If either 
115759   ** of these statements is untrue, then the data structure is corrupt.
115760   */
115761   if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode] 
115762    || pReader->aDoclist[pReader->nDoclist-1]
115763   ){
115764     return SQLITE_CORRUPT;
115765   }
115766   return SQLITE_OK;
115767 }
115768
115769 /*
115770 ** Set the SegReader to point to the first docid in the doclist associated
115771 ** with the current term.
115772 */
115773 static void fts3SegReaderFirstDocid(Fts3SegReader *pReader){
115774   int n;
115775   assert( pReader->aDoclist );
115776   assert( !pReader->pOffsetList );
115777   n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
115778   pReader->pOffsetList = &pReader->aDoclist[n];
115779 }
115780
115781 /*
115782 ** Advance the SegReader to point to the next docid in the doclist
115783 ** associated with the current term.
115784 ** 
115785 ** If arguments ppOffsetList and pnOffsetList are not NULL, then 
115786 ** *ppOffsetList is set to point to the first column-offset list
115787 ** in the doclist entry (i.e. immediately past the docid varint).
115788 ** *pnOffsetList is set to the length of the set of column-offset
115789 ** lists, not including the nul-terminator byte. For example:
115790 */
115791 static void fts3SegReaderNextDocid(
115792   Fts3SegReader *pReader,
115793   char **ppOffsetList,
115794   int *pnOffsetList
115795 ){
115796   char *p = pReader->pOffsetList;
115797   char c = 0;
115798
115799   /* Pointer p currently points at the first byte of an offset list. The
115800   ** following two lines advance it to point one byte past the end of
115801   ** the same offset list.
115802   */
115803   while( *p | c ) c = *p++ & 0x80;
115804   p++;
115805
115806   /* If required, populate the output variables with a pointer to and the
115807   ** size of the previous offset-list.
115808   */
115809   if( ppOffsetList ){
115810     *ppOffsetList = pReader->pOffsetList;
115811     *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
115812   }
115813
115814   /* If there are no more entries in the doclist, set pOffsetList to
115815   ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
115816   ** Fts3SegReader.pOffsetList to point to the next offset list before
115817   ** returning.
115818   */
115819   if( p>=&pReader->aDoclist[pReader->nDoclist] ){
115820     pReader->pOffsetList = 0;
115821   }else{
115822     sqlite3_int64 iDelta;
115823     pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
115824     pReader->iDocid += iDelta;
115825   }
115826 }
115827
115828 /*
115829 ** This function is called to estimate the amount of data that will be 
115830 ** loaded from the disk If SegReaderIterate() is called on this seg-reader,
115831 ** in units of average document size.
115832 ** 
115833 ** This can be used as follows: If the caller has a small doclist that 
115834 ** contains references to N documents, and is considering merging it with
115835 ** a large doclist (size X "average documents"), it may opt not to load
115836 ** the large doclist if X>N.
115837 */
115838 SQLITE_PRIVATE int sqlite3Fts3SegReaderCost(
115839   Fts3Cursor *pCsr,               /* FTS3 cursor handle */
115840   Fts3SegReader *pReader,         /* Segment-reader handle */
115841   int *pnCost                     /* IN/OUT: Number of bytes read */
115842 ){
115843   Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
115844   int rc = SQLITE_OK;             /* Return code */
115845   int nCost = 0;                  /* Cost in bytes to return */
115846   int pgsz = p->nPgsz;            /* Database page size */
115847
115848   /* If this seg-reader is reading the pending-terms table, or if all data
115849   ** for the segment is stored on the root page of the b-tree, then the cost
115850   ** is zero. In this case all required data is already in main memory.
115851   */
115852   if( p->bHasStat 
115853    && !fts3SegReaderIsPending(pReader) 
115854    && !fts3SegReaderIsRootOnly(pReader) 
115855   ){
115856     int nBlob = 0;
115857     sqlite3_int64 iBlock;
115858
115859     if( pCsr->nRowAvg==0 ){
115860       /* The average document size, which is required to calculate the cost
115861       ** of each doclist, has not yet been determined. Read the required 
115862       ** data from the %_stat table to calculate it.
115863       **
115864       ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3 
115865       ** varints, where nCol is the number of columns in the FTS3 table.
115866       ** The first varint is the number of documents currently stored in
115867       ** the table. The following nCol varints contain the total amount of
115868       ** data stored in all rows of each column of the table, from left
115869       ** to right.
115870       */
115871       sqlite3_stmt *pStmt;
115872       sqlite3_int64 nDoc = 0;
115873       sqlite3_int64 nByte = 0;
115874       const char *a;
115875       rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
115876       if( rc ) return rc;
115877       a = sqlite3_column_blob(pStmt, 0);
115878       if( a ){
115879         const char *pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
115880         a += sqlite3Fts3GetVarint(a, &nDoc);
115881         while( a<pEnd ){
115882           a += sqlite3Fts3GetVarint(a, &nByte);
115883         }
115884       }
115885       if( nDoc==0 || nByte==0 ){
115886         sqlite3_reset(pStmt);
115887         return SQLITE_CORRUPT;
115888       }
115889
115890       pCsr->nRowAvg = (int)(((nByte / nDoc) + pgsz) / pgsz);
115891       assert( pCsr->nRowAvg>0 ); 
115892       rc = sqlite3_reset(pStmt);
115893       if( rc!=SQLITE_OK ) return rc;
115894     }
115895
115896     /* Assume that a blob flows over onto overflow pages if it is larger
115897     ** than (pgsz-35) bytes in size (the file-format documentation
115898     ** confirms this).
115899     */
115900     for(iBlock=pReader->iStartBlock; iBlock<=pReader->iLeafEndBlock; iBlock++){
115901       rc = sqlite3Fts3ReadBlock(p, iBlock, 0, &nBlob);
115902       if( rc!=SQLITE_OK ) break;
115903       if( (nBlob+35)>pgsz ){
115904         int nOvfl = (nBlob + 34)/pgsz;
115905         nCost += ((nOvfl + pCsr->nRowAvg - 1)/pCsr->nRowAvg);
115906       }
115907     }
115908   }
115909
115910   *pnCost += nCost;
115911   return rc;
115912 }
115913
115914 /*
115915 ** Free all allocations associated with the iterator passed as the 
115916 ** second argument.
115917 */
115918 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
115919   if( pReader && !fts3SegReaderIsPending(pReader) ){
115920     sqlite3_free(pReader->zTerm);
115921     if( !fts3SegReaderIsRootOnly(pReader) ){
115922       sqlite3_free(pReader->aNode);
115923     }
115924   }
115925   sqlite3_free(pReader);
115926 }
115927
115928 /*
115929 ** Allocate a new SegReader object.
115930 */
115931 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
115932   int iAge,                       /* Segment "age". */
115933   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
115934   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
115935   sqlite3_int64 iEndBlock,        /* Final block of segment */
115936   const char *zRoot,              /* Buffer containing root node */
115937   int nRoot,                      /* Size of buffer containing root node */
115938   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
115939 ){
115940   int rc = SQLITE_OK;             /* Return code */
115941   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
115942   int nExtra = 0;                 /* Bytes to allocate segment root node */
115943
115944   assert( iStartLeaf<=iEndLeaf );
115945   if( iStartLeaf==0 ){
115946     nExtra = nRoot + FTS3_NODE_PADDING;
115947   }
115948
115949   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
115950   if( !pReader ){
115951     return SQLITE_NOMEM;
115952   }
115953   memset(pReader, 0, sizeof(Fts3SegReader));
115954   pReader->iIdx = iAge;
115955   pReader->iStartBlock = iStartLeaf;
115956   pReader->iLeafEndBlock = iEndLeaf;
115957   pReader->iEndBlock = iEndBlock;
115958
115959   if( nExtra ){
115960     /* The entire segment is stored in the root node. */
115961     pReader->aNode = (char *)&pReader[1];
115962     pReader->nNode = nRoot;
115963     memcpy(pReader->aNode, zRoot, nRoot);
115964     memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
115965   }else{
115966     pReader->iCurrentBlock = iStartLeaf-1;
115967   }
115968
115969   if( rc==SQLITE_OK ){
115970     *ppReader = pReader;
115971   }else{
115972     sqlite3Fts3SegReaderFree(pReader);
115973   }
115974   return rc;
115975 }
115976
115977 /*
115978 ** This is a comparison function used as a qsort() callback when sorting
115979 ** an array of pending terms by term. This occurs as part of flushing
115980 ** the contents of the pending-terms hash table to the database.
115981 */
115982 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
115983   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
115984   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
115985   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
115986   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
115987
115988   int n = (n1<n2 ? n1 : n2);
115989   int c = memcmp(z1, z2, n);
115990   if( c==0 ){
115991     c = n1 - n2;
115992   }
115993   return c;
115994 }
115995
115996 /*
115997 ** This function is used to allocate an Fts3SegReader that iterates through
115998 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
115999 */
116000 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
116001   Fts3Table *p,                   /* Virtual table handle */
116002   const char *zTerm,              /* Term to search for */
116003   int nTerm,                      /* Size of buffer zTerm */
116004   int isPrefix,                   /* True for a term-prefix query */
116005   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
116006 ){
116007   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
116008   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
116009   int nElem = 0;                  /* Size of array at aElem */
116010   int rc = SQLITE_OK;             /* Return Code */
116011
116012   if( isPrefix ){
116013     int nAlloc = 0;               /* Size of allocated array at aElem */
116014     Fts3HashElem *pE = 0;         /* Iterator variable */
116015
116016     for(pE=fts3HashFirst(&p->pendingTerms); pE; pE=fts3HashNext(pE)){
116017       char *zKey = (char *)fts3HashKey(pE);
116018       int nKey = fts3HashKeysize(pE);
116019       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
116020         if( nElem==nAlloc ){
116021           Fts3HashElem **aElem2;
116022           nAlloc += 16;
116023           aElem2 = (Fts3HashElem **)sqlite3_realloc(
116024               aElem, nAlloc*sizeof(Fts3HashElem *)
116025           );
116026           if( !aElem2 ){
116027             rc = SQLITE_NOMEM;
116028             nElem = 0;
116029             break;
116030           }
116031           aElem = aElem2;
116032         }
116033         aElem[nElem++] = pE;
116034       }
116035     }
116036
116037     /* If more than one term matches the prefix, sort the Fts3HashElem
116038     ** objects in term order using qsort(). This uses the same comparison
116039     ** callback as is used when flushing terms to disk.
116040     */
116041     if( nElem>1 ){
116042       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
116043     }
116044
116045   }else{
116046     Fts3HashElem *pE = fts3HashFindElem(&p->pendingTerms, zTerm, nTerm);
116047     if( pE ){
116048       aElem = &pE;
116049       nElem = 1;
116050     }
116051   }
116052
116053   if( nElem>0 ){
116054     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
116055     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
116056     if( !pReader ){
116057       rc = SQLITE_NOMEM;
116058     }else{
116059       memset(pReader, 0, nByte);
116060       pReader->iIdx = 0x7FFFFFFF;
116061       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
116062       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
116063     }
116064   }
116065
116066   if( isPrefix ){
116067     sqlite3_free(aElem);
116068   }
116069   *ppReader = pReader;
116070   return rc;
116071 }
116072
116073
116074 /*
116075 ** The second argument to this function is expected to be a statement of
116076 ** the form:
116077 **
116078 **   SELECT 
116079 **     idx,                  -- col 0
116080 **     start_block,          -- col 1
116081 **     leaves_end_block,     -- col 2
116082 **     end_block,            -- col 3
116083 **     root                  -- col 4
116084 **   FROM %_segdir ...
116085 **
116086 ** This function allocates and initializes a Fts3SegReader structure to
116087 ** iterate through the terms stored in the segment identified by the
116088 ** current row that pStmt is pointing to. 
116089 **
116090 ** If successful, the Fts3SegReader is left pointing to the first term
116091 ** in the segment and SQLITE_OK is returned. Otherwise, an SQLite error
116092 ** code is returned.
116093 */
116094 static int fts3SegReaderNew(
116095   sqlite3_stmt *pStmt,            /* See above */
116096   int iAge,                       /* Segment "age". */
116097   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
116098 ){
116099   return sqlite3Fts3SegReaderNew(iAge, 
116100       sqlite3_column_int64(pStmt, 1),
116101       sqlite3_column_int64(pStmt, 2),
116102       sqlite3_column_int64(pStmt, 3),
116103       sqlite3_column_blob(pStmt, 4),
116104       sqlite3_column_bytes(pStmt, 4),
116105       ppReader
116106   );
116107 }
116108
116109 /*
116110 ** Compare the entries pointed to by two Fts3SegReader structures. 
116111 ** Comparison is as follows:
116112 **
116113 **   1) EOF is greater than not EOF.
116114 **
116115 **   2) The current terms (if any) are compared using memcmp(). If one
116116 **      term is a prefix of another, the longer term is considered the
116117 **      larger.
116118 **
116119 **   3) By segment age. An older segment is considered larger.
116120 */
116121 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
116122   int rc;
116123   if( pLhs->aNode && pRhs->aNode ){
116124     int rc2 = pLhs->nTerm - pRhs->nTerm;
116125     if( rc2<0 ){
116126       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
116127     }else{
116128       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
116129     }
116130     if( rc==0 ){
116131       rc = rc2;
116132     }
116133   }else{
116134     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
116135   }
116136   if( rc==0 ){
116137     rc = pRhs->iIdx - pLhs->iIdx;
116138   }
116139   assert( rc!=0 );
116140   return rc;
116141 }
116142
116143 /*
116144 ** A different comparison function for SegReader structures. In this
116145 ** version, it is assumed that each SegReader points to an entry in
116146 ** a doclist for identical terms. Comparison is made as follows:
116147 **
116148 **   1) EOF (end of doclist in this case) is greater than not EOF.
116149 **
116150 **   2) By current docid.
116151 **
116152 **   3) By segment age. An older segment is considered larger.
116153 */
116154 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
116155   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
116156   if( rc==0 ){
116157     if( pLhs->iDocid==pRhs->iDocid ){
116158       rc = pRhs->iIdx - pLhs->iIdx;
116159     }else{
116160       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
116161     }
116162   }
116163   assert( pLhs->aNode && pRhs->aNode );
116164   return rc;
116165 }
116166
116167 /*
116168 ** Compare the term that the Fts3SegReader object passed as the first argument
116169 ** points to with the term specified by arguments zTerm and nTerm. 
116170 **
116171 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
116172 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
116173 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
116174 */
116175 static int fts3SegReaderTermCmp(
116176   Fts3SegReader *pSeg,            /* Segment reader object */
116177   const char *zTerm,              /* Term to compare to */
116178   int nTerm                       /* Size of term zTerm in bytes */
116179 ){
116180   int res = 0;
116181   if( pSeg->aNode ){
116182     if( pSeg->nTerm>nTerm ){
116183       res = memcmp(pSeg->zTerm, zTerm, nTerm);
116184     }else{
116185       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
116186     }
116187     if( res==0 ){
116188       res = pSeg->nTerm-nTerm;
116189     }
116190   }
116191   return res;
116192 }
116193
116194 /*
116195 ** Argument apSegment is an array of nSegment elements. It is known that
116196 ** the final (nSegment-nSuspect) members are already in sorted order
116197 ** (according to the comparison function provided). This function shuffles
116198 ** the array around until all entries are in sorted order.
116199 */
116200 static void fts3SegReaderSort(
116201   Fts3SegReader **apSegment,                     /* Array to sort entries of */
116202   int nSegment,                                  /* Size of apSegment array */
116203   int nSuspect,                                  /* Unsorted entry count */
116204   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
116205 ){
116206   int i;                          /* Iterator variable */
116207
116208   assert( nSuspect<=nSegment );
116209
116210   if( nSuspect==nSegment ) nSuspect--;
116211   for(i=nSuspect-1; i>=0; i--){
116212     int j;
116213     for(j=i; j<(nSegment-1); j++){
116214       Fts3SegReader *pTmp;
116215       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
116216       pTmp = apSegment[j+1];
116217       apSegment[j+1] = apSegment[j];
116218       apSegment[j] = pTmp;
116219     }
116220   }
116221
116222 #ifndef NDEBUG
116223   /* Check that the list really is sorted now. */
116224   for(i=0; i<(nSuspect-1); i++){
116225     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
116226   }
116227 #endif
116228 }
116229
116230 /* 
116231 ** Insert a record into the %_segments table.
116232 */
116233 static int fts3WriteSegment(
116234   Fts3Table *p,                   /* Virtual table handle */
116235   sqlite3_int64 iBlock,           /* Block id for new block */
116236   char *z,                        /* Pointer to buffer containing block data */
116237   int n                           /* Size of buffer z in bytes */
116238 ){
116239   sqlite3_stmt *pStmt;
116240   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
116241   if( rc==SQLITE_OK ){
116242     sqlite3_bind_int64(pStmt, 1, iBlock);
116243     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
116244     sqlite3_step(pStmt);
116245     rc = sqlite3_reset(pStmt);
116246   }
116247   return rc;
116248 }
116249
116250 /* 
116251 ** Insert a record into the %_segdir table.
116252 */
116253 static int fts3WriteSegdir(
116254   Fts3Table *p,                   /* Virtual table handle */
116255   int iLevel,                     /* Value for "level" field */
116256   int iIdx,                       /* Value for "idx" field */
116257   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
116258   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
116259   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
116260   char *zRoot,                    /* Blob value for "root" field */
116261   int nRoot                       /* Number of bytes in buffer zRoot */
116262 ){
116263   sqlite3_stmt *pStmt;
116264   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
116265   if( rc==SQLITE_OK ){
116266     sqlite3_bind_int(pStmt, 1, iLevel);
116267     sqlite3_bind_int(pStmt, 2, iIdx);
116268     sqlite3_bind_int64(pStmt, 3, iStartBlock);
116269     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
116270     sqlite3_bind_int64(pStmt, 5, iEndBlock);
116271     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
116272     sqlite3_step(pStmt);
116273     rc = sqlite3_reset(pStmt);
116274   }
116275   return rc;
116276 }
116277
116278 /*
116279 ** Return the size of the common prefix (if any) shared by zPrev and
116280 ** zNext, in bytes. For example, 
116281 **
116282 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
116283 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
116284 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
116285 */
116286 static int fts3PrefixCompress(
116287   const char *zPrev,              /* Buffer containing previous term */
116288   int nPrev,                      /* Size of buffer zPrev in bytes */
116289   const char *zNext,              /* Buffer containing next term */
116290   int nNext                       /* Size of buffer zNext in bytes */
116291 ){
116292   int n;
116293   UNUSED_PARAMETER(nNext);
116294   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
116295   return n;
116296 }
116297
116298 /*
116299 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
116300 ** (according to memcmp) than the previous term.
116301 */
116302 static int fts3NodeAddTerm(
116303   Fts3Table *p,                   /* Virtual table handle */
116304   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */ 
116305   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
116306   const char *zTerm,              /* Pointer to buffer containing term */
116307   int nTerm                       /* Size of term in bytes */
116308 ){
116309   SegmentNode *pTree = *ppTree;
116310   int rc;
116311   SegmentNode *pNew;
116312
116313   /* First try to append the term to the current node. Return early if 
116314   ** this is possible.
116315   */
116316   if( pTree ){
116317     int nData = pTree->nData;     /* Current size of node in bytes */
116318     int nReq = nData;             /* Required space after adding zTerm */
116319     int nPrefix;                  /* Number of bytes of prefix compression */
116320     int nSuffix;                  /* Suffix length */
116321
116322     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
116323     nSuffix = nTerm-nPrefix;
116324
116325     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
116326     if( nReq<=p->nNodeSize || !pTree->zTerm ){
116327
116328       if( nReq>p->nNodeSize ){
116329         /* An unusual case: this is the first term to be added to the node
116330         ** and the static node buffer (p->nNodeSize bytes) is not large
116331         ** enough. Use a separately malloced buffer instead This wastes
116332         ** p->nNodeSize bytes, but since this scenario only comes about when
116333         ** the database contain two terms that share a prefix of almost 2KB, 
116334         ** this is not expected to be a serious problem. 
116335         */
116336         assert( pTree->aData==(char *)&pTree[1] );
116337         pTree->aData = (char *)sqlite3_malloc(nReq);
116338         if( !pTree->aData ){
116339           return SQLITE_NOMEM;
116340         }
116341       }
116342
116343       if( pTree->zTerm ){
116344         /* There is no prefix-length field for first term in a node */
116345         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
116346       }
116347
116348       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
116349       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
116350       pTree->nData = nData + nSuffix;
116351       pTree->nEntry++;
116352
116353       if( isCopyTerm ){
116354         if( pTree->nMalloc<nTerm ){
116355           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
116356           if( !zNew ){
116357             return SQLITE_NOMEM;
116358           }
116359           pTree->nMalloc = nTerm*2;
116360           pTree->zMalloc = zNew;
116361         }
116362         pTree->zTerm = pTree->zMalloc;
116363         memcpy(pTree->zTerm, zTerm, nTerm);
116364         pTree->nTerm = nTerm;
116365       }else{
116366         pTree->zTerm = (char *)zTerm;
116367         pTree->nTerm = nTerm;
116368       }
116369       return SQLITE_OK;
116370     }
116371   }
116372
116373   /* If control flows to here, it was not possible to append zTerm to the
116374   ** current node. Create a new node (a right-sibling of the current node).
116375   ** If this is the first node in the tree, the term is added to it.
116376   **
116377   ** Otherwise, the term is not added to the new node, it is left empty for
116378   ** now. Instead, the term is inserted into the parent of pTree. If pTree 
116379   ** has no parent, one is created here.
116380   */
116381   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
116382   if( !pNew ){
116383     return SQLITE_NOMEM;
116384   }
116385   memset(pNew, 0, sizeof(SegmentNode));
116386   pNew->nData = 1 + FTS3_VARINT_MAX;
116387   pNew->aData = (char *)&pNew[1];
116388
116389   if( pTree ){
116390     SegmentNode *pParent = pTree->pParent;
116391     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
116392     if( pTree->pParent==0 ){
116393       pTree->pParent = pParent;
116394     }
116395     pTree->pRight = pNew;
116396     pNew->pLeftmost = pTree->pLeftmost;
116397     pNew->pParent = pParent;
116398     pNew->zMalloc = pTree->zMalloc;
116399     pNew->nMalloc = pTree->nMalloc;
116400     pTree->zMalloc = 0;
116401   }else{
116402     pNew->pLeftmost = pNew;
116403     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); 
116404   }
116405
116406   *ppTree = pNew;
116407   return rc;
116408 }
116409
116410 /*
116411 ** Helper function for fts3NodeWrite().
116412 */
116413 static int fts3TreeFinishNode(
116414   SegmentNode *pTree, 
116415   int iHeight, 
116416   sqlite3_int64 iLeftChild
116417 ){
116418   int nStart;
116419   assert( iHeight>=1 && iHeight<128 );
116420   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
116421   pTree->aData[nStart] = (char)iHeight;
116422   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
116423   return nStart;
116424 }
116425
116426 /*
116427 ** Write the buffer for the segment node pTree and all of its peers to the
116428 ** database. Then call this function recursively to write the parent of 
116429 ** pTree and its peers to the database. 
116430 **
116431 ** Except, if pTree is a root node, do not write it to the database. Instead,
116432 ** set output variables *paRoot and *pnRoot to contain the root node.
116433 **
116434 ** If successful, SQLITE_OK is returned and output variable *piLast is
116435 ** set to the largest blockid written to the database (or zero if no
116436 ** blocks were written to the db). Otherwise, an SQLite error code is 
116437 ** returned.
116438 */
116439 static int fts3NodeWrite(
116440   Fts3Table *p,                   /* Virtual table handle */
116441   SegmentNode *pTree,             /* SegmentNode handle */
116442   int iHeight,                    /* Height of this node in tree */
116443   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
116444   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
116445   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
116446   char **paRoot,                  /* OUT: Data for root node */
116447   int *pnRoot                     /* OUT: Size of root node in bytes */
116448 ){
116449   int rc = SQLITE_OK;
116450
116451   if( !pTree->pParent ){
116452     /* Root node of the tree. */
116453     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
116454     *piLast = iFree-1;
116455     *pnRoot = pTree->nData - nStart;
116456     *paRoot = &pTree->aData[nStart];
116457   }else{
116458     SegmentNode *pIter;
116459     sqlite3_int64 iNextFree = iFree;
116460     sqlite3_int64 iNextLeaf = iLeaf;
116461     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
116462       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
116463       int nWrite = pIter->nData - nStart;
116464   
116465       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
116466       iNextFree++;
116467       iNextLeaf += (pIter->nEntry+1);
116468     }
116469     if( rc==SQLITE_OK ){
116470       assert( iNextLeaf==iFree );
116471       rc = fts3NodeWrite(
116472           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
116473       );
116474     }
116475   }
116476
116477   return rc;
116478 }
116479
116480 /*
116481 ** Free all memory allocations associated with the tree pTree.
116482 */
116483 static void fts3NodeFree(SegmentNode *pTree){
116484   if( pTree ){
116485     SegmentNode *p = pTree->pLeftmost;
116486     fts3NodeFree(p->pParent);
116487     while( p ){
116488       SegmentNode *pRight = p->pRight;
116489       if( p->aData!=(char *)&p[1] ){
116490         sqlite3_free(p->aData);
116491       }
116492       assert( pRight==0 || p->zMalloc==0 );
116493       sqlite3_free(p->zMalloc);
116494       sqlite3_free(p);
116495       p = pRight;
116496     }
116497   }
116498 }
116499
116500 /*
116501 ** Add a term to the segment being constructed by the SegmentWriter object
116502 ** *ppWriter. When adding the first term to a segment, *ppWriter should
116503 ** be passed NULL. This function will allocate a new SegmentWriter object
116504 ** and return it via the input/output variable *ppWriter in this case.
116505 **
116506 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
116507 */
116508 static int fts3SegWriterAdd(
116509   Fts3Table *p,                   /* Virtual table handle */
116510   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */ 
116511   int isCopyTerm,                 /* True if buffer zTerm must be copied */
116512   const char *zTerm,              /* Pointer to buffer containing term */
116513   int nTerm,                      /* Size of term in bytes */
116514   const char *aDoclist,           /* Pointer to buffer containing doclist */
116515   int nDoclist                    /* Size of doclist in bytes */
116516 ){
116517   int nPrefix;                    /* Size of term prefix in bytes */
116518   int nSuffix;                    /* Size of term suffix in bytes */
116519   int nReq;                       /* Number of bytes required on leaf page */
116520   int nData;
116521   SegmentWriter *pWriter = *ppWriter;
116522
116523   if( !pWriter ){
116524     int rc;
116525     sqlite3_stmt *pStmt;
116526
116527     /* Allocate the SegmentWriter structure */
116528     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
116529     if( !pWriter ) return SQLITE_NOMEM;
116530     memset(pWriter, 0, sizeof(SegmentWriter));
116531     *ppWriter = pWriter;
116532
116533     /* Allocate a buffer in which to accumulate data */
116534     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
116535     if( !pWriter->aData ) return SQLITE_NOMEM;
116536     pWriter->nSize = p->nNodeSize;
116537
116538     /* Find the next free blockid in the %_segments table */
116539     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
116540     if( rc!=SQLITE_OK ) return rc;
116541     if( SQLITE_ROW==sqlite3_step(pStmt) ){
116542       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
116543       pWriter->iFirst = pWriter->iFree;
116544     }
116545     rc = sqlite3_reset(pStmt);
116546     if( rc!=SQLITE_OK ) return rc;
116547   }
116548   nData = pWriter->nData;
116549
116550   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
116551   nSuffix = nTerm-nPrefix;
116552
116553   /* Figure out how many bytes are required by this new entry */
116554   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
116555     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
116556     nSuffix +                               /* Term suffix */
116557     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
116558     nDoclist;                               /* Doclist data */
116559
116560   if( nData>0 && nData+nReq>p->nNodeSize ){
116561     int rc;
116562
116563     /* The current leaf node is full. Write it out to the database. */
116564     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
116565     if( rc!=SQLITE_OK ) return rc;
116566
116567     /* Add the current term to the interior node tree. The term added to
116568     ** the interior tree must:
116569     **
116570     **   a) be greater than the largest term on the leaf node just written
116571     **      to the database (still available in pWriter->zTerm), and
116572     **
116573     **   b) be less than or equal to the term about to be added to the new
116574     **      leaf node (zTerm/nTerm).
116575     **
116576     ** In other words, it must be the prefix of zTerm 1 byte longer than
116577     ** the common prefix (if any) of zTerm and pWriter->zTerm.
116578     */
116579     assert( nPrefix<nTerm );
116580     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
116581     if( rc!=SQLITE_OK ) return rc;
116582
116583     nData = 0;
116584     pWriter->nTerm = 0;
116585
116586     nPrefix = 0;
116587     nSuffix = nTerm;
116588     nReq = 1 +                              /* varint containing prefix size */
116589       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
116590       nTerm +                               /* Term suffix */
116591       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
116592       nDoclist;                             /* Doclist data */
116593   }
116594
116595   /* If the buffer currently allocated is too small for this entry, realloc
116596   ** the buffer to make it large enough.
116597   */
116598   if( nReq>pWriter->nSize ){
116599     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
116600     if( !aNew ) return SQLITE_NOMEM;
116601     pWriter->aData = aNew;
116602     pWriter->nSize = nReq;
116603   }
116604   assert( nData+nReq<=pWriter->nSize );
116605
116606   /* Append the prefix-compressed term and doclist to the buffer. */
116607   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
116608   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
116609   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
116610   nData += nSuffix;
116611   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
116612   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
116613   pWriter->nData = nData + nDoclist;
116614
116615   /* Save the current term so that it can be used to prefix-compress the next.
116616   ** If the isCopyTerm parameter is true, then the buffer pointed to by
116617   ** zTerm is transient, so take a copy of the term data. Otherwise, just
116618   ** store a copy of the pointer.
116619   */
116620   if( isCopyTerm ){
116621     if( nTerm>pWriter->nMalloc ){
116622       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
116623       if( !zNew ){
116624         return SQLITE_NOMEM;
116625       }
116626       pWriter->nMalloc = nTerm*2;
116627       pWriter->zMalloc = zNew;
116628       pWriter->zTerm = zNew;
116629     }
116630     assert( pWriter->zTerm==pWriter->zMalloc );
116631     memcpy(pWriter->zTerm, zTerm, nTerm);
116632   }else{
116633     pWriter->zTerm = (char *)zTerm;
116634   }
116635   pWriter->nTerm = nTerm;
116636
116637   return SQLITE_OK;
116638 }
116639
116640 /*
116641 ** Flush all data associated with the SegmentWriter object pWriter to the
116642 ** database. This function must be called after all terms have been added
116643 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
116644 ** returned. Otherwise, an SQLite error code.
116645 */
116646 static int fts3SegWriterFlush(
116647   Fts3Table *p,                   /* Virtual table handle */
116648   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
116649   int iLevel,                     /* Value for 'level' column of %_segdir */
116650   int iIdx                        /* Value for 'idx' column of %_segdir */
116651 ){
116652   int rc;                         /* Return code */
116653   if( pWriter->pTree ){
116654     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
116655     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
116656     char *zRoot = NULL;           /* Pointer to buffer containing root node */
116657     int nRoot = 0;                /* Size of buffer zRoot */
116658
116659     iLastLeaf = pWriter->iFree;
116660     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
116661     if( rc==SQLITE_OK ){
116662       rc = fts3NodeWrite(p, pWriter->pTree, 1,
116663           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
116664     }
116665     if( rc==SQLITE_OK ){
116666       rc = fts3WriteSegdir(
116667           p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
116668     }
116669   }else{
116670     /* The entire tree fits on the root node. Write it to the segdir table. */
116671     rc = fts3WriteSegdir(
116672         p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
116673   }
116674   return rc;
116675 }
116676
116677 /*
116678 ** Release all memory held by the SegmentWriter object passed as the 
116679 ** first argument.
116680 */
116681 static void fts3SegWriterFree(SegmentWriter *pWriter){
116682   if( pWriter ){
116683     sqlite3_free(pWriter->aData);
116684     sqlite3_free(pWriter->zMalloc);
116685     fts3NodeFree(pWriter->pTree);
116686     sqlite3_free(pWriter);
116687   }
116688 }
116689
116690 /*
116691 ** The first value in the apVal[] array is assumed to contain an integer.
116692 ** This function tests if there exist any documents with docid values that
116693 ** are different from that integer. i.e. if deleting the document with docid
116694 ** apVal[0] would mean the FTS3 table were empty.
116695 **
116696 ** If successful, *pisEmpty is set to true if the table is empty except for
116697 ** document apVal[0], or false otherwise, and SQLITE_OK is returned. If an
116698 ** error occurs, an SQLite error code is returned.
116699 */
116700 static int fts3IsEmpty(Fts3Table *p, sqlite3_value **apVal, int *pisEmpty){
116701   sqlite3_stmt *pStmt;
116702   int rc;
116703   rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, apVal);
116704   if( rc==SQLITE_OK ){
116705     if( SQLITE_ROW==sqlite3_step(pStmt) ){
116706       *pisEmpty = sqlite3_column_int(pStmt, 0);
116707     }
116708     rc = sqlite3_reset(pStmt);
116709   }
116710   return rc;
116711 }
116712
116713 /*
116714 ** Set *pnSegment to the number of segments of level iLevel in the database.
116715 **
116716 ** Return SQLITE_OK if successful, or an SQLite error code if not.
116717 */
116718 static int fts3SegmentCount(Fts3Table *p, int iLevel, int *pnSegment){
116719   sqlite3_stmt *pStmt;
116720   int rc;
116721
116722   assert( iLevel>=0 );
116723   rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_COUNT, &pStmt, 0);
116724   if( rc!=SQLITE_OK ) return rc;
116725   sqlite3_bind_int(pStmt, 1, iLevel);
116726   if( SQLITE_ROW==sqlite3_step(pStmt) ){
116727     *pnSegment = sqlite3_column_int(pStmt, 0);
116728   }
116729   return sqlite3_reset(pStmt);
116730 }
116731
116732 /*
116733 ** Set *pnSegment to the total number of segments in the database. Set
116734 ** *pnMax to the largest segment level in the database (segment levels
116735 ** are stored in the 'level' column of the %_segdir table).
116736 **
116737 ** Return SQLITE_OK if successful, or an SQLite error code if not.
116738 */
116739 static int fts3SegmentCountMax(Fts3Table *p, int *pnSegment, int *pnMax){
116740   sqlite3_stmt *pStmt;
116741   int rc;
116742
116743   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_COUNT_MAX, &pStmt, 0);
116744   if( rc!=SQLITE_OK ) return rc;
116745   if( SQLITE_ROW==sqlite3_step(pStmt) ){
116746     *pnSegment = sqlite3_column_int(pStmt, 0);
116747     *pnMax = sqlite3_column_int(pStmt, 1);
116748   }
116749   return sqlite3_reset(pStmt);
116750 }
116751
116752 /*
116753 ** This function is used after merging multiple segments into a single large
116754 ** segment to delete the old, now redundant, segment b-trees. Specifically,
116755 ** it:
116756 ** 
116757 **   1) Deletes all %_segments entries for the segments associated with 
116758 **      each of the SegReader objects in the array passed as the third 
116759 **      argument, and
116760 **
116761 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
116762 **      entries regardless of level if (iLevel<0).
116763 **
116764 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
116765 */
116766 static int fts3DeleteSegdir(
116767   Fts3Table *p,                   /* Virtual table handle */
116768   int iLevel,                     /* Level of %_segdir entries to delete */
116769   Fts3SegReader **apSegment,      /* Array of SegReader objects */
116770   int nReader                     /* Size of array apSegment */
116771 ){
116772   int rc;                         /* Return Code */
116773   int i;                          /* Iterator variable */
116774   sqlite3_stmt *pDelete;          /* SQL statement to delete rows */
116775
116776   rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
116777   for(i=0; rc==SQLITE_OK && i<nReader; i++){
116778     Fts3SegReader *pSegment = apSegment[i];
116779     if( pSegment->iStartBlock ){
116780       sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
116781       sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
116782       sqlite3_step(pDelete);
116783       rc = sqlite3_reset(pDelete);
116784     }
116785   }
116786   if( rc!=SQLITE_OK ){
116787     return rc;
116788   }
116789
116790   if( iLevel>=0 ){
116791     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_BY_LEVEL, &pDelete, 0);
116792     if( rc==SQLITE_OK ){
116793       sqlite3_bind_int(pDelete, 1, iLevel);
116794       sqlite3_step(pDelete);
116795       rc = sqlite3_reset(pDelete);
116796     }
116797   }else{
116798     fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
116799   }
116800
116801   return rc;
116802 }
116803
116804 /*
116805 ** When this function is called, buffer *ppList (size *pnList bytes) contains 
116806 ** a position list that may (or may not) feature multiple columns. This
116807 ** function adjusts the pointer *ppList and the length *pnList so that they
116808 ** identify the subset of the position list that corresponds to column iCol.
116809 **
116810 ** If there are no entries in the input position list for column iCol, then
116811 ** *pnList is set to zero before returning.
116812 */
116813 static void fts3ColumnFilter(
116814   int iCol,                       /* Column to filter on */
116815   char **ppList,                  /* IN/OUT: Pointer to position list */
116816   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
116817 ){
116818   char *pList = *ppList;
116819   int nList = *pnList;
116820   char *pEnd = &pList[nList];
116821   int iCurrent = 0;
116822   char *p = pList;
116823
116824   assert( iCol>=0 );
116825   while( 1 ){
116826     char c = 0;
116827     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
116828   
116829     if( iCol==iCurrent ){
116830       nList = (int)(p - pList);
116831       break;
116832     }
116833
116834     nList -= (int)(p - pList);
116835     pList = p;
116836     if( nList==0 ){
116837       break;
116838     }
116839     p = &pList[1];
116840     p += sqlite3Fts3GetVarint32(p, &iCurrent);
116841   }
116842
116843   *ppList = pList;
116844   *pnList = nList;
116845 }
116846
116847 /*
116848 ** sqlite3Fts3SegReaderIterate() callback used when merging multiple 
116849 ** segments to create a single, larger segment.
116850 */
116851 static int fts3MergeCallback(
116852   Fts3Table *p,                   /* FTS3 Virtual table handle */
116853   void *pContext,                 /* Pointer to SegmentWriter* to write with */
116854   char *zTerm,                    /* Term to write to the db */
116855   int nTerm,                      /* Number of bytes in zTerm */
116856   char *aDoclist,                 /* Doclist associated with zTerm */
116857   int nDoclist                    /* Number of bytes in doclist */
116858 ){
116859   SegmentWriter **ppW = (SegmentWriter **)pContext;
116860   return fts3SegWriterAdd(p, ppW, 1, zTerm, nTerm, aDoclist, nDoclist);
116861 }
116862
116863 /*
116864 ** sqlite3Fts3SegReaderIterate() callback used when flushing the contents
116865 ** of the pending-terms hash table to the database.
116866 */
116867 static int fts3FlushCallback(
116868   Fts3Table *p,                   /* FTS3 Virtual table handle */
116869   void *pContext,                 /* Pointer to SegmentWriter* to write with */
116870   char *zTerm,                    /* Term to write to the db */
116871   int nTerm,                      /* Number of bytes in zTerm */
116872   char *aDoclist,                 /* Doclist associated with zTerm */
116873   int nDoclist                    /* Number of bytes in doclist */
116874 ){
116875   SegmentWriter **ppW = (SegmentWriter **)pContext;
116876   return fts3SegWriterAdd(p, ppW, 0, zTerm, nTerm, aDoclist, nDoclist);
116877 }
116878
116879 /*
116880 ** This function is used to iterate through a contiguous set of terms 
116881 ** stored in the full-text index. It merges data contained in one or 
116882 ** more segments to support this.
116883 **
116884 ** The second argument is passed an array of pointers to SegReader objects
116885 ** allocated with sqlite3Fts3SegReaderNew(). This function merges the range 
116886 ** of terms selected by each SegReader. If a single term is present in
116887 ** more than one segment, the associated doclists are merged. For each
116888 ** term and (possibly merged) doclist in the merged range, the callback
116889 ** function xFunc is invoked with its arguments set as follows.
116890 **
116891 **   arg 0: Copy of 'p' parameter passed to this function
116892 **   arg 1: Copy of 'pContext' parameter passed to this function
116893 **   arg 2: Pointer to buffer containing term
116894 **   arg 3: Size of arg 2 buffer in bytes
116895 **   arg 4: Pointer to buffer containing doclist
116896 **   arg 5: Size of arg 2 buffer in bytes
116897 **
116898 ** The 4th argument to this function is a pointer to a structure of type
116899 ** Fts3SegFilter, defined in fts3Int.h. The contents of this structure
116900 ** further restrict the range of terms that callbacks are made for and
116901 ** modify the behaviour of this function. See comments above structure
116902 ** definition for details.
116903 */
116904 SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
116905   Fts3Table *p,                   /* Virtual table handle */
116906   Fts3SegReader **apSegment,      /* Array of Fts3SegReader objects */
116907   int nSegment,                   /* Size of apSegment array */
116908   Fts3SegFilter *pFilter,         /* Restrictions on range of iteration */
116909   int (*xFunc)(Fts3Table *, void *, char *, int, char *, int),  /* Callback */
116910   void *pContext                  /* Callback context (2nd argument) */
116911 ){
116912   int i;                          /* Iterator variable */
116913   char *aBuffer = 0;              /* Buffer to merge doclists in */
116914   int nAlloc = 0;                 /* Allocated size of aBuffer buffer */
116915   int rc = SQLITE_OK;             /* Return code */
116916
116917   int isIgnoreEmpty =  (pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
116918   int isRequirePos =   (pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
116919   int isColFilter =    (pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
116920   int isPrefix =       (pFilter->flags & FTS3_SEGMENT_PREFIX);
116921
116922   /* If there are zero segments, this function is a no-op. This scenario
116923   ** comes about only when reading from an empty database.
116924   */
116925   if( nSegment==0 ) goto finished;
116926
116927   /* If the Fts3SegFilter defines a specific term (or term prefix) to search 
116928   ** for, then advance each segment iterator until it points to a term of
116929   ** equal or greater value than the specified term. This prevents many
116930   ** unnecessary merge/sort operations for the case where single segment
116931   ** b-tree leaf nodes contain more than one term.
116932   */
116933   for(i=0; i<nSegment; i++){
116934     int nTerm = pFilter->nTerm;
116935     const char *zTerm = pFilter->zTerm;
116936     Fts3SegReader *pSeg = apSegment[i];
116937     do {
116938       rc = fts3SegReaderNext(p, pSeg);
116939       if( rc!=SQLITE_OK ) goto finished;
116940     }while( zTerm && fts3SegReaderTermCmp(pSeg, zTerm, nTerm)<0 );
116941   }
116942
116943   fts3SegReaderSort(apSegment, nSegment, nSegment, fts3SegReaderCmp);
116944   while( apSegment[0]->aNode ){
116945     int nTerm = apSegment[0]->nTerm;
116946     char *zTerm = apSegment[0]->zTerm;
116947     int nMerge = 1;
116948
116949     /* If this is a prefix-search, and if the term that apSegment[0] points
116950     ** to does not share a suffix with pFilter->zTerm/nTerm, then all 
116951     ** required callbacks have been made. In this case exit early.
116952     **
116953     ** Similarly, if this is a search for an exact match, and the first term
116954     ** of segment apSegment[0] is not a match, exit early.
116955     */
116956     if( pFilter->zTerm ){
116957       if( nTerm<pFilter->nTerm 
116958        || (!isPrefix && nTerm>pFilter->nTerm)
116959        || memcmp(zTerm, pFilter->zTerm, pFilter->nTerm) 
116960     ){
116961         goto finished;
116962       }
116963     }
116964
116965     while( nMerge<nSegment 
116966         && apSegment[nMerge]->aNode
116967         && apSegment[nMerge]->nTerm==nTerm 
116968         && 0==memcmp(zTerm, apSegment[nMerge]->zTerm, nTerm)
116969     ){
116970       nMerge++;
116971     }
116972
116973     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
116974     if( nMerge==1 && !isIgnoreEmpty ){
116975       Fts3SegReader *p0 = apSegment[0];
116976       rc = xFunc(p, pContext, zTerm, nTerm, p0->aDoclist, p0->nDoclist);
116977       if( rc!=SQLITE_OK ) goto finished;
116978     }else{
116979       int nDoclist = 0;           /* Size of doclist */
116980       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
116981
116982       /* The current term of the first nMerge entries in the array
116983       ** of Fts3SegReader objects is the same. The doclists must be merged
116984       ** and a single term added to the new segment.
116985       */
116986       for(i=0; i<nMerge; i++){
116987         fts3SegReaderFirstDocid(apSegment[i]);
116988       }
116989       fts3SegReaderSort(apSegment, nMerge, nMerge, fts3SegReaderDoclistCmp);
116990       while( apSegment[0]->pOffsetList ){
116991         int j;                    /* Number of segments that share a docid */
116992         char *pList;
116993         int nList;
116994         int nByte;
116995         sqlite3_int64 iDocid = apSegment[0]->iDocid;
116996         fts3SegReaderNextDocid(apSegment[0], &pList, &nList);
116997         j = 1;
116998         while( j<nMerge
116999             && apSegment[j]->pOffsetList
117000             && apSegment[j]->iDocid==iDocid
117001         ){
117002           fts3SegReaderNextDocid(apSegment[j], 0, 0);
117003           j++;
117004         }
117005
117006         if( isColFilter ){
117007           fts3ColumnFilter(pFilter->iCol, &pList, &nList);
117008         }
117009
117010         if( !isIgnoreEmpty || nList>0 ){
117011           nByte = sqlite3Fts3VarintLen(iDocid-iPrev) + (isRequirePos?nList+1:0);
117012           if( nDoclist+nByte>nAlloc ){
117013             char *aNew;
117014             nAlloc = (nDoclist+nByte)*2;
117015             aNew = sqlite3_realloc(aBuffer, nAlloc);
117016             if( !aNew ){
117017               rc = SQLITE_NOMEM;
117018               goto finished;
117019             }
117020             aBuffer = aNew;
117021           }
117022           nDoclist += sqlite3Fts3PutVarint(&aBuffer[nDoclist], iDocid-iPrev);
117023           iPrev = iDocid;
117024           if( isRequirePos ){
117025             memcpy(&aBuffer[nDoclist], pList, nList);
117026             nDoclist += nList;
117027             aBuffer[nDoclist++] = '\0';
117028           }
117029         }
117030
117031         fts3SegReaderSort(apSegment, nMerge, j, fts3SegReaderDoclistCmp);
117032       }
117033
117034       if( nDoclist>0 ){
117035         rc = xFunc(p, pContext, zTerm, nTerm, aBuffer, nDoclist);
117036         if( rc!=SQLITE_OK ) goto finished;
117037       }
117038     }
117039
117040     /* If there is a term specified to filter on, and this is not a prefix
117041     ** search, return now. The callback that corresponds to the required
117042     ** term (if such a term exists in the index) has already been made.
117043     */
117044     if( pFilter->zTerm && !isPrefix ){
117045       goto finished;
117046     }
117047
117048     for(i=0; i<nMerge; i++){
117049       rc = fts3SegReaderNext(p, apSegment[i]);
117050       if( rc!=SQLITE_OK ) goto finished;
117051     }
117052     fts3SegReaderSort(apSegment, nSegment, nMerge, fts3SegReaderCmp);
117053   }
117054
117055  finished:
117056   sqlite3_free(aBuffer);
117057   return rc;
117058 }
117059
117060 /*
117061 ** Merge all level iLevel segments in the database into a single 
117062 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
117063 ** single segment with a level equal to the numerically largest level 
117064 ** currently present in the database.
117065 **
117066 ** If this function is called with iLevel<0, but there is only one
117067 ** segment in the database, SQLITE_DONE is returned immediately. 
117068 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, 
117069 ** an SQLite error code is returned.
117070 */
117071 static int fts3SegmentMerge(Fts3Table *p, int iLevel){
117072   int i;                          /* Iterator variable */
117073   int rc;                         /* Return code */
117074   int iIdx;                       /* Index of new segment */
117075   int iNewLevel = 0;              /* Level to create new segment at */
117076   sqlite3_stmt *pStmt = 0;
117077   SegmentWriter *pWriter = 0;
117078   int nSegment = 0;               /* Number of segments being merged */
117079   Fts3SegReader **apSegment = 0;  /* Array of Segment iterators */
117080   Fts3SegReader *pPending = 0;    /* Iterator for pending-terms */
117081   Fts3SegFilter filter;           /* Segment term filter condition */
117082
117083   if( iLevel<0 ){
117084     /* This call is to merge all segments in the database to a single
117085     ** segment. The level of the new segment is equal to the the numerically 
117086     ** greatest segment level currently present in the database. The index
117087     ** of the new segment is always 0.
117088     */
117089     iIdx = 0;
117090     rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pPending);
117091     if( rc!=SQLITE_OK ) goto finished;
117092     rc = fts3SegmentCountMax(p, &nSegment, &iNewLevel);
117093     if( rc!=SQLITE_OK ) goto finished;
117094     nSegment += (pPending!=0);
117095     if( nSegment<=1 ){
117096       return SQLITE_DONE;
117097     }
117098   }else{
117099     /* This call is to merge all segments at level iLevel. Find the next
117100     ** available segment index at level iLevel+1. The call to
117101     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to 
117102     ** a single iLevel+2 segment if necessary.
117103     */
117104     iNewLevel = iLevel+1;
117105     rc = fts3AllocateSegdirIdx(p, iNewLevel, &iIdx);
117106     if( rc!=SQLITE_OK ) goto finished;
117107     rc = fts3SegmentCount(p, iLevel, &nSegment);
117108     if( rc!=SQLITE_OK ) goto finished;
117109   }
117110   assert( nSegment>0 );
117111   assert( iNewLevel>=0 );
117112
117113   /* Allocate space for an array of pointers to segment iterators. */
117114   apSegment = (Fts3SegReader**)sqlite3_malloc(sizeof(Fts3SegReader *)*nSegment);
117115   if( !apSegment ){
117116     rc = SQLITE_NOMEM;
117117     goto finished;
117118   }
117119   memset(apSegment, 0, sizeof(Fts3SegReader *)*nSegment);
117120
117121   /* Allocate a Fts3SegReader structure for each segment being merged. A 
117122   ** Fts3SegReader stores the state data required to iterate through all 
117123   ** entries on all leaves of a single segment. 
117124   */
117125   assert( SQL_SELECT_LEVEL+1==SQL_SELECT_ALL_LEVEL);
117126   rc = fts3SqlStmt(p, SQL_SELECT_LEVEL+(iLevel<0), &pStmt, 0);
117127   if( rc!=SQLITE_OK ) goto finished;
117128   sqlite3_bind_int(pStmt, 1, iLevel);
117129   for(i=0; SQLITE_ROW==(sqlite3_step(pStmt)); i++){
117130     rc = fts3SegReaderNew(pStmt, i, &apSegment[i]);
117131     if( rc!=SQLITE_OK ){
117132       goto finished;
117133     }
117134   }
117135   rc = sqlite3_reset(pStmt);
117136   if( pPending ){
117137     apSegment[i] = pPending;
117138     pPending = 0;
117139   }
117140   pStmt = 0;
117141   if( rc!=SQLITE_OK ) goto finished;
117142
117143   memset(&filter, 0, sizeof(Fts3SegFilter));
117144   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
117145   filter.flags |= (iLevel<0 ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
117146   rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment,
117147       &filter, fts3MergeCallback, (void *)&pWriter
117148   );
117149   if( rc!=SQLITE_OK ) goto finished;
117150
117151   rc = fts3DeleteSegdir(p, iLevel, apSegment, nSegment);
117152   if( rc==SQLITE_OK ){
117153     rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
117154   }
117155
117156  finished:
117157   fts3SegWriterFree(pWriter);
117158   if( apSegment ){
117159     for(i=0; i<nSegment; i++){
117160       sqlite3Fts3SegReaderFree(apSegment[i]);
117161     }
117162     sqlite3_free(apSegment);
117163   }
117164   sqlite3Fts3SegReaderFree(pPending);
117165   sqlite3_reset(pStmt);
117166   return rc;
117167 }
117168
117169
117170 /* 
117171 ** Flush the contents of pendingTerms to a level 0 segment.
117172 */
117173 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
117174   int rc;                         /* Return Code */
117175   int idx;                        /* Index of new segment created */
117176   SegmentWriter *pWriter = 0;     /* Used to write the segment */
117177   Fts3SegReader *pReader = 0;     /* Used to iterate through the hash table */
117178
117179   /* Allocate a SegReader object to iterate through the contents of the
117180   ** pending-terms table. If an error occurs, or if there are no terms
117181   ** in the pending-terms table, return immediately.
117182   */
117183   rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pReader);
117184   if( rc!=SQLITE_OK || pReader==0 ){
117185     return rc;
117186   }
117187
117188   /* Determine the next index at level 0. If level 0 is already full, this
117189   ** call may merge all existing level 0 segments into a single level 1
117190   ** segment.
117191   */
117192   rc = fts3AllocateSegdirIdx(p, 0, &idx);
117193
117194   /* If no errors have occured, iterate through the contents of the 
117195   ** pending-terms hash table using the Fts3SegReader iterator. The callback
117196   ** writes each term (along with its doclist) to the database via the
117197   ** SegmentWriter handle pWriter.
117198   */
117199   if( rc==SQLITE_OK ){
117200     void *c = (void *)&pWriter;   /* SegReaderIterate() callback context */
117201     Fts3SegFilter f;              /* SegReaderIterate() parameters */
117202
117203     memset(&f, 0, sizeof(Fts3SegFilter));
117204     f.flags = FTS3_SEGMENT_REQUIRE_POS;
117205     rc = sqlite3Fts3SegReaderIterate(p, &pReader, 1, &f, fts3FlushCallback, c);
117206   }
117207   assert( pWriter || rc!=SQLITE_OK );
117208
117209   /* If no errors have occured, flush the SegmentWriter object to the
117210   ** database. Then delete the SegmentWriter and Fts3SegReader objects
117211   ** allocated by this function.
117212   */
117213   if( rc==SQLITE_OK ){
117214     rc = fts3SegWriterFlush(p, pWriter, 0, idx);
117215   }
117216   fts3SegWriterFree(pWriter);
117217   sqlite3Fts3SegReaderFree(pReader);
117218
117219   if( rc==SQLITE_OK ){
117220     sqlite3Fts3PendingTermsClear(p);
117221   }
117222   return rc;
117223 }
117224
117225 /*
117226 ** Encode N integers as varints into a blob.
117227 */
117228 static void fts3EncodeIntArray(
117229   int N,             /* The number of integers to encode */
117230   u32 *a,            /* The integer values */
117231   char *zBuf,        /* Write the BLOB here */
117232   int *pNBuf         /* Write number of bytes if zBuf[] used here */
117233 ){
117234   int i, j;
117235   for(i=j=0; i<N; i++){
117236     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
117237   }
117238   *pNBuf = j;
117239 }
117240
117241 /*
117242 ** Decode a blob of varints into N integers
117243 */
117244 static void fts3DecodeIntArray(
117245   int N,             /* The number of integers to decode */
117246   u32 *a,            /* Write the integer values */
117247   const char *zBuf,  /* The BLOB containing the varints */
117248   int nBuf           /* size of the BLOB */
117249 ){
117250   int i, j;
117251   UNUSED_PARAMETER(nBuf);
117252   for(i=j=0; i<N; i++){
117253     sqlite3_int64 x;
117254     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
117255     assert(j<=nBuf);
117256     a[i] = (u32)(x & 0xffffffff);
117257   }
117258 }
117259
117260 /*
117261 ** Insert the sizes (in tokens) for each column of the document
117262 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
117263 ** a blob of varints.
117264 */
117265 static void fts3InsertDocsize(
117266   int *pRC,         /* Result code */
117267   Fts3Table *p,     /* Table into which to insert */
117268   u32 *aSz          /* Sizes of each column */
117269 ){
117270   char *pBlob;             /* The BLOB encoding of the document size */
117271   int nBlob;               /* Number of bytes in the BLOB */
117272   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
117273   int rc;                  /* Result code from subfunctions */
117274
117275   if( *pRC ) return;
117276   pBlob = sqlite3_malloc( 10*p->nColumn );
117277   if( pBlob==0 ){
117278     *pRC = SQLITE_NOMEM;
117279     return;
117280   }
117281   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
117282   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
117283   if( rc ){
117284     sqlite3_free(pBlob);
117285     *pRC = rc;
117286     return;
117287   }
117288   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
117289   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
117290   sqlite3_step(pStmt);
117291   *pRC = sqlite3_reset(pStmt);
117292 }
117293
117294 /*
117295 ** Record 0 of the %_stat table contains a blob consisting of N varints,
117296 ** where N is the number of user defined columns in the fts3 table plus
117297 ** two. If nCol is the number of user defined columns, then values of the 
117298 ** varints are set as follows:
117299 **
117300 **   Varint 0:       Total number of rows in the table.
117301 **
117302 **   Varint 1..nCol: For each column, the total number of tokens stored in
117303 **                   the column for all rows of the table.
117304 **
117305 **   Varint 1+nCol:  The total size, in bytes, of all text values in all
117306 **                   columns of all rows of the table.
117307 **
117308 */
117309 static void fts3UpdateDocTotals(
117310   int *pRC,                       /* The result code */
117311   Fts3Table *p,                   /* Table being updated */
117312   u32 *aSzIns,                    /* Size increases */
117313   u32 *aSzDel,                    /* Size decreases */
117314   int nChng                       /* Change in the number of documents */
117315 ){
117316   char *pBlob;             /* Storage for BLOB written into %_stat */
117317   int nBlob;               /* Size of BLOB written into %_stat */
117318   u32 *a;                  /* Array of integers that becomes the BLOB */
117319   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
117320   int i;                   /* Loop counter */
117321   int rc;                  /* Result code from subfunctions */
117322
117323   const int nStat = p->nColumn+2;
117324
117325   if( *pRC ) return;
117326   a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
117327   if( a==0 ){
117328     *pRC = SQLITE_NOMEM;
117329     return;
117330   }
117331   pBlob = (char*)&a[nStat];
117332   rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
117333   if( rc ){
117334     sqlite3_free(a);
117335     *pRC = rc;
117336     return;
117337   }
117338   if( sqlite3_step(pStmt)==SQLITE_ROW ){
117339     fts3DecodeIntArray(nStat, a,
117340          sqlite3_column_blob(pStmt, 0),
117341          sqlite3_column_bytes(pStmt, 0));
117342   }else{
117343     memset(a, 0, sizeof(u32)*(nStat) );
117344   }
117345   sqlite3_reset(pStmt);
117346   if( nChng<0 && a[0]<(u32)(-nChng) ){
117347     a[0] = 0;
117348   }else{
117349     a[0] += nChng;
117350   }
117351   for(i=0; i<p->nColumn+1; i++){
117352     u32 x = a[i+1];
117353     if( x+aSzIns[i] < aSzDel[i] ){
117354       x = 0;
117355     }else{
117356       x = x + aSzIns[i] - aSzDel[i];
117357     }
117358     a[i+1] = x;
117359   }
117360   fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
117361   rc = fts3SqlStmt(p, SQL_REPLACE_DOCTOTAL, &pStmt, 0);
117362   if( rc ){
117363     sqlite3_free(a);
117364     *pRC = rc;
117365     return;
117366   }
117367   sqlite3_bind_blob(pStmt, 1, pBlob, nBlob, SQLITE_STATIC);
117368   sqlite3_step(pStmt);
117369   *pRC = sqlite3_reset(pStmt);
117370   sqlite3_free(a);
117371 }
117372
117373 /*
117374 ** Handle a 'special' INSERT of the form:
117375 **
117376 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
117377 **
117378 ** Argument pVal contains the result of <expr>. Currently the only 
117379 ** meaningful value to insert is the text 'optimize'.
117380 */
117381 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
117382   int rc;                         /* Return Code */
117383   const char *zVal = (const char *)sqlite3_value_text(pVal);
117384   int nVal = sqlite3_value_bytes(pVal);
117385
117386   if( !zVal ){
117387     return SQLITE_NOMEM;
117388   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
117389     rc = fts3SegmentMerge(p, -1);
117390     if( rc==SQLITE_DONE ){
117391       rc = SQLITE_OK;
117392     }else{
117393       sqlite3Fts3PendingTermsClear(p);
117394     }
117395 #ifdef SQLITE_TEST
117396   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
117397     p->nNodeSize = atoi(&zVal[9]);
117398     rc = SQLITE_OK;
117399   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
117400     p->nMaxPendingData = atoi(&zVal[11]);
117401     rc = SQLITE_OK;
117402 #endif
117403   }else{
117404     rc = SQLITE_ERROR;
117405   }
117406
117407   sqlite3Fts3SegmentsClose(p);
117408   return rc;
117409 }
117410
117411 /*
117412 ** Return the deferred doclist associated with deferred token pDeferred.
117413 ** This function assumes that sqlite3Fts3CacheDeferredDoclists() has already
117414 ** been called to allocate and populate the doclist.
117415 */
117416 SQLITE_PRIVATE char *sqlite3Fts3DeferredDoclist(Fts3DeferredToken *pDeferred, int *pnByte){
117417   if( pDeferred->pList ){
117418     *pnByte = pDeferred->pList->nData;
117419     return pDeferred->pList->aData;
117420   }
117421   *pnByte = 0;
117422   return 0;
117423 }
117424
117425 /*
117426 ** Helper fucntion for FreeDeferredDoclists(). This function removes all
117427 ** references to deferred doclists from within the tree of Fts3Expr 
117428 ** structures headed by 
117429 */
117430 static void fts3DeferredDoclistClear(Fts3Expr *pExpr){
117431   if( pExpr ){
117432     fts3DeferredDoclistClear(pExpr->pLeft);
117433     fts3DeferredDoclistClear(pExpr->pRight);
117434     if( pExpr->isLoaded ){
117435       sqlite3_free(pExpr->aDoclist);
117436       pExpr->isLoaded = 0;
117437       pExpr->aDoclist = 0;
117438       pExpr->nDoclist = 0;
117439       pExpr->pCurrent = 0;
117440       pExpr->iCurrent = 0;
117441     }
117442   }
117443 }
117444
117445 /*
117446 ** Delete all cached deferred doclists. Deferred doclists are cached
117447 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
117448 */
117449 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
117450   Fts3DeferredToken *pDef;
117451   for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
117452     sqlite3_free(pDef->pList);
117453     pDef->pList = 0;
117454   }
117455   if( pCsr->pDeferred ){
117456     fts3DeferredDoclistClear(pCsr->pExpr);
117457   }
117458 }
117459
117460 /*
117461 ** Free all entries in the pCsr->pDeffered list. Entries are added to 
117462 ** this list using sqlite3Fts3DeferToken().
117463 */
117464 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
117465   Fts3DeferredToken *pDef;
117466   Fts3DeferredToken *pNext;
117467   for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
117468     pNext = pDef->pNext;
117469     sqlite3_free(pDef->pList);
117470     sqlite3_free(pDef);
117471   }
117472   pCsr->pDeferred = 0;
117473 }
117474
117475 /*
117476 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
117477 ** based on the row that pCsr currently points to.
117478 **
117479 ** A deferred-doclist is like any other doclist with position information
117480 ** included, except that it only contains entries for a single row of the
117481 ** table, not for all rows.
117482 */
117483 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
117484   int rc = SQLITE_OK;             /* Return code */
117485   if( pCsr->pDeferred ){
117486     int i;                        /* Used to iterate through table columns */
117487     sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
117488     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
117489   
117490     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
117491     sqlite3_tokenizer *pT = p->pTokenizer;
117492     sqlite3_tokenizer_module const *pModule = pT->pModule;
117493    
117494     assert( pCsr->isRequireSeek==0 );
117495     iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
117496   
117497     for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
117498       const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
117499       sqlite3_tokenizer_cursor *pTC = 0;
117500   
117501       rc = pModule->xOpen(pT, zText, -1, &pTC);
117502       while( rc==SQLITE_OK ){
117503         char const *zToken;       /* Buffer containing token */
117504         int nToken;               /* Number of bytes in token */
117505         int iDum1, iDum2;         /* Dummy variables */
117506         int iPos;                 /* Position of token in zText */
117507   
117508         pTC->pTokenizer = pT;
117509         rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
117510         for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
117511           Fts3PhraseToken *pPT = pDef->pToken;
117512           if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
117513            && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
117514            && (0==memcmp(zToken, pPT->z, pPT->n))
117515           ){
117516             fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
117517           }
117518         }
117519       }
117520       if( pTC ) pModule->xClose(pTC);
117521       if( rc==SQLITE_DONE ) rc = SQLITE_OK;
117522     }
117523   
117524     for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
117525       if( pDef->pList ){
117526         rc = fts3PendingListAppendVarint(&pDef->pList, 0);
117527       }
117528     }
117529   }
117530
117531   return rc;
117532 }
117533
117534 /*
117535 ** Add an entry for token pToken to the pCsr->pDeferred list.
117536 */
117537 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
117538   Fts3Cursor *pCsr,               /* Fts3 table cursor */
117539   Fts3PhraseToken *pToken,        /* Token to defer */
117540   int iCol                        /* Column that token must appear in (or -1) */
117541 ){
117542   Fts3DeferredToken *pDeferred;
117543   pDeferred = sqlite3_malloc(sizeof(*pDeferred));
117544   if( !pDeferred ){
117545     return SQLITE_NOMEM;
117546   }
117547   memset(pDeferred, 0, sizeof(*pDeferred));
117548   pDeferred->pToken = pToken;
117549   pDeferred->pNext = pCsr->pDeferred; 
117550   pDeferred->iCol = iCol;
117551   pCsr->pDeferred = pDeferred;
117552
117553   assert( pToken->pDeferred==0 );
117554   pToken->pDeferred = pDeferred;
117555
117556   return SQLITE_OK;
117557 }
117558
117559
117560 /*
117561 ** This function does the work for the xUpdate method of FTS3 virtual
117562 ** tables.
117563 */
117564 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
117565   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
117566   int nArg,                       /* Size of argument array */
117567   sqlite3_value **apVal,          /* Array of arguments */
117568   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
117569 ){
117570   Fts3Table *p = (Fts3Table *)pVtab;
117571   int rc = SQLITE_OK;             /* Return Code */
117572   int isRemove = 0;               /* True for an UPDATE or DELETE */
117573   sqlite3_int64 iRemove = 0;      /* Rowid removed by UPDATE or DELETE */
117574   u32 *aSzIns;                    /* Sizes of inserted documents */
117575   u32 *aSzDel;                    /* Sizes of deleted documents */
117576   int nChng = 0;                  /* Net change in number of documents */
117577
117578   assert( p->pSegments==0 );
117579
117580   /* Allocate space to hold the change in document sizes */
117581   aSzIns = sqlite3_malloc( sizeof(aSzIns[0])*(p->nColumn+1)*2 );
117582   if( aSzIns==0 ) return SQLITE_NOMEM;
117583   aSzDel = &aSzIns[p->nColumn+1];
117584   memset(aSzIns, 0, sizeof(aSzIns[0])*(p->nColumn+1)*2);
117585
117586   /* If this is a DELETE or UPDATE operation, remove the old record. */
117587   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
117588     int isEmpty = 0;
117589     rc = fts3IsEmpty(p, apVal, &isEmpty);
117590     if( rc==SQLITE_OK ){
117591       if( isEmpty ){
117592         /* Deleting this row means the whole table is empty. In this case
117593         ** delete the contents of all three tables and throw away any
117594         ** data in the pendingTerms hash table.
117595         */
117596         rc = fts3DeleteAll(p);
117597       }else{
117598         isRemove = 1;
117599         iRemove = sqlite3_value_int64(apVal[0]);
117600         rc = fts3PendingTermsDocid(p, iRemove);
117601         fts3DeleteTerms(&rc, p, apVal, aSzDel);
117602         fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, apVal);
117603         if( p->bHasDocsize ){
117604           fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, apVal);
117605         }
117606         nChng--;
117607       }
117608     }
117609   }else if( sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL ){
117610     sqlite3_free(aSzIns);
117611     return fts3SpecialInsert(p, apVal[p->nColumn+2]);
117612   }
117613   
117614   /* If this is an INSERT or UPDATE operation, insert the new record. */
117615   if( nArg>1 && rc==SQLITE_OK ){
117616     rc = fts3InsertData(p, apVal, pRowid);
117617     if( rc==SQLITE_OK && (!isRemove || *pRowid!=iRemove) ){
117618       rc = fts3PendingTermsDocid(p, *pRowid);
117619     }
117620     if( rc==SQLITE_OK ){
117621       rc = fts3InsertTerms(p, apVal, aSzIns);
117622     }
117623     if( p->bHasDocsize ){
117624       fts3InsertDocsize(&rc, p, aSzIns);
117625     }
117626     nChng++;
117627   }
117628
117629   if( p->bHasStat ){
117630     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
117631   }
117632
117633   sqlite3_free(aSzIns);
117634   sqlite3Fts3SegmentsClose(p);
117635   return rc;
117636 }
117637
117638 /* 
117639 ** Flush any data in the pending-terms hash table to disk. If successful,
117640 ** merge all segments in the database (including the new segment, if 
117641 ** there was any data to flush) into a single segment. 
117642 */
117643 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
117644   int rc;
117645   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
117646   if( rc==SQLITE_OK ){
117647     rc = fts3SegmentMerge(p, -1);
117648     if( rc==SQLITE_OK ){
117649       rc = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
117650       if( rc==SQLITE_OK ){
117651         sqlite3Fts3PendingTermsClear(p);
117652       }
117653     }else{
117654       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
117655       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
117656     }
117657   }
117658   sqlite3Fts3SegmentsClose(p);
117659   return rc;
117660 }
117661
117662 #endif
117663
117664 /************** End of fts3_write.c ******************************************/
117665 /************** Begin file fts3_snippet.c ************************************/
117666 /*
117667 ** 2009 Oct 23
117668 **
117669 ** The author disclaims copyright to this source code.  In place of
117670 ** a legal notice, here is a blessing:
117671 **
117672 **    May you do good and not evil.
117673 **    May you find forgiveness for yourself and forgive others.
117674 **    May you share freely, never taking more than you give.
117675 **
117676 ******************************************************************************
117677 */
117678
117679 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
117680
117681
117682 /*
117683 ** Characters that may appear in the second argument to matchinfo().
117684 */
117685 #define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
117686 #define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
117687 #define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
117688 #define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
117689 #define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
117690 #define FTS3_MATCHINFO_LCS       's'        /* nCol values */
117691 #define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
117692
117693 /*
117694 ** The default value for the second argument to matchinfo(). 
117695 */
117696 #define FTS3_MATCHINFO_DEFAULT   "pcx"
117697
117698
117699 /*
117700 ** Used as an fts3ExprIterate() context when loading phrase doclists to
117701 ** Fts3Expr.aDoclist[]/nDoclist.
117702 */
117703 typedef struct LoadDoclistCtx LoadDoclistCtx;
117704 struct LoadDoclistCtx {
117705   Fts3Cursor *pCsr;               /* FTS3 Cursor */
117706   int nPhrase;                    /* Number of phrases seen so far */
117707   int nToken;                     /* Number of tokens seen so far */
117708 };
117709
117710 /*
117711 ** The following types are used as part of the implementation of the 
117712 ** fts3BestSnippet() routine.
117713 */
117714 typedef struct SnippetIter SnippetIter;
117715 typedef struct SnippetPhrase SnippetPhrase;
117716 typedef struct SnippetFragment SnippetFragment;
117717
117718 struct SnippetIter {
117719   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
117720   int iCol;                       /* Extract snippet from this column */
117721   int nSnippet;                   /* Requested snippet length (in tokens) */
117722   int nPhrase;                    /* Number of phrases in query */
117723   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
117724   int iCurrent;                   /* First token of current snippet */
117725 };
117726
117727 struct SnippetPhrase {
117728   int nToken;                     /* Number of tokens in phrase */
117729   char *pList;                    /* Pointer to start of phrase position list */
117730   int iHead;                      /* Next value in position list */
117731   char *pHead;                    /* Position list data following iHead */
117732   int iTail;                      /* Next value in trailing position list */
117733   char *pTail;                    /* Position list data following iTail */
117734 };
117735
117736 struct SnippetFragment {
117737   int iCol;                       /* Column snippet is extracted from */
117738   int iPos;                       /* Index of first token in snippet */
117739   u64 covered;                    /* Mask of query phrases covered */
117740   u64 hlmask;                     /* Mask of snippet terms to highlight */
117741 };
117742
117743 /*
117744 ** This type is used as an fts3ExprIterate() context object while 
117745 ** accumulating the data returned by the matchinfo() function.
117746 */
117747 typedef struct MatchInfo MatchInfo;
117748 struct MatchInfo {
117749   Fts3Cursor *pCursor;            /* FTS3 Cursor */
117750   int nCol;                       /* Number of columns in table */
117751   int nPhrase;                    /* Number of matchable phrases in query */
117752   sqlite3_int64 nDoc;             /* Number of docs in database */
117753   u32 *aMatchinfo;                /* Pre-allocated buffer */
117754 };
117755
117756
117757
117758 /*
117759 ** The snippet() and offsets() functions both return text values. An instance
117760 ** of the following structure is used to accumulate those values while the
117761 ** functions are running. See fts3StringAppend() for details.
117762 */
117763 typedef struct StrBuffer StrBuffer;
117764 struct StrBuffer {
117765   char *z;                        /* Pointer to buffer containing string */
117766   int n;                          /* Length of z in bytes (excl. nul-term) */
117767   int nAlloc;                     /* Allocated size of buffer z in bytes */
117768 };
117769
117770
117771 /*
117772 ** This function is used to help iterate through a position-list. A position
117773 ** list is a list of unique integers, sorted from smallest to largest. Each
117774 ** element of the list is represented by an FTS3 varint that takes the value
117775 ** of the difference between the current element and the previous one plus
117776 ** two. For example, to store the position-list:
117777 **
117778 **     4 9 113
117779 **
117780 ** the three varints:
117781 **
117782 **     6 7 106
117783 **
117784 ** are encoded.
117785 **
117786 ** When this function is called, *pp points to the start of an element of
117787 ** the list. *piPos contains the value of the previous entry in the list.
117788 ** After it returns, *piPos contains the value of the next element of the
117789 ** list and *pp is advanced to the following varint.
117790 */
117791 static void fts3GetDeltaPosition(char **pp, int *piPos){
117792   int iVal;
117793   *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
117794   *piPos += (iVal-2);
117795 }
117796
117797 /*
117798 ** Helper function for fts3ExprIterate() (see below).
117799 */
117800 static int fts3ExprIterate2(
117801   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
117802   int *piPhrase,                  /* Pointer to phrase counter */
117803   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
117804   void *pCtx                      /* Second argument to pass to callback */
117805 ){
117806   int rc;                         /* Return code */
117807   int eType = pExpr->eType;       /* Type of expression node pExpr */
117808
117809   if( eType!=FTSQUERY_PHRASE ){
117810     assert( pExpr->pLeft && pExpr->pRight );
117811     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
117812     if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
117813       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
117814     }
117815   }else{
117816     rc = x(pExpr, *piPhrase, pCtx);
117817     (*piPhrase)++;
117818   }
117819   return rc;
117820 }
117821
117822 /*
117823 ** Iterate through all phrase nodes in an FTS3 query, except those that
117824 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
117825 ** For each phrase node found, the supplied callback function is invoked.
117826 **
117827 ** If the callback function returns anything other than SQLITE_OK, 
117828 ** the iteration is abandoned and the error code returned immediately.
117829 ** Otherwise, SQLITE_OK is returned after a callback has been made for
117830 ** all eligible phrase nodes.
117831 */
117832 static int fts3ExprIterate(
117833   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
117834   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
117835   void *pCtx                      /* Second argument to pass to callback */
117836 ){
117837   int iPhrase = 0;                /* Variable used as the phrase counter */
117838   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
117839 }
117840
117841 /*
117842 ** The argument to this function is always a phrase node. Its doclist 
117843 ** (Fts3Expr.aDoclist[]) and the doclists associated with all phrase nodes
117844 ** to the left of this one in the query tree have already been loaded.
117845 **
117846 ** If this phrase node is part of a series of phrase nodes joined by 
117847 ** NEAR operators (and is not the left-most of said series), then elements are
117848 ** removed from the phrases doclist consistent with the NEAR restriction. If
117849 ** required, elements may be removed from the doclists of phrases to the
117850 ** left of this one that are part of the same series of NEAR operator 
117851 ** connected phrases.
117852 **
117853 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
117854 */
117855 static int fts3ExprNearTrim(Fts3Expr *pExpr){
117856   int rc = SQLITE_OK;
117857   Fts3Expr *pParent = pExpr->pParent;
117858
117859   assert( pExpr->eType==FTSQUERY_PHRASE );
117860   while( rc==SQLITE_OK
117861    && pParent 
117862    && pParent->eType==FTSQUERY_NEAR 
117863    && pParent->pRight==pExpr 
117864   ){
117865     /* This expression (pExpr) is the right-hand-side of a NEAR operator. 
117866     ** Find the expression to the left of the same operator.
117867     */
117868     int nNear = pParent->nNear;
117869     Fts3Expr *pLeft = pParent->pLeft;
117870
117871     if( pLeft->eType!=FTSQUERY_PHRASE ){
117872       assert( pLeft->eType==FTSQUERY_NEAR );
117873       assert( pLeft->pRight->eType==FTSQUERY_PHRASE );
117874       pLeft = pLeft->pRight;
117875     }
117876
117877     rc = sqlite3Fts3ExprNearTrim(pLeft, pExpr, nNear);
117878
117879     pExpr = pLeft;
117880     pParent = pExpr->pParent;
117881   }
117882
117883   return rc;
117884 }
117885
117886 /*
117887 ** This is an fts3ExprIterate() callback used while loading the doclists
117888 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
117889 ** fts3ExprLoadDoclists().
117890 */
117891 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
117892   int rc = SQLITE_OK;
117893   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
117894
117895   UNUSED_PARAMETER(iPhrase);
117896
117897   p->nPhrase++;
117898   p->nToken += pExpr->pPhrase->nToken;
117899
117900   if( pExpr->isLoaded==0 ){
117901     rc = sqlite3Fts3ExprLoadDoclist(p->pCsr, pExpr);
117902     pExpr->isLoaded = 1;
117903     if( rc==SQLITE_OK ){
117904       rc = fts3ExprNearTrim(pExpr);
117905     }
117906   }
117907
117908   return rc;
117909 }
117910
117911 /*
117912 ** Load the doclists for each phrase in the query associated with FTS3 cursor
117913 ** pCsr. 
117914 **
117915 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable 
117916 ** phrases in the expression (all phrases except those directly or 
117917 ** indirectly descended from the right-hand-side of a NOT operator). If 
117918 ** pnToken is not NULL, then it is set to the number of tokens in all
117919 ** matchable phrases of the expression.
117920 */
117921 static int fts3ExprLoadDoclists(
117922   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
117923   int *pnPhrase,                  /* OUT: Number of phrases in query */
117924   int *pnToken                    /* OUT: Number of tokens in query */
117925 ){
117926   int rc;                         /* Return Code */
117927   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
117928   sCtx.pCsr = pCsr;
117929   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
117930   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
117931   if( pnToken ) *pnToken = sCtx.nToken;
117932   return rc;
117933 }
117934
117935 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
117936   (*(int *)ctx)++;
117937   UNUSED_PARAMETER(pExpr);
117938   UNUSED_PARAMETER(iPhrase);
117939   return SQLITE_OK;
117940 }
117941 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
117942   int nPhrase = 0;
117943   (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
117944   return nPhrase;
117945 }
117946
117947 /*
117948 ** Advance the position list iterator specified by the first two 
117949 ** arguments so that it points to the first element with a value greater
117950 ** than or equal to parameter iNext.
117951 */
117952 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
117953   char *pIter = *ppIter;
117954   if( pIter ){
117955     int iIter = *piIter;
117956
117957     while( iIter<iNext ){
117958       if( 0==(*pIter & 0xFE) ){
117959         iIter = -1;
117960         pIter = 0;
117961         break;
117962       }
117963       fts3GetDeltaPosition(&pIter, &iIter);
117964     }
117965
117966     *piIter = iIter;
117967     *ppIter = pIter;
117968   }
117969 }
117970
117971 /*
117972 ** Advance the snippet iterator to the next candidate snippet.
117973 */
117974 static int fts3SnippetNextCandidate(SnippetIter *pIter){
117975   int i;                          /* Loop counter */
117976
117977   if( pIter->iCurrent<0 ){
117978     /* The SnippetIter object has just been initialized. The first snippet
117979     ** candidate always starts at offset 0 (even if this candidate has a
117980     ** score of 0.0).
117981     */
117982     pIter->iCurrent = 0;
117983
117984     /* Advance the 'head' iterator of each phrase to the first offset that
117985     ** is greater than or equal to (iNext+nSnippet).
117986     */
117987     for(i=0; i<pIter->nPhrase; i++){
117988       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
117989       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
117990     }
117991   }else{
117992     int iStart;
117993     int iEnd = 0x7FFFFFFF;
117994
117995     for(i=0; i<pIter->nPhrase; i++){
117996       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
117997       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
117998         iEnd = pPhrase->iHead;
117999       }
118000     }
118001     if( iEnd==0x7FFFFFFF ){
118002       return 1;
118003     }
118004
118005     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
118006     for(i=0; i<pIter->nPhrase; i++){
118007       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
118008       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
118009       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
118010     }
118011   }
118012
118013   return 0;
118014 }
118015
118016 /*
118017 ** Retrieve information about the current candidate snippet of snippet 
118018 ** iterator pIter.
118019 */
118020 static void fts3SnippetDetails(
118021   SnippetIter *pIter,             /* Snippet iterator */
118022   u64 mCovered,                   /* Bitmask of phrases already covered */
118023   int *piToken,                   /* OUT: First token of proposed snippet */
118024   int *piScore,                   /* OUT: "Score" for this snippet */
118025   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
118026   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
118027 ){
118028   int iStart = pIter->iCurrent;   /* First token of snippet */
118029   int iScore = 0;                 /* Score of this snippet */
118030   int i;                          /* Loop counter */
118031   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
118032   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
118033
118034   for(i=0; i<pIter->nPhrase; i++){
118035     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
118036     if( pPhrase->pTail ){
118037       char *pCsr = pPhrase->pTail;
118038       int iCsr = pPhrase->iTail;
118039
118040       while( iCsr<(iStart+pIter->nSnippet) ){
118041         int j;
118042         u64 mPhrase = (u64)1 << i;
118043         u64 mPos = (u64)1 << (iCsr - iStart);
118044         assert( iCsr>=iStart );
118045         if( (mCover|mCovered)&mPhrase ){
118046           iScore++;
118047         }else{
118048           iScore += 1000;
118049         }
118050         mCover |= mPhrase;
118051
118052         for(j=0; j<pPhrase->nToken; j++){
118053           mHighlight |= (mPos>>j);
118054         }
118055
118056         if( 0==(*pCsr & 0x0FE) ) break;
118057         fts3GetDeltaPosition(&pCsr, &iCsr);
118058       }
118059     }
118060   }
118061
118062   /* Set the output variables before returning. */
118063   *piToken = iStart;
118064   *piScore = iScore;
118065   *pmCover = mCover;
118066   *pmHighlight = mHighlight;
118067 }
118068
118069 /*
118070 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
118071 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
118072 */
118073 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
118074   SnippetIter *p = (SnippetIter *)ctx;
118075   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
118076   char *pCsr;
118077
118078   pPhrase->nToken = pExpr->pPhrase->nToken;
118079
118080   pCsr = sqlite3Fts3FindPositions(pExpr, p->pCsr->iPrevId, p->iCol);
118081   if( pCsr ){
118082     int iFirst = 0;
118083     pPhrase->pList = pCsr;
118084     fts3GetDeltaPosition(&pCsr, &iFirst);
118085     pPhrase->pHead = pCsr;
118086     pPhrase->pTail = pCsr;
118087     pPhrase->iHead = iFirst;
118088     pPhrase->iTail = iFirst;
118089   }else{
118090     assert( pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 );
118091   }
118092
118093   return SQLITE_OK;
118094 }
118095
118096 /*
118097 ** Select the fragment of text consisting of nFragment contiguous tokens 
118098 ** from column iCol that represent the "best" snippet. The best snippet
118099 ** is the snippet with the highest score, where scores are calculated
118100 ** by adding:
118101 **
118102 **   (a) +1 point for each occurence of a matchable phrase in the snippet.
118103 **
118104 **   (b) +1000 points for the first occurence of each matchable phrase in 
118105 **       the snippet for which the corresponding mCovered bit is not set.
118106 **
118107 ** The selected snippet parameters are stored in structure *pFragment before
118108 ** returning. The score of the selected snippet is stored in *piScore
118109 ** before returning.
118110 */
118111 static int fts3BestSnippet(
118112   int nSnippet,                   /* Desired snippet length */
118113   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
118114   int iCol,                       /* Index of column to create snippet from */
118115   u64 mCovered,                   /* Mask of phrases already covered */
118116   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
118117   SnippetFragment *pFragment,     /* OUT: Best snippet found */
118118   int *piScore                    /* OUT: Score of snippet pFragment */
118119 ){
118120   int rc;                         /* Return Code */
118121   int nList;                      /* Number of phrases in expression */
118122   SnippetIter sIter;              /* Iterates through snippet candidates */
118123   int nByte;                      /* Number of bytes of space to allocate */
118124   int iBestScore = -1;            /* Best snippet score found so far */
118125   int i;                          /* Loop counter */
118126
118127   memset(&sIter, 0, sizeof(sIter));
118128
118129   /* Iterate through the phrases in the expression to count them. The same
118130   ** callback makes sure the doclists are loaded for each phrase.
118131   */
118132   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
118133   if( rc!=SQLITE_OK ){
118134     return rc;
118135   }
118136
118137   /* Now that it is known how many phrases there are, allocate and zero
118138   ** the required space using malloc().
118139   */
118140   nByte = sizeof(SnippetPhrase) * nList;
118141   sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
118142   if( !sIter.aPhrase ){
118143     return SQLITE_NOMEM;
118144   }
118145   memset(sIter.aPhrase, 0, nByte);
118146
118147   /* Initialize the contents of the SnippetIter object. Then iterate through
118148   ** the set of phrases in the expression to populate the aPhrase[] array.
118149   */
118150   sIter.pCsr = pCsr;
118151   sIter.iCol = iCol;
118152   sIter.nSnippet = nSnippet;
118153   sIter.nPhrase = nList;
118154   sIter.iCurrent = -1;
118155   (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
118156
118157   /* Set the *pmSeen output variable. */
118158   for(i=0; i<nList; i++){
118159     if( sIter.aPhrase[i].pHead ){
118160       *pmSeen |= (u64)1 << i;
118161     }
118162   }
118163
118164   /* Loop through all candidate snippets. Store the best snippet in 
118165   ** *pFragment. Store its associated 'score' in iBestScore.
118166   */
118167   pFragment->iCol = iCol;
118168   while( !fts3SnippetNextCandidate(&sIter) ){
118169     int iPos;
118170     int iScore;
118171     u64 mCover;
118172     u64 mHighlight;
118173     fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
118174     assert( iScore>=0 );
118175     if( iScore>iBestScore ){
118176       pFragment->iPos = iPos;
118177       pFragment->hlmask = mHighlight;
118178       pFragment->covered = mCover;
118179       iBestScore = iScore;
118180     }
118181   }
118182
118183   sqlite3_free(sIter.aPhrase);
118184   *piScore = iBestScore;
118185   return SQLITE_OK;
118186 }
118187
118188
118189 /*
118190 ** Append a string to the string-buffer passed as the first argument.
118191 **
118192 ** If nAppend is negative, then the length of the string zAppend is
118193 ** determined using strlen().
118194 */
118195 static int fts3StringAppend(
118196   StrBuffer *pStr,                /* Buffer to append to */
118197   const char *zAppend,            /* Pointer to data to append to buffer */
118198   int nAppend                     /* Size of zAppend in bytes (or -1) */
118199 ){
118200   if( nAppend<0 ){
118201     nAppend = (int)strlen(zAppend);
118202   }
118203
118204   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
118205   ** to grow the buffer until so that it is big enough to accomadate the
118206   ** appended data.
118207   */
118208   if( pStr->n+nAppend+1>=pStr->nAlloc ){
118209     int nAlloc = pStr->nAlloc+nAppend+100;
118210     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
118211     if( !zNew ){
118212       return SQLITE_NOMEM;
118213     }
118214     pStr->z = zNew;
118215     pStr->nAlloc = nAlloc;
118216   }
118217
118218   /* Append the data to the string buffer. */
118219   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
118220   pStr->n += nAppend;
118221   pStr->z[pStr->n] = '\0';
118222
118223   return SQLITE_OK;
118224 }
118225
118226 /*
118227 ** The fts3BestSnippet() function often selects snippets that end with a
118228 ** query term. That is, the final term of the snippet is always a term
118229 ** that requires highlighting. For example, if 'X' is a highlighted term
118230 ** and '.' is a non-highlighted term, BestSnippet() may select:
118231 **
118232 **     ........X.....X
118233 **
118234 ** This function "shifts" the beginning of the snippet forward in the 
118235 ** document so that there are approximately the same number of 
118236 ** non-highlighted terms to the right of the final highlighted term as there
118237 ** are to the left of the first highlighted term. For example, to this:
118238 **
118239 **     ....X.....X....
118240 **
118241 ** This is done as part of extracting the snippet text, not when selecting
118242 ** the snippet. Snippet selection is done based on doclists only, so there
118243 ** is no way for fts3BestSnippet() to know whether or not the document 
118244 ** actually contains terms that follow the final highlighted term. 
118245 */
118246 static int fts3SnippetShift(
118247   Fts3Table *pTab,                /* FTS3 table snippet comes from */
118248   int nSnippet,                   /* Number of tokens desired for snippet */
118249   const char *zDoc,               /* Document text to extract snippet from */
118250   int nDoc,                       /* Size of buffer zDoc in bytes */
118251   int *piPos,                     /* IN/OUT: First token of snippet */
118252   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
118253 ){
118254   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
118255
118256   if( hlmask ){
118257     int nLeft;                    /* Tokens to the left of first highlight */
118258     int nRight;                   /* Tokens to the right of last highlight */
118259     int nDesired;                 /* Ideal number of tokens to shift forward */
118260
118261     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
118262     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
118263     nDesired = (nLeft-nRight)/2;
118264
118265     /* Ideally, the start of the snippet should be pushed forward in the
118266     ** document nDesired tokens. This block checks if there are actually
118267     ** nDesired tokens to the right of the snippet. If so, *piPos and
118268     ** *pHlMask are updated to shift the snippet nDesired tokens to the
118269     ** right. Otherwise, the snippet is shifted by the number of tokens
118270     ** available.
118271     */
118272     if( nDesired>0 ){
118273       int nShift;                 /* Number of tokens to shift snippet by */
118274       int iCurrent = 0;           /* Token counter */
118275       int rc;                     /* Return Code */
118276       sqlite3_tokenizer_module *pMod;
118277       sqlite3_tokenizer_cursor *pC;
118278       pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
118279
118280       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
118281       ** or more tokens in zDoc/nDoc.
118282       */
118283       rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
118284       if( rc!=SQLITE_OK ){
118285         return rc;
118286       }
118287       pC->pTokenizer = pTab->pTokenizer;
118288       while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
118289         const char *ZDUMMY; int DUMMY1, DUMMY2, DUMMY3;
118290         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
118291       }
118292       pMod->xClose(pC);
118293       if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
118294
118295       nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
118296       assert( nShift<=nDesired );
118297       if( nShift>0 ){
118298         *piPos += nShift;
118299         *pHlmask = hlmask >> nShift;
118300       }
118301     }
118302   }
118303   return SQLITE_OK;
118304 }
118305
118306 /*
118307 ** Extract the snippet text for fragment pFragment from cursor pCsr and
118308 ** append it to string buffer pOut.
118309 */
118310 static int fts3SnippetText(
118311   Fts3Cursor *pCsr,               /* FTS3 Cursor */
118312   SnippetFragment *pFragment,     /* Snippet to extract */
118313   int iFragment,                  /* Fragment number */
118314   int isLast,                     /* True for final fragment in snippet */
118315   int nSnippet,                   /* Number of tokens in extracted snippet */
118316   const char *zOpen,              /* String inserted before highlighted term */
118317   const char *zClose,             /* String inserted after highlighted term */
118318   const char *zEllipsis,          /* String inserted between snippets */
118319   StrBuffer *pOut                 /* Write output here */
118320 ){
118321   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
118322   int rc;                         /* Return code */
118323   const char *zDoc;               /* Document text to extract snippet from */
118324   int nDoc;                       /* Size of zDoc in bytes */
118325   int iCurrent = 0;               /* Current token number of document */
118326   int iEnd = 0;                   /* Byte offset of end of current token */
118327   int isShiftDone = 0;            /* True after snippet is shifted */
118328   int iPos = pFragment->iPos;     /* First token of snippet */
118329   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
118330   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
118331   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
118332   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
118333   const char *ZDUMMY;             /* Dummy argument used with tokenizer */
118334   int DUMMY1;                     /* Dummy argument used with tokenizer */
118335   
118336   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
118337   if( zDoc==0 ){
118338     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
118339       return SQLITE_NOMEM;
118340     }
118341     return SQLITE_OK;
118342   }
118343   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
118344
118345   /* Open a token cursor on the document. */
118346   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
118347   rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
118348   if( rc!=SQLITE_OK ){
118349     return rc;
118350   }
118351   pC->pTokenizer = pTab->pTokenizer;
118352
118353   while( rc==SQLITE_OK ){
118354     int iBegin;                   /* Offset in zDoc of start of token */
118355     int iFin;                     /* Offset in zDoc of end of token */
118356     int isHighlight;              /* True for highlighted terms */
118357
118358     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
118359     if( rc!=SQLITE_OK ){
118360       if( rc==SQLITE_DONE ){
118361         /* Special case - the last token of the snippet is also the last token
118362         ** of the column. Append any punctuation that occurred between the end
118363         ** of the previous token and the end of the document to the output. 
118364         ** Then break out of the loop. */
118365         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
118366       }
118367       break;
118368     }
118369     if( iCurrent<iPos ){ continue; }
118370
118371     if( !isShiftDone ){
118372       int n = nDoc - iBegin;
118373       rc = fts3SnippetShift(pTab, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask);
118374       isShiftDone = 1;
118375
118376       /* Now that the shift has been done, check if the initial "..." are
118377       ** required. They are required if (a) this is not the first fragment,
118378       ** or (b) this fragment does not begin at position 0 of its column. 
118379       */
118380       if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
118381         rc = fts3StringAppend(pOut, zEllipsis, -1);
118382       }
118383       if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
118384     }
118385
118386     if( iCurrent>=(iPos+nSnippet) ){
118387       if( isLast ){
118388         rc = fts3StringAppend(pOut, zEllipsis, -1);
118389       }
118390       break;
118391     }
118392
118393     /* Set isHighlight to true if this term should be highlighted. */
118394     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
118395
118396     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
118397     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
118398     if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
118399     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
118400
118401     iEnd = iFin;
118402   }
118403
118404   pMod->xClose(pC);
118405   return rc;
118406 }
118407
118408
118409 /*
118410 ** This function is used to count the entries in a column-list (a 
118411 ** delta-encoded list of term offsets within a single column of a single 
118412 ** row). When this function is called, *ppCollist should point to the
118413 ** beginning of the first varint in the column-list (the varint that
118414 ** contains the position of the first matching term in the column data).
118415 ** Before returning, *ppCollist is set to point to the first byte after
118416 ** the last varint in the column-list (either the 0x00 signifying the end
118417 ** of the position-list, or the 0x01 that precedes the column number of
118418 ** the next column in the position-list).
118419 **
118420 ** The number of elements in the column-list is returned.
118421 */
118422 static int fts3ColumnlistCount(char **ppCollist){
118423   char *pEnd = *ppCollist;
118424   char c = 0;
118425   int nEntry = 0;
118426
118427   /* A column-list is terminated by either a 0x01 or 0x00. */
118428   while( 0xFE & (*pEnd | c) ){
118429     c = *pEnd++ & 0x80;
118430     if( !c ) nEntry++;
118431   }
118432
118433   *ppCollist = pEnd;
118434   return nEntry;
118435 }
118436
118437 static void fts3LoadColumnlistCounts(char **pp, u32 *aOut, int isGlobal){
118438   char *pCsr = *pp;
118439   while( *pCsr ){
118440     int nHit;
118441     sqlite3_int64 iCol = 0;
118442     if( *pCsr==0x01 ){
118443       pCsr++;
118444       pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
118445     }
118446     nHit = fts3ColumnlistCount(&pCsr);
118447     assert( nHit>0 );
118448     if( isGlobal ){
118449       aOut[iCol*3+1]++;
118450     }
118451     aOut[iCol*3] += nHit;
118452   }
118453   pCsr++;
118454   *pp = pCsr;
118455 }
118456
118457 /*
118458 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
118459 ** for a single query. 
118460 **
118461 ** fts3ExprIterate() callback to load the 'global' elements of a
118462 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements 
118463 ** of the matchinfo array that are constant for all rows returned by the 
118464 ** current query.
118465 **
118466 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
118467 ** function populates Matchinfo.aMatchinfo[] as follows:
118468 **
118469 **   for(iCol=0; iCol<nCol; iCol++){
118470 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
118471 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
118472 **   }
118473 **
118474 ** where X is the number of matches for phrase iPhrase is column iCol of all
118475 ** rows of the table. Y is the number of rows for which column iCol contains
118476 ** at least one instance of phrase iPhrase.
118477 **
118478 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
118479 ** Y values are set to nDoc, where nDoc is the number of documents in the 
118480 ** file system. This is done because the full-text index doclist is required
118481 ** to calculate these values properly, and the full-text index doclist is
118482 ** not available for deferred tokens.
118483 */
118484 static int fts3ExprGlobalHitsCb(
118485   Fts3Expr *pExpr,                /* Phrase expression node */
118486   int iPhrase,                    /* Phrase number (numbered from zero) */
118487   void *pCtx                      /* Pointer to MatchInfo structure */
118488 ){
118489   MatchInfo *p = (MatchInfo *)pCtx;
118490   Fts3Cursor *pCsr = p->pCursor;
118491   char *pIter;
118492   char *pEnd;
118493   char *pFree = 0;
118494   u32 *aOut = &p->aMatchinfo[3*iPhrase*p->nCol];
118495
118496   assert( pExpr->isLoaded );
118497   assert( pExpr->eType==FTSQUERY_PHRASE );
118498
118499   if( pCsr->pDeferred ){
118500     Fts3Phrase *pPhrase = pExpr->pPhrase;
118501     int ii;
118502     for(ii=0; ii<pPhrase->nToken; ii++){
118503       if( pPhrase->aToken[ii].bFulltext ) break;
118504     }
118505     if( ii<pPhrase->nToken ){
118506       int nFree = 0;
118507       int rc = sqlite3Fts3ExprLoadFtDoclist(pCsr, pExpr, &pFree, &nFree);
118508       if( rc!=SQLITE_OK ) return rc;
118509       pIter = pFree;
118510       pEnd = &pFree[nFree];
118511     }else{
118512       int iCol;                   /* Column index */
118513       for(iCol=0; iCol<p->nCol; iCol++){
118514         aOut[iCol*3 + 1] = (u32)p->nDoc;
118515         aOut[iCol*3 + 2] = (u32)p->nDoc;
118516       }
118517       return SQLITE_OK;
118518     }
118519   }else{
118520     pIter = pExpr->aDoclist;
118521     pEnd = &pExpr->aDoclist[pExpr->nDoclist];
118522   }
118523
118524   /* Fill in the global hit count matrix row for this phrase. */
118525   while( pIter<pEnd ){
118526     while( *pIter++ & 0x80 );      /* Skip past docid. */
118527     fts3LoadColumnlistCounts(&pIter, &aOut[1], 1);
118528   }
118529
118530   sqlite3_free(pFree);
118531   return SQLITE_OK;
118532 }
118533
118534 /*
118535 ** fts3ExprIterate() callback used to collect the "local" part of the
118536 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the 
118537 ** array that are different for each row returned by the query.
118538 */
118539 static int fts3ExprLocalHitsCb(
118540   Fts3Expr *pExpr,                /* Phrase expression node */
118541   int iPhrase,                    /* Phrase number */
118542   void *pCtx                      /* Pointer to MatchInfo structure */
118543 ){
118544   MatchInfo *p = (MatchInfo *)pCtx;
118545
118546   if( pExpr->aDoclist ){
118547     char *pCsr;
118548     int iStart = iPhrase * p->nCol * 3;
118549     int i;
118550
118551     for(i=0; i<p->nCol; i++) p->aMatchinfo[iStart+i*3] = 0;
118552
118553     pCsr = sqlite3Fts3FindPositions(pExpr, p->pCursor->iPrevId, -1);
118554     if( pCsr ){
118555       fts3LoadColumnlistCounts(&pCsr, &p->aMatchinfo[iStart], 0);
118556     }
118557   }
118558
118559   return SQLITE_OK;
118560 }
118561
118562 static int fts3MatchinfoCheck(
118563   Fts3Table *pTab, 
118564   char cArg,
118565   char **pzErr
118566 ){
118567   if( (cArg==FTS3_MATCHINFO_NPHRASE)
118568    || (cArg==FTS3_MATCHINFO_NCOL)
118569    || (cArg==FTS3_MATCHINFO_NDOC && pTab->bHasStat)
118570    || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bHasStat)
118571    || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
118572    || (cArg==FTS3_MATCHINFO_LCS)
118573    || (cArg==FTS3_MATCHINFO_HITS)
118574   ){
118575     return SQLITE_OK;
118576   }
118577   *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
118578   return SQLITE_ERROR;
118579 }
118580
118581 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
118582   int nVal;                       /* Number of integers output by cArg */
118583
118584   switch( cArg ){
118585     case FTS3_MATCHINFO_NDOC:
118586     case FTS3_MATCHINFO_NPHRASE: 
118587     case FTS3_MATCHINFO_NCOL: 
118588       nVal = 1;
118589       break;
118590
118591     case FTS3_MATCHINFO_AVGLENGTH:
118592     case FTS3_MATCHINFO_LENGTH:
118593     case FTS3_MATCHINFO_LCS:
118594       nVal = pInfo->nCol;
118595       break;
118596
118597     default:
118598       assert( cArg==FTS3_MATCHINFO_HITS );
118599       nVal = pInfo->nCol * pInfo->nPhrase * 3;
118600       break;
118601   }
118602
118603   return nVal;
118604 }
118605
118606 static int fts3MatchinfoSelectDoctotal(
118607   Fts3Table *pTab,
118608   sqlite3_stmt **ppStmt,
118609   sqlite3_int64 *pnDoc,
118610   const char **paLen
118611 ){
118612   sqlite3_stmt *pStmt;
118613   const char *a;
118614   sqlite3_int64 nDoc;
118615
118616   if( !*ppStmt ){
118617     int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
118618     if( rc!=SQLITE_OK ) return rc;
118619   }
118620   pStmt = *ppStmt;
118621   assert( sqlite3_data_count(pStmt)==1 );
118622
118623   a = sqlite3_column_blob(pStmt, 0);
118624   a += sqlite3Fts3GetVarint(a, &nDoc);
118625   *pnDoc = (u32)nDoc;
118626
118627   if( paLen ) *paLen = a;
118628   return SQLITE_OK;
118629 }
118630
118631 /*
118632 ** An instance of the following structure is used to store state while 
118633 ** iterating through a multi-column position-list corresponding to the
118634 ** hits for a single phrase on a single row in order to calculate the
118635 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
118636 */
118637 typedef struct LcsIterator LcsIterator;
118638 struct LcsIterator {
118639   Fts3Expr *pExpr;                /* Pointer to phrase expression */
118640   char *pRead;                    /* Cursor used to iterate through aDoclist */
118641   int iPosOffset;                 /* Tokens count up to end of this phrase */
118642   int iCol;                       /* Current column number */
118643   int iPos;                       /* Current position */
118644 };
118645
118646 /* 
118647 ** If LcsIterator.iCol is set to the following value, the iterator has
118648 ** finished iterating through all offsets for all columns.
118649 */
118650 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
118651
118652 static int fts3MatchinfoLcsCb(
118653   Fts3Expr *pExpr,                /* Phrase expression node */
118654   int iPhrase,                    /* Phrase number (numbered from zero) */
118655   void *pCtx                      /* Pointer to MatchInfo structure */
118656 ){
118657   LcsIterator *aIter = (LcsIterator *)pCtx;
118658   aIter[iPhrase].pExpr = pExpr;
118659   return SQLITE_OK;
118660 }
118661
118662 /*
118663 ** Advance the iterator passed as an argument to the next position. Return
118664 ** 1 if the iterator is at EOF or if it now points to the start of the
118665 ** position list for the next column.
118666 */
118667 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
118668   char *pRead = pIter->pRead;
118669   sqlite3_int64 iRead;
118670   int rc = 0;
118671
118672   pRead += sqlite3Fts3GetVarint(pRead, &iRead);
118673   if( iRead==0 ){
118674     pIter->iCol = LCS_ITERATOR_FINISHED;
118675     rc = 1;
118676   }else{
118677     if( iRead==1 ){
118678       pRead += sqlite3Fts3GetVarint(pRead, &iRead);
118679       pIter->iCol = (int)iRead;
118680       pIter->iPos = pIter->iPosOffset;
118681       pRead += sqlite3Fts3GetVarint(pRead, &iRead);
118682       rc = 1;
118683     }
118684     pIter->iPos += (int)(iRead-2);
118685   }
118686
118687   pIter->pRead = pRead;
118688   return rc;
118689 }
118690   
118691 /*
118692 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag. 
118693 **
118694 ** If the call is successful, the longest-common-substring lengths for each
118695 ** column are written into the first nCol elements of the pInfo->aMatchinfo[] 
118696 ** array before returning. SQLITE_OK is returned in this case.
118697 **
118698 ** Otherwise, if an error occurs, an SQLite error code is returned and the
118699 ** data written to the first nCol elements of pInfo->aMatchinfo[] is 
118700 ** undefined.
118701 */
118702 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
118703   LcsIterator *aIter;
118704   int i;
118705   int iCol;
118706   int nToken = 0;
118707
118708   /* Allocate and populate the array of LcsIterator objects. The array
118709   ** contains one element for each matchable phrase in the query.
118710   **/
118711   aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
118712   if( !aIter ) return SQLITE_NOMEM;
118713   memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
118714   (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
118715   for(i=0; i<pInfo->nPhrase; i++){
118716     LcsIterator *pIter = &aIter[i];
118717     nToken -= pIter->pExpr->pPhrase->nToken;
118718     pIter->iPosOffset = nToken;
118719     pIter->pRead = sqlite3Fts3FindPositions(pIter->pExpr, pCsr->iPrevId, -1);
118720     if( pIter->pRead ){
118721       pIter->iPos = pIter->iPosOffset;
118722       fts3LcsIteratorAdvance(&aIter[i]);
118723     }else{
118724       pIter->iCol = LCS_ITERATOR_FINISHED;
118725     }
118726   }
118727
118728   for(iCol=0; iCol<pInfo->nCol; iCol++){
118729     int nLcs = 0;                 /* LCS value for this column */
118730     int nLive = 0;                /* Number of iterators in aIter not at EOF */
118731
118732     /* Loop through the iterators in aIter[]. Set nLive to the number of
118733     ** iterators that point to a position-list corresponding to column iCol.
118734     */
118735     for(i=0; i<pInfo->nPhrase; i++){
118736       assert( aIter[i].iCol>=iCol );
118737       if( aIter[i].iCol==iCol ) nLive++;
118738     }
118739
118740     /* The following loop runs until all iterators in aIter[] have finished
118741     ** iterating through positions in column iCol. Exactly one of the 
118742     ** iterators is advanced each time the body of the loop is run.
118743     */
118744     while( nLive>0 ){
118745       LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
118746       int nThisLcs = 0;           /* LCS for the current iterator positions */
118747
118748       for(i=0; i<pInfo->nPhrase; i++){
118749         LcsIterator *pIter = &aIter[i];
118750         if( iCol!=pIter->iCol ){  
118751           /* This iterator is already at EOF for this column. */
118752           nThisLcs = 0;
118753         }else{
118754           if( pAdv==0 || pIter->iPos<pAdv->iPos ){
118755             pAdv = pIter;
118756           }
118757           if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
118758             nThisLcs++;
118759           }else{
118760             nThisLcs = 1;
118761           }
118762           if( nThisLcs>nLcs ) nLcs = nThisLcs;
118763         }
118764       }
118765       if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
118766     }
118767
118768     pInfo->aMatchinfo[iCol] = nLcs;
118769   }
118770
118771   sqlite3_free(aIter);
118772   return SQLITE_OK;
118773 }
118774
118775 /*
118776 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
118777 ** be returned by the matchinfo() function. Argument zArg contains the 
118778 ** format string passed as the second argument to matchinfo (or the
118779 ** default value "pcx" if no second argument was specified). The format
118780 ** string has already been validated and the pInfo->aMatchinfo[] array
118781 ** is guaranteed to be large enough for the output.
118782 **
118783 ** If bGlobal is true, then populate all fields of the matchinfo() output.
118784 ** If it is false, then assume that those fields that do not change between
118785 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
118786 ** have already been populated.
118787 **
118788 ** Return SQLITE_OK if successful, or an SQLite error code if an error 
118789 ** occurs. If a value other than SQLITE_OK is returned, the state the
118790 ** pInfo->aMatchinfo[] buffer is left in is undefined.
118791 */
118792 static int fts3MatchinfoValues(
118793   Fts3Cursor *pCsr,               /* FTS3 cursor object */
118794   int bGlobal,                    /* True to grab the global stats */
118795   MatchInfo *pInfo,               /* Matchinfo context object */
118796   const char *zArg                /* Matchinfo format string */
118797 ){
118798   int rc = SQLITE_OK;
118799   int i;
118800   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
118801   sqlite3_stmt *pSelect = 0;
118802
118803   for(i=0; rc==SQLITE_OK && zArg[i]; i++){
118804
118805     switch( zArg[i] ){
118806       case FTS3_MATCHINFO_NPHRASE:
118807         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
118808         break;
118809
118810       case FTS3_MATCHINFO_NCOL:
118811         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
118812         break;
118813         
118814       case FTS3_MATCHINFO_NDOC:
118815         if( bGlobal ){
118816           sqlite3_int64 nDoc;
118817           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
118818           pInfo->aMatchinfo[0] = (u32)nDoc;
118819         }
118820         break;
118821
118822       case FTS3_MATCHINFO_AVGLENGTH: 
118823         if( bGlobal ){
118824           sqlite3_int64 nDoc;     /* Number of rows in table */
118825           const char *a;          /* Aggregate column length array */
118826
118827           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
118828           if( rc==SQLITE_OK ){
118829             int iCol;
118830             for(iCol=0; iCol<pInfo->nCol; iCol++){
118831               sqlite3_int64 nToken;
118832               a += sqlite3Fts3GetVarint(a, &nToken);
118833               pInfo->aMatchinfo[iCol] = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
118834             }
118835           }
118836         }
118837         break;
118838
118839       case FTS3_MATCHINFO_LENGTH: {
118840         sqlite3_stmt *pSelectDocsize = 0;
118841         rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
118842         if( rc==SQLITE_OK ){
118843           int iCol;
118844           const char *a = sqlite3_column_blob(pSelectDocsize, 0);
118845           for(iCol=0; iCol<pInfo->nCol; iCol++){
118846             sqlite3_int64 nToken;
118847             a += sqlite3Fts3GetVarint(a, &nToken);
118848             pInfo->aMatchinfo[iCol] = (u32)nToken;
118849           }
118850         }
118851         sqlite3_reset(pSelectDocsize);
118852         break;
118853       }
118854
118855       case FTS3_MATCHINFO_LCS:
118856         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
118857         if( rc==SQLITE_OK ){
118858           rc = fts3MatchinfoLcs(pCsr, pInfo);
118859         }
118860         break;
118861
118862       default: {
118863         Fts3Expr *pExpr;
118864         assert( zArg[i]==FTS3_MATCHINFO_HITS );
118865         pExpr = pCsr->pExpr;
118866         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
118867         if( rc!=SQLITE_OK ) break;
118868         if( bGlobal ){
118869           if( pCsr->pDeferred ){
118870             rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
118871             if( rc!=SQLITE_OK ) break;
118872           }
118873           rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
118874           if( rc!=SQLITE_OK ) break;
118875         }
118876         (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
118877         break;
118878       }
118879     }
118880
118881     pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
118882   }
118883
118884   sqlite3_reset(pSelect);
118885   return rc;
118886 }
118887
118888
118889 /*
118890 ** Populate pCsr->aMatchinfo[] with data for the current row. The 
118891 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
118892 */
118893 static int fts3GetMatchinfo(
118894   Fts3Cursor *pCsr,               /* FTS3 Cursor object */
118895   const char *zArg                /* Second argument to matchinfo() function */
118896 ){
118897   MatchInfo sInfo;
118898   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
118899   int rc = SQLITE_OK;
118900   int bGlobal = 0;                /* Collect 'global' stats as well as local */
118901
118902   memset(&sInfo, 0, sizeof(MatchInfo));
118903   sInfo.pCursor = pCsr;
118904   sInfo.nCol = pTab->nColumn;
118905
118906   /* If there is cached matchinfo() data, but the format string for the 
118907   ** cache does not match the format string for this request, discard 
118908   ** the cached data. */
118909   if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
118910     assert( pCsr->aMatchinfo );
118911     sqlite3_free(pCsr->aMatchinfo);
118912     pCsr->zMatchinfo = 0;
118913     pCsr->aMatchinfo = 0;
118914   }
118915
118916   /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
118917   ** matchinfo function has been called for this query. In this case 
118918   ** allocate the array used to accumulate the matchinfo data and
118919   ** initialize those elements that are constant for every row.
118920   */
118921   if( pCsr->aMatchinfo==0 ){
118922     int nMatchinfo = 0;           /* Number of u32 elements in match-info */
118923     int nArg;                     /* Bytes in zArg */
118924     int i;                        /* Used to iterate through zArg */
118925
118926     /* Determine the number of phrases in the query */
118927     pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
118928     sInfo.nPhrase = pCsr->nPhrase;
118929
118930     /* Determine the number of integers in the buffer returned by this call. */
118931     for(i=0; zArg[i]; i++){
118932       nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
118933     }
118934
118935     /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
118936     nArg = (int)strlen(zArg);
118937     pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
118938     if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
118939
118940     pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
118941     pCsr->nMatchinfo = nMatchinfo;
118942     memcpy(pCsr->zMatchinfo, zArg, nArg+1);
118943     memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
118944     pCsr->isMatchinfoNeeded = 1;
118945     bGlobal = 1;
118946   }
118947
118948   sInfo.aMatchinfo = pCsr->aMatchinfo;
118949   sInfo.nPhrase = pCsr->nPhrase;
118950   if( pCsr->isMatchinfoNeeded ){
118951     rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
118952     pCsr->isMatchinfoNeeded = 0;
118953   }
118954
118955   return rc;
118956 }
118957
118958 /*
118959 ** Implementation of snippet() function.
118960 */
118961 SQLITE_PRIVATE void sqlite3Fts3Snippet(
118962   sqlite3_context *pCtx,          /* SQLite function call context */
118963   Fts3Cursor *pCsr,               /* Cursor object */
118964   const char *zStart,             /* Snippet start text - "<b>" */
118965   const char *zEnd,               /* Snippet end text - "</b>" */
118966   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
118967   int iCol,                       /* Extract snippet from this column */
118968   int nToken                      /* Approximate number of tokens in snippet */
118969 ){
118970   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
118971   int rc = SQLITE_OK;
118972   int i;
118973   StrBuffer res = {0, 0, 0};
118974
118975   /* The returned text includes up to four fragments of text extracted from
118976   ** the data in the current row. The first iteration of the for(...) loop
118977   ** below attempts to locate a single fragment of text nToken tokens in 
118978   ** size that contains at least one instance of all phrases in the query
118979   ** expression that appear in the current row. If such a fragment of text
118980   ** cannot be found, the second iteration of the loop attempts to locate
118981   ** a pair of fragments, and so on.
118982   */
118983   int nSnippet = 0;               /* Number of fragments in this snippet */
118984   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
118985   int nFToken = -1;               /* Number of tokens in each fragment */
118986
118987   if( !pCsr->pExpr ){
118988     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
118989     return;
118990   }
118991
118992   for(nSnippet=1; 1; nSnippet++){
118993
118994     int iSnip;                    /* Loop counter 0..nSnippet-1 */
118995     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
118996     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
118997
118998     if( nToken>=0 ){
118999       nFToken = (nToken+nSnippet-1) / nSnippet;
119000     }else{
119001       nFToken = -1 * nToken;
119002     }
119003
119004     for(iSnip=0; iSnip<nSnippet; iSnip++){
119005       int iBestScore = -1;        /* Best score of columns checked so far */
119006       int iRead;                  /* Used to iterate through columns */
119007       SnippetFragment *pFragment = &aSnippet[iSnip];
119008
119009       memset(pFragment, 0, sizeof(*pFragment));
119010
119011       /* Loop through all columns of the table being considered for snippets.
119012       ** If the iCol argument to this function was negative, this means all
119013       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
119014       */
119015       for(iRead=0; iRead<pTab->nColumn; iRead++){
119016         SnippetFragment sF = {0, 0, 0, 0};
119017         int iS;
119018         if( iCol>=0 && iRead!=iCol ) continue;
119019
119020         /* Find the best snippet of nFToken tokens in column iRead. */
119021         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
119022         if( rc!=SQLITE_OK ){
119023           goto snippet_out;
119024         }
119025         if( iS>iBestScore ){
119026           *pFragment = sF;
119027           iBestScore = iS;
119028         }
119029       }
119030
119031       mCovered |= pFragment->covered;
119032     }
119033
119034     /* If all query phrases seen by fts3BestSnippet() are present in at least
119035     ** one of the nSnippet snippet fragments, break out of the loop.
119036     */
119037     assert( (mCovered&mSeen)==mCovered );
119038     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
119039   }
119040
119041   assert( nFToken>0 );
119042
119043   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
119044     rc = fts3SnippetText(pCsr, &aSnippet[i], 
119045         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
119046     );
119047   }
119048
119049  snippet_out:
119050   sqlite3Fts3SegmentsClose(pTab);
119051   if( rc!=SQLITE_OK ){
119052     sqlite3_result_error_code(pCtx, rc);
119053     sqlite3_free(res.z);
119054   }else{
119055     sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
119056   }
119057 }
119058
119059
119060 typedef struct TermOffset TermOffset;
119061 typedef struct TermOffsetCtx TermOffsetCtx;
119062
119063 struct TermOffset {
119064   char *pList;                    /* Position-list */
119065   int iPos;                       /* Position just read from pList */
119066   int iOff;                       /* Offset of this term from read positions */
119067 };
119068
119069 struct TermOffsetCtx {
119070   int iCol;                       /* Column of table to populate aTerm for */
119071   int iTerm;
119072   sqlite3_int64 iDocid;
119073   TermOffset *aTerm;
119074 };
119075
119076 /*
119077 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
119078 */
119079 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
119080   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
119081   int nTerm;                      /* Number of tokens in phrase */
119082   int iTerm;                      /* For looping through nTerm phrase terms */
119083   char *pList;                    /* Pointer to position list for phrase */
119084   int iPos = 0;                   /* First position in position-list */
119085
119086   UNUSED_PARAMETER(iPhrase);
119087   pList = sqlite3Fts3FindPositions(pExpr, p->iDocid, p->iCol);
119088   nTerm = pExpr->pPhrase->nToken;
119089   if( pList ){
119090     fts3GetDeltaPosition(&pList, &iPos);
119091     assert( iPos>=0 );
119092   }
119093
119094   for(iTerm=0; iTerm<nTerm; iTerm++){
119095     TermOffset *pT = &p->aTerm[p->iTerm++];
119096     pT->iOff = nTerm-iTerm-1;
119097     pT->pList = pList;
119098     pT->iPos = iPos;
119099   }
119100
119101   return SQLITE_OK;
119102 }
119103
119104 /*
119105 ** Implementation of offsets() function.
119106 */
119107 SQLITE_PRIVATE void sqlite3Fts3Offsets(
119108   sqlite3_context *pCtx,          /* SQLite function call context */
119109   Fts3Cursor *pCsr                /* Cursor object */
119110 ){
119111   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
119112   sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
119113   const char *ZDUMMY;             /* Dummy argument used with xNext() */
119114   int NDUMMY;                     /* Dummy argument used with xNext() */
119115   int rc;                         /* Return Code */
119116   int nToken;                     /* Number of tokens in query */
119117   int iCol;                       /* Column currently being processed */
119118   StrBuffer res = {0, 0, 0};      /* Result string */
119119   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
119120
119121   if( !pCsr->pExpr ){
119122     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
119123     return;
119124   }
119125
119126   memset(&sCtx, 0, sizeof(sCtx));
119127   assert( pCsr->isRequireSeek==0 );
119128
119129   /* Count the number of terms in the query */
119130   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
119131   if( rc!=SQLITE_OK ) goto offsets_out;
119132
119133   /* Allocate the array of TermOffset iterators. */
119134   sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
119135   if( 0==sCtx.aTerm ){
119136     rc = SQLITE_NOMEM;
119137     goto offsets_out;
119138   }
119139   sCtx.iDocid = pCsr->iPrevId;
119140
119141   /* Loop through the table columns, appending offset information to 
119142   ** string-buffer res for each column.
119143   */
119144   for(iCol=0; iCol<pTab->nColumn; iCol++){
119145     sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
119146     int iStart;
119147     int iEnd;
119148     int iCurrent;
119149     const char *zDoc;
119150     int nDoc;
119151
119152     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is 
119153     ** no way that this operation can fail, so the return code from
119154     ** fts3ExprIterate() can be discarded.
119155     */
119156     sCtx.iCol = iCol;
119157     sCtx.iTerm = 0;
119158     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
119159
119160     /* Retreive the text stored in column iCol. If an SQL NULL is stored 
119161     ** in column iCol, jump immediately to the next iteration of the loop.
119162     ** If an OOM occurs while retrieving the data (this can happen if SQLite
119163     ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM 
119164     ** to the caller. 
119165     */
119166     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
119167     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
119168     if( zDoc==0 ){
119169       if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
119170         continue;
119171       }
119172       rc = SQLITE_NOMEM;
119173       goto offsets_out;
119174     }
119175
119176     /* Initialize a tokenizer iterator to iterate through column iCol. */
119177     rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
119178     if( rc!=SQLITE_OK ) goto offsets_out;
119179     pC->pTokenizer = pTab->pTokenizer;
119180
119181     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
119182     while( rc==SQLITE_OK ){
119183       int i;                      /* Used to loop through terms */
119184       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
119185       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
119186
119187       for(i=0; i<nToken; i++){
119188         TermOffset *pT = &sCtx.aTerm[i];
119189         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
119190           iMinPos = pT->iPos-pT->iOff;
119191           pTerm = pT;
119192         }
119193       }
119194
119195       if( !pTerm ){
119196         /* All offsets for this column have been gathered. */
119197         break;
119198       }else{
119199         assert( iCurrent<=iMinPos );
119200         if( 0==(0xFE&*pTerm->pList) ){
119201           pTerm->pList = 0;
119202         }else{
119203           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
119204         }
119205         while( rc==SQLITE_OK && iCurrent<iMinPos ){
119206           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
119207         }
119208         if( rc==SQLITE_OK ){
119209           char aBuffer[64];
119210           sqlite3_snprintf(sizeof(aBuffer), aBuffer, 
119211               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
119212           );
119213           rc = fts3StringAppend(&res, aBuffer, -1);
119214         }else if( rc==SQLITE_DONE ){
119215           rc = SQLITE_CORRUPT;
119216         }
119217       }
119218     }
119219     if( rc==SQLITE_DONE ){
119220       rc = SQLITE_OK;
119221     }
119222
119223     pMod->xClose(pC);
119224     if( rc!=SQLITE_OK ) goto offsets_out;
119225   }
119226
119227  offsets_out:
119228   sqlite3_free(sCtx.aTerm);
119229   assert( rc!=SQLITE_DONE );
119230   sqlite3Fts3SegmentsClose(pTab);
119231   if( rc!=SQLITE_OK ){
119232     sqlite3_result_error_code(pCtx,  rc);
119233     sqlite3_free(res.z);
119234   }else{
119235     sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
119236   }
119237   return;
119238 }
119239
119240 /*
119241 ** Implementation of matchinfo() function.
119242 */
119243 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
119244   sqlite3_context *pContext,      /* Function call context */
119245   Fts3Cursor *pCsr,               /* FTS3 table cursor */
119246   const char *zArg                /* Second arg to matchinfo() function */
119247 ){
119248   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
119249   int rc;
119250   int i;
119251   const char *zFormat;
119252
119253   if( zArg ){
119254     for(i=0; zArg[i]; i++){
119255       char *zErr = 0;
119256       if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
119257         sqlite3_result_error(pContext, zErr, -1);
119258         sqlite3_free(zErr);
119259         return;
119260       }
119261     }
119262     zFormat = zArg;
119263   }else{
119264     zFormat = FTS3_MATCHINFO_DEFAULT;
119265   }
119266
119267   if( !pCsr->pExpr ){
119268     sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
119269     return;
119270   }
119271
119272   /* Retrieve matchinfo() data. */
119273   rc = fts3GetMatchinfo(pCsr, zFormat);
119274   sqlite3Fts3SegmentsClose(pTab);
119275
119276   if( rc!=SQLITE_OK ){
119277     sqlite3_result_error_code(pContext, rc);
119278   }else{
119279     int n = pCsr->nMatchinfo * sizeof(u32);
119280     sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
119281   }
119282 }
119283
119284 #endif
119285
119286 /************** End of fts3_snippet.c ****************************************/
119287 /************** Begin file rtree.c *******************************************/
119288 /*
119289 ** 2001 September 15
119290 **
119291 ** The author disclaims copyright to this source code.  In place of
119292 ** a legal notice, here is a blessing:
119293 **
119294 **    May you do good and not evil.
119295 **    May you find forgiveness for yourself and forgive others.
119296 **    May you share freely, never taking more than you give.
119297 **
119298 *************************************************************************
119299 ** This file contains code for implementations of the r-tree and r*-tree
119300 ** algorithms packaged as an SQLite virtual table module.
119301 */
119302
119303 /*
119304 ** Database Format of R-Tree Tables
119305 ** --------------------------------
119306 **
119307 ** The data structure for a single virtual r-tree table is stored in three 
119308 ** native SQLite tables declared as follows. In each case, the '%' character
119309 ** in the table name is replaced with the user-supplied name of the r-tree
119310 ** table.
119311 **
119312 **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
119313 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
119314 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
119315 **
119316 ** The data for each node of the r-tree structure is stored in the %_node
119317 ** table. For each node that is not the root node of the r-tree, there is
119318 ** an entry in the %_parent table associating the node with its parent.
119319 ** And for each row of data in the table, there is an entry in the %_rowid
119320 ** table that maps from the entries rowid to the id of the node that it
119321 ** is stored on.
119322 **
119323 ** The root node of an r-tree always exists, even if the r-tree table is
119324 ** empty. The nodeno of the root node is always 1. All other nodes in the
119325 ** table must be the same size as the root node. The content of each node
119326 ** is formatted as follows:
119327 **
119328 **   1. If the node is the root node (node 1), then the first 2 bytes
119329 **      of the node contain the tree depth as a big-endian integer.
119330 **      For non-root nodes, the first 2 bytes are left unused.
119331 **
119332 **   2. The next 2 bytes contain the number of entries currently 
119333 **      stored in the node.
119334 **
119335 **   3. The remainder of the node contains the node entries. Each entry
119336 **      consists of a single 8-byte integer followed by an even number
119337 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
119338 **      of a record. For internal nodes it is the node number of a
119339 **      child page.
119340 */
119341
119342 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
119343
119344 /*
119345 ** This file contains an implementation of a couple of different variants
119346 ** of the r-tree algorithm. See the README file for further details. The 
119347 ** same data-structure is used for all, but the algorithms for insert and
119348 ** delete operations vary. The variants used are selected at compile time 
119349 ** by defining the following symbols:
119350 */
119351
119352 /* Either, both or none of the following may be set to activate 
119353 ** r*tree variant algorithms.
119354 */
119355 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
119356 #define VARIANT_RSTARTREE_REINSERT      1
119357
119358 /* 
119359 ** Exactly one of the following must be set to 1.
119360 */
119361 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
119362 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
119363 #define VARIANT_RSTARTREE_SPLIT         1
119364
119365 #define VARIANT_GUTTMAN_SPLIT \
119366         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
119367
119368 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
119369   #define PickNext QuadraticPickNext
119370   #define PickSeeds QuadraticPickSeeds
119371   #define AssignCells splitNodeGuttman
119372 #endif
119373 #if VARIANT_GUTTMAN_LINEAR_SPLIT
119374   #define PickNext LinearPickNext
119375   #define PickSeeds LinearPickSeeds
119376   #define AssignCells splitNodeGuttman
119377 #endif
119378 #if VARIANT_RSTARTREE_SPLIT
119379   #define AssignCells splitNodeStartree
119380 #endif
119381
119382 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
119383 # define NDEBUG 1
119384 #endif
119385
119386 #ifndef SQLITE_CORE
119387   SQLITE_EXTENSION_INIT1
119388 #else
119389 #endif
119390
119391
119392 #ifndef SQLITE_AMALGAMATION
119393 #include "sqlite3rtree.h"
119394 typedef sqlite3_int64 i64;
119395 typedef unsigned char u8;
119396 typedef unsigned int u32;
119397 #endif
119398
119399 /*  The following macro is used to suppress compiler warnings.
119400 */
119401 #ifndef UNUSED_PARAMETER
119402 # define UNUSED_PARAMETER(x) (void)(x)
119403 #endif
119404
119405 typedef struct Rtree Rtree;
119406 typedef struct RtreeCursor RtreeCursor;
119407 typedef struct RtreeNode RtreeNode;
119408 typedef struct RtreeCell RtreeCell;
119409 typedef struct RtreeConstraint RtreeConstraint;
119410 typedef struct RtreeMatchArg RtreeMatchArg;
119411 typedef struct RtreeGeomCallback RtreeGeomCallback;
119412 typedef union RtreeCoord RtreeCoord;
119413
119414 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
119415 #define RTREE_MAX_DIMENSIONS 5
119416
119417 /* Size of hash table Rtree.aHash. This hash table is not expected to
119418 ** ever contain very many entries, so a fixed number of buckets is 
119419 ** used.
119420 */
119421 #define HASHSIZE 128
119422
119423 /* 
119424 ** An rtree virtual-table object.
119425 */
119426 struct Rtree {
119427   sqlite3_vtab base;
119428   sqlite3 *db;                /* Host database connection */
119429   int iNodeSize;              /* Size in bytes of each node in the node table */
119430   int nDim;                   /* Number of dimensions */
119431   int nBytesPerCell;          /* Bytes consumed per cell */
119432   int iDepth;                 /* Current depth of the r-tree structure */
119433   char *zDb;                  /* Name of database containing r-tree table */
119434   char *zName;                /* Name of r-tree table */ 
119435   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
119436   int nBusy;                  /* Current number of users of this structure */
119437
119438   /* List of nodes removed during a CondenseTree operation. List is
119439   ** linked together via the pointer normally used for hash chains -
119440   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
119441   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
119442   */
119443   RtreeNode *pDeleted;
119444   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
119445
119446   /* Statements to read/write/delete a record from xxx_node */
119447   sqlite3_stmt *pReadNode;
119448   sqlite3_stmt *pWriteNode;
119449   sqlite3_stmt *pDeleteNode;
119450
119451   /* Statements to read/write/delete a record from xxx_rowid */
119452   sqlite3_stmt *pReadRowid;
119453   sqlite3_stmt *pWriteRowid;
119454   sqlite3_stmt *pDeleteRowid;
119455
119456   /* Statements to read/write/delete a record from xxx_parent */
119457   sqlite3_stmt *pReadParent;
119458   sqlite3_stmt *pWriteParent;
119459   sqlite3_stmt *pDeleteParent;
119460
119461   int eCoordType;
119462 };
119463
119464 /* Possible values for eCoordType: */
119465 #define RTREE_COORD_REAL32 0
119466 #define RTREE_COORD_INT32  1
119467
119468 /*
119469 ** The minimum number of cells allowed for a node is a third of the 
119470 ** maximum. In Gutman's notation:
119471 **
119472 **     m = M/3
119473 **
119474 ** If an R*-tree "Reinsert" operation is required, the same number of
119475 ** cells are removed from the overfull node and reinserted into the tree.
119476 */
119477 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
119478 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
119479 #define RTREE_MAXCELLS 51
119480
119481 /*
119482 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
119483 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
119484 ** Therefore all non-root nodes must contain at least 3 entries. Since 
119485 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
119486 ** 40 or less.
119487 */
119488 #define RTREE_MAX_DEPTH 40
119489
119490 /* 
119491 ** An rtree cursor object.
119492 */
119493 struct RtreeCursor {
119494   sqlite3_vtab_cursor base;
119495   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
119496   int iCell;                        /* Index of current cell in pNode */
119497   int iStrategy;                    /* Copy of idxNum search parameter */
119498   int nConstraint;                  /* Number of entries in aConstraint */
119499   RtreeConstraint *aConstraint;     /* Search constraints. */
119500 };
119501
119502 union RtreeCoord {
119503   float f;
119504   int i;
119505 };
119506
119507 /*
119508 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
119509 ** formatted as a double. This macro assumes that local variable pRtree points
119510 ** to the Rtree structure associated with the RtreeCoord.
119511 */
119512 #define DCOORD(coord) (                           \
119513   (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
119514     ((double)coord.f) :                           \
119515     ((double)coord.i)                             \
119516 )
119517
119518 /*
119519 ** A search constraint.
119520 */
119521 struct RtreeConstraint {
119522   int iCoord;                     /* Index of constrained coordinate */
119523   int op;                         /* Constraining operation */
119524   double rValue;                  /* Constraint value. */
119525   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
119526   sqlite3_rtree_geometry *pGeom;  /* Constraint callback argument for a MATCH */
119527 };
119528
119529 /* Possible values for RtreeConstraint.op */
119530 #define RTREE_EQ    0x41
119531 #define RTREE_LE    0x42
119532 #define RTREE_LT    0x43
119533 #define RTREE_GE    0x44
119534 #define RTREE_GT    0x45
119535 #define RTREE_MATCH 0x46
119536
119537 /* 
119538 ** An rtree structure node.
119539 */
119540 struct RtreeNode {
119541   RtreeNode *pParent;               /* Parent node */
119542   i64 iNode;
119543   int nRef;
119544   int isDirty;
119545   u8 *zData;
119546   RtreeNode *pNext;                 /* Next node in this hash chain */
119547 };
119548 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
119549
119550 /* 
119551 ** Structure to store a deserialized rtree record.
119552 */
119553 struct RtreeCell {
119554   i64 iRowid;
119555   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
119556 };
119557
119558
119559 /*
119560 ** Value for the first field of every RtreeMatchArg object. The MATCH
119561 ** operator tests that the first field of a blob operand matches this
119562 ** value to avoid operating on invalid blobs (which could cause a segfault).
119563 */
119564 #define RTREE_GEOMETRY_MAGIC 0x891245AB
119565
119566 /*
119567 ** An instance of this structure must be supplied as a blob argument to
119568 ** the right-hand-side of an SQL MATCH operator used to constrain an
119569 ** r-tree query.
119570 */
119571 struct RtreeMatchArg {
119572   u32 magic;                      /* Always RTREE_GEOMETRY_MAGIC */
119573   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
119574   void *pContext;
119575   int nParam;
119576   double aParam[1];
119577 };
119578
119579 /*
119580 ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
119581 ** a single instance of the following structure is allocated. It is used
119582 ** as the context for the user-function created by by s_r_g_c(). The object
119583 ** is eventually deleted by the destructor mechanism provided by
119584 ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
119585 ** the geometry callback function).
119586 */
119587 struct RtreeGeomCallback {
119588   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
119589   void *pContext;
119590 };
119591
119592 #ifndef MAX
119593 # define MAX(x,y) ((x) < (y) ? (y) : (x))
119594 #endif
119595 #ifndef MIN
119596 # define MIN(x,y) ((x) > (y) ? (y) : (x))
119597 #endif
119598
119599 /*
119600 ** Functions to deserialize a 16 bit integer, 32 bit real number and
119601 ** 64 bit integer. The deserialized value is returned.
119602 */
119603 static int readInt16(u8 *p){
119604   return (p[0]<<8) + p[1];
119605 }
119606 static void readCoord(u8 *p, RtreeCoord *pCoord){
119607   u32 i = (
119608     (((u32)p[0]) << 24) + 
119609     (((u32)p[1]) << 16) + 
119610     (((u32)p[2]) <<  8) + 
119611     (((u32)p[3]) <<  0)
119612   );
119613   *(u32 *)pCoord = i;
119614 }
119615 static i64 readInt64(u8 *p){
119616   return (
119617     (((i64)p[0]) << 56) + 
119618     (((i64)p[1]) << 48) + 
119619     (((i64)p[2]) << 40) + 
119620     (((i64)p[3]) << 32) + 
119621     (((i64)p[4]) << 24) + 
119622     (((i64)p[5]) << 16) + 
119623     (((i64)p[6]) <<  8) + 
119624     (((i64)p[7]) <<  0)
119625   );
119626 }
119627
119628 /*
119629 ** Functions to serialize a 16 bit integer, 32 bit real number and
119630 ** 64 bit integer. The value returned is the number of bytes written
119631 ** to the argument buffer (always 2, 4 and 8 respectively).
119632 */
119633 static int writeInt16(u8 *p, int i){
119634   p[0] = (i>> 8)&0xFF;
119635   p[1] = (i>> 0)&0xFF;
119636   return 2;
119637 }
119638 static int writeCoord(u8 *p, RtreeCoord *pCoord){
119639   u32 i;
119640   assert( sizeof(RtreeCoord)==4 );
119641   assert( sizeof(u32)==4 );
119642   i = *(u32 *)pCoord;
119643   p[0] = (i>>24)&0xFF;
119644   p[1] = (i>>16)&0xFF;
119645   p[2] = (i>> 8)&0xFF;
119646   p[3] = (i>> 0)&0xFF;
119647   return 4;
119648 }
119649 static int writeInt64(u8 *p, i64 i){
119650   p[0] = (i>>56)&0xFF;
119651   p[1] = (i>>48)&0xFF;
119652   p[2] = (i>>40)&0xFF;
119653   p[3] = (i>>32)&0xFF;
119654   p[4] = (i>>24)&0xFF;
119655   p[5] = (i>>16)&0xFF;
119656   p[6] = (i>> 8)&0xFF;
119657   p[7] = (i>> 0)&0xFF;
119658   return 8;
119659 }
119660
119661 /*
119662 ** Increment the reference count of node p.
119663 */
119664 static void nodeReference(RtreeNode *p){
119665   if( p ){
119666     p->nRef++;
119667   }
119668 }
119669
119670 /*
119671 ** Clear the content of node p (set all bytes to 0x00).
119672 */
119673 static void nodeZero(Rtree *pRtree, RtreeNode *p){
119674   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
119675   p->isDirty = 1;
119676 }
119677
119678 /*
119679 ** Given a node number iNode, return the corresponding key to use
119680 ** in the Rtree.aHash table.
119681 */
119682 static int nodeHash(i64 iNode){
119683   return (
119684     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ 
119685     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
119686   ) % HASHSIZE;
119687 }
119688
119689 /*
119690 ** Search the node hash table for node iNode. If found, return a pointer
119691 ** to it. Otherwise, return 0.
119692 */
119693 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
119694   RtreeNode *p;
119695   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
119696   return p;
119697 }
119698
119699 /*
119700 ** Add node pNode to the node hash table.
119701 */
119702 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
119703   int iHash;
119704   assert( pNode->pNext==0 );
119705   iHash = nodeHash(pNode->iNode);
119706   pNode->pNext = pRtree->aHash[iHash];
119707   pRtree->aHash[iHash] = pNode;
119708 }
119709
119710 /*
119711 ** Remove node pNode from the node hash table.
119712 */
119713 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
119714   RtreeNode **pp;
119715   if( pNode->iNode!=0 ){
119716     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
119717     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
119718     *pp = pNode->pNext;
119719     pNode->pNext = 0;
119720   }
119721 }
119722
119723 /*
119724 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
119725 ** indicating that node has not yet been assigned a node number. It is
119726 ** assigned a node number when nodeWrite() is called to write the
119727 ** node contents out to the database.
119728 */
119729 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
119730   RtreeNode *pNode;
119731   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
119732   if( pNode ){
119733     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
119734     pNode->zData = (u8 *)&pNode[1];
119735     pNode->nRef = 1;
119736     pNode->pParent = pParent;
119737     pNode->isDirty = 1;
119738     nodeReference(pParent);
119739   }
119740   return pNode;
119741 }
119742
119743 /*
119744 ** Obtain a reference to an r-tree node.
119745 */
119746 static int
119747 nodeAcquire(
119748   Rtree *pRtree,             /* R-tree structure */
119749   i64 iNode,                 /* Node number to load */
119750   RtreeNode *pParent,        /* Either the parent node or NULL */
119751   RtreeNode **ppNode         /* OUT: Acquired node */
119752 ){
119753   int rc;
119754   int rc2 = SQLITE_OK;
119755   RtreeNode *pNode;
119756
119757   /* Check if the requested node is already in the hash table. If so,
119758   ** increase its reference count and return it.
119759   */
119760   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
119761     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
119762     if( pParent && !pNode->pParent ){
119763       nodeReference(pParent);
119764       pNode->pParent = pParent;
119765     }
119766     pNode->nRef++;
119767     *ppNode = pNode;
119768     return SQLITE_OK;
119769   }
119770
119771   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
119772   rc = sqlite3_step(pRtree->pReadNode);
119773   if( rc==SQLITE_ROW ){
119774     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
119775     if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
119776       pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
119777       if( !pNode ){
119778         rc2 = SQLITE_NOMEM;
119779       }else{
119780         pNode->pParent = pParent;
119781         pNode->zData = (u8 *)&pNode[1];
119782         pNode->nRef = 1;
119783         pNode->iNode = iNode;
119784         pNode->isDirty = 0;
119785         pNode->pNext = 0;
119786         memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
119787         nodeReference(pParent);
119788       }
119789     }
119790   }
119791   rc = sqlite3_reset(pRtree->pReadNode);
119792   if( rc==SQLITE_OK ) rc = rc2;
119793
119794   /* If the root node was just loaded, set pRtree->iDepth to the height
119795   ** of the r-tree structure. A height of zero means all data is stored on
119796   ** the root node. A height of one means the children of the root node
119797   ** are the leaves, and so on. If the depth as specified on the root node
119798   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
119799   */
119800   if( pNode && iNode==1 ){
119801     pRtree->iDepth = readInt16(pNode->zData);
119802     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
119803       rc = SQLITE_CORRUPT;
119804     }
119805   }
119806
119807   /* If no error has occurred so far, check if the "number of entries"
119808   ** field on the node is too large. If so, set the return code to 
119809   ** SQLITE_CORRUPT.
119810   */
119811   if( pNode && rc==SQLITE_OK ){
119812     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
119813       rc = SQLITE_CORRUPT;
119814     }
119815   }
119816
119817   if( rc==SQLITE_OK ){
119818     if( pNode!=0 ){
119819       nodeHashInsert(pRtree, pNode);
119820     }else{
119821       rc = SQLITE_CORRUPT;
119822     }
119823     *ppNode = pNode;
119824   }else{
119825     sqlite3_free(pNode);
119826     *ppNode = 0;
119827   }
119828
119829   return rc;
119830 }
119831
119832 /*
119833 ** Overwrite cell iCell of node pNode with the contents of pCell.
119834 */
119835 static void nodeOverwriteCell(
119836   Rtree *pRtree, 
119837   RtreeNode *pNode,  
119838   RtreeCell *pCell, 
119839   int iCell
119840 ){
119841   int ii;
119842   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
119843   p += writeInt64(p, pCell->iRowid);
119844   for(ii=0; ii<(pRtree->nDim*2); ii++){
119845     p += writeCoord(p, &pCell->aCoord[ii]);
119846   }
119847   pNode->isDirty = 1;
119848 }
119849
119850 /*
119851 ** Remove cell the cell with index iCell from node pNode.
119852 */
119853 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
119854   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
119855   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
119856   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
119857   memmove(pDst, pSrc, nByte);
119858   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
119859   pNode->isDirty = 1;
119860 }
119861
119862 /*
119863 ** Insert the contents of cell pCell into node pNode. If the insert
119864 ** is successful, return SQLITE_OK.
119865 **
119866 ** If there is not enough free space in pNode, return SQLITE_FULL.
119867 */
119868 static int
119869 nodeInsertCell(
119870   Rtree *pRtree, 
119871   RtreeNode *pNode, 
119872   RtreeCell *pCell 
119873 ){
119874   int nCell;                    /* Current number of cells in pNode */
119875   int nMaxCell;                 /* Maximum number of cells for pNode */
119876
119877   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
119878   nCell = NCELL(pNode);
119879
119880   assert( nCell<=nMaxCell );
119881   if( nCell<nMaxCell ){
119882     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
119883     writeInt16(&pNode->zData[2], nCell+1);
119884     pNode->isDirty = 1;
119885   }
119886
119887   return (nCell==nMaxCell);
119888 }
119889
119890 /*
119891 ** If the node is dirty, write it out to the database.
119892 */
119893 static int
119894 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
119895   int rc = SQLITE_OK;
119896   if( pNode->isDirty ){
119897     sqlite3_stmt *p = pRtree->pWriteNode;
119898     if( pNode->iNode ){
119899       sqlite3_bind_int64(p, 1, pNode->iNode);
119900     }else{
119901       sqlite3_bind_null(p, 1);
119902     }
119903     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
119904     sqlite3_step(p);
119905     pNode->isDirty = 0;
119906     rc = sqlite3_reset(p);
119907     if( pNode->iNode==0 && rc==SQLITE_OK ){
119908       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
119909       nodeHashInsert(pRtree, pNode);
119910     }
119911   }
119912   return rc;
119913 }
119914
119915 /*
119916 ** Release a reference to a node. If the node is dirty and the reference
119917 ** count drops to zero, the node data is written to the database.
119918 */
119919 static int
119920 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
119921   int rc = SQLITE_OK;
119922   if( pNode ){
119923     assert( pNode->nRef>0 );
119924     pNode->nRef--;
119925     if( pNode->nRef==0 ){
119926       if( pNode->iNode==1 ){
119927         pRtree->iDepth = -1;
119928       }
119929       if( pNode->pParent ){
119930         rc = nodeRelease(pRtree, pNode->pParent);
119931       }
119932       if( rc==SQLITE_OK ){
119933         rc = nodeWrite(pRtree, pNode);
119934       }
119935       nodeHashDelete(pRtree, pNode);
119936       sqlite3_free(pNode);
119937     }
119938   }
119939   return rc;
119940 }
119941
119942 /*
119943 ** Return the 64-bit integer value associated with cell iCell of
119944 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
119945 ** an internal node, then the 64-bit integer is a child page number.
119946 */
119947 static i64 nodeGetRowid(
119948   Rtree *pRtree, 
119949   RtreeNode *pNode, 
119950   int iCell
119951 ){
119952   assert( iCell<NCELL(pNode) );
119953   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
119954 }
119955
119956 /*
119957 ** Return coordinate iCoord from cell iCell in node pNode.
119958 */
119959 static void nodeGetCoord(
119960   Rtree *pRtree, 
119961   RtreeNode *pNode, 
119962   int iCell,
119963   int iCoord,
119964   RtreeCoord *pCoord           /* Space to write result to */
119965 ){
119966   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
119967 }
119968
119969 /*
119970 ** Deserialize cell iCell of node pNode. Populate the structure pointed
119971 ** to by pCell with the results.
119972 */
119973 static void nodeGetCell(
119974   Rtree *pRtree, 
119975   RtreeNode *pNode, 
119976   int iCell,
119977   RtreeCell *pCell
119978 ){
119979   int ii;
119980   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
119981   for(ii=0; ii<pRtree->nDim*2; ii++){
119982     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
119983   }
119984 }
119985
119986
119987 /* Forward declaration for the function that does the work of
119988 ** the virtual table module xCreate() and xConnect() methods.
119989 */
119990 static int rtreeInit(
119991   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
119992 );
119993
119994 /* 
119995 ** Rtree virtual table module xCreate method.
119996 */
119997 static int rtreeCreate(
119998   sqlite3 *db,
119999   void *pAux,
120000   int argc, const char *const*argv,
120001   sqlite3_vtab **ppVtab,
120002   char **pzErr
120003 ){
120004   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
120005 }
120006
120007 /* 
120008 ** Rtree virtual table module xConnect method.
120009 */
120010 static int rtreeConnect(
120011   sqlite3 *db,
120012   void *pAux,
120013   int argc, const char *const*argv,
120014   sqlite3_vtab **ppVtab,
120015   char **pzErr
120016 ){
120017   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
120018 }
120019
120020 /*
120021 ** Increment the r-tree reference count.
120022 */
120023 static void rtreeReference(Rtree *pRtree){
120024   pRtree->nBusy++;
120025 }
120026
120027 /*
120028 ** Decrement the r-tree reference count. When the reference count reaches
120029 ** zero the structure is deleted.
120030 */
120031 static void rtreeRelease(Rtree *pRtree){
120032   pRtree->nBusy--;
120033   if( pRtree->nBusy==0 ){
120034     sqlite3_finalize(pRtree->pReadNode);
120035     sqlite3_finalize(pRtree->pWriteNode);
120036     sqlite3_finalize(pRtree->pDeleteNode);
120037     sqlite3_finalize(pRtree->pReadRowid);
120038     sqlite3_finalize(pRtree->pWriteRowid);
120039     sqlite3_finalize(pRtree->pDeleteRowid);
120040     sqlite3_finalize(pRtree->pReadParent);
120041     sqlite3_finalize(pRtree->pWriteParent);
120042     sqlite3_finalize(pRtree->pDeleteParent);
120043     sqlite3_free(pRtree);
120044   }
120045 }
120046
120047 /* 
120048 ** Rtree virtual table module xDisconnect method.
120049 */
120050 static int rtreeDisconnect(sqlite3_vtab *pVtab){
120051   rtreeRelease((Rtree *)pVtab);
120052   return SQLITE_OK;
120053 }
120054
120055 /* 
120056 ** Rtree virtual table module xDestroy method.
120057 */
120058 static int rtreeDestroy(sqlite3_vtab *pVtab){
120059   Rtree *pRtree = (Rtree *)pVtab;
120060   int rc;
120061   char *zCreate = sqlite3_mprintf(
120062     "DROP TABLE '%q'.'%q_node';"
120063     "DROP TABLE '%q'.'%q_rowid';"
120064     "DROP TABLE '%q'.'%q_parent';",
120065     pRtree->zDb, pRtree->zName, 
120066     pRtree->zDb, pRtree->zName,
120067     pRtree->zDb, pRtree->zName
120068   );
120069   if( !zCreate ){
120070     rc = SQLITE_NOMEM;
120071   }else{
120072     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
120073     sqlite3_free(zCreate);
120074   }
120075   if( rc==SQLITE_OK ){
120076     rtreeRelease(pRtree);
120077   }
120078
120079   return rc;
120080 }
120081
120082 /* 
120083 ** Rtree virtual table module xOpen method.
120084 */
120085 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
120086   int rc = SQLITE_NOMEM;
120087   RtreeCursor *pCsr;
120088
120089   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
120090   if( pCsr ){
120091     memset(pCsr, 0, sizeof(RtreeCursor));
120092     pCsr->base.pVtab = pVTab;
120093     rc = SQLITE_OK;
120094   }
120095   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
120096
120097   return rc;
120098 }
120099
120100
120101 /*
120102 ** Free the RtreeCursor.aConstraint[] array and its contents.
120103 */
120104 static void freeCursorConstraints(RtreeCursor *pCsr){
120105   if( pCsr->aConstraint ){
120106     int i;                        /* Used to iterate through constraint array */
120107     for(i=0; i<pCsr->nConstraint; i++){
120108       sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
120109       if( pGeom ){
120110         if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
120111         sqlite3_free(pGeom);
120112       }
120113     }
120114     sqlite3_free(pCsr->aConstraint);
120115     pCsr->aConstraint = 0;
120116   }
120117 }
120118
120119 /* 
120120 ** Rtree virtual table module xClose method.
120121 */
120122 static int rtreeClose(sqlite3_vtab_cursor *cur){
120123   Rtree *pRtree = (Rtree *)(cur->pVtab);
120124   int rc;
120125   RtreeCursor *pCsr = (RtreeCursor *)cur;
120126   freeCursorConstraints(pCsr);
120127   rc = nodeRelease(pRtree, pCsr->pNode);
120128   sqlite3_free(pCsr);
120129   return rc;
120130 }
120131
120132 /*
120133 ** Rtree virtual table module xEof method.
120134 **
120135 ** Return non-zero if the cursor does not currently point to a valid 
120136 ** record (i.e if the scan has finished), or zero otherwise.
120137 */
120138 static int rtreeEof(sqlite3_vtab_cursor *cur){
120139   RtreeCursor *pCsr = (RtreeCursor *)cur;
120140   return (pCsr->pNode==0);
120141 }
120142
120143 /*
120144 ** The r-tree constraint passed as the second argument to this function is
120145 ** guaranteed to be a MATCH constraint.
120146 */
120147 static int testRtreeGeom(
120148   Rtree *pRtree,                  /* R-Tree object */
120149   RtreeConstraint *pConstraint,   /* MATCH constraint to test */
120150   RtreeCell *pCell,               /* Cell to test */
120151   int *pbRes                      /* OUT: Test result */
120152 ){
120153   int i;
120154   double aCoord[RTREE_MAX_DIMENSIONS*2];
120155   int nCoord = pRtree->nDim*2;
120156
120157   assert( pConstraint->op==RTREE_MATCH );
120158   assert( pConstraint->pGeom );
120159
120160   for(i=0; i<nCoord; i++){
120161     aCoord[i] = DCOORD(pCell->aCoord[i]);
120162   }
120163   return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
120164 }
120165
120166 /* 
120167 ** Cursor pCursor currently points to a cell in a non-leaf page.
120168 ** Set *pbEof to true if the sub-tree headed by the cell is filtered
120169 ** (excluded) by the constraints in the pCursor->aConstraint[] 
120170 ** array, or false otherwise.
120171 **
120172 ** Return SQLITE_OK if successful or an SQLite error code if an error
120173 ** occurs within a geometry callback.
120174 */
120175 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
120176   RtreeCell cell;
120177   int ii;
120178   int bRes = 0;
120179   int rc = SQLITE_OK;
120180
120181   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
120182   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
120183     RtreeConstraint *p = &pCursor->aConstraint[ii];
120184     double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
120185     double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
120186
120187     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
120188         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
120189     );
120190
120191     switch( p->op ){
120192       case RTREE_LE: case RTREE_LT: 
120193         bRes = p->rValue<cell_min; 
120194         break;
120195
120196       case RTREE_GE: case RTREE_GT: 
120197         bRes = p->rValue>cell_max; 
120198         break;
120199
120200       case RTREE_EQ:
120201         bRes = (p->rValue>cell_max || p->rValue<cell_min);
120202         break;
120203
120204       default: {
120205         assert( p->op==RTREE_MATCH );
120206         rc = testRtreeGeom(pRtree, p, &cell, &bRes);
120207         bRes = !bRes;
120208         break;
120209       }
120210     }
120211   }
120212
120213   *pbEof = bRes;
120214   return rc;
120215 }
120216
120217 /* 
120218 ** Test if the cell that cursor pCursor currently points to
120219 ** would be filtered (excluded) by the constraints in the 
120220 ** pCursor->aConstraint[] array. If so, set *pbEof to true before
120221 ** returning. If the cell is not filtered (excluded) by the constraints,
120222 ** set pbEof to zero.
120223 **
120224 ** Return SQLITE_OK if successful or an SQLite error code if an error
120225 ** occurs within a geometry callback.
120226 **
120227 ** This function assumes that the cell is part of a leaf node.
120228 */
120229 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
120230   RtreeCell cell;
120231   int ii;
120232   *pbEof = 0;
120233
120234   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
120235   for(ii=0; ii<pCursor->nConstraint; ii++){
120236     RtreeConstraint *p = &pCursor->aConstraint[ii];
120237     double coord = DCOORD(cell.aCoord[p->iCoord]);
120238     int res;
120239     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
120240         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
120241     );
120242     switch( p->op ){
120243       case RTREE_LE: res = (coord<=p->rValue); break;
120244       case RTREE_LT: res = (coord<p->rValue);  break;
120245       case RTREE_GE: res = (coord>=p->rValue); break;
120246       case RTREE_GT: res = (coord>p->rValue);  break;
120247       case RTREE_EQ: res = (coord==p->rValue); break;
120248       default: {
120249         int rc;
120250         assert( p->op==RTREE_MATCH );
120251         rc = testRtreeGeom(pRtree, p, &cell, &res);
120252         if( rc!=SQLITE_OK ){
120253           return rc;
120254         }
120255         break;
120256       }
120257     }
120258
120259     if( !res ){
120260       *pbEof = 1;
120261       return SQLITE_OK;
120262     }
120263   }
120264
120265   return SQLITE_OK;
120266 }
120267
120268 /*
120269 ** Cursor pCursor currently points at a node that heads a sub-tree of
120270 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
120271 ** to point to the left-most cell of the sub-tree that matches the 
120272 ** configured constraints.
120273 */
120274 static int descendToCell(
120275   Rtree *pRtree, 
120276   RtreeCursor *pCursor, 
120277   int iHeight,
120278   int *pEof                 /* OUT: Set to true if cannot descend */
120279 ){
120280   int isEof;
120281   int rc;
120282   int ii;
120283   RtreeNode *pChild;
120284   sqlite3_int64 iRowid;
120285
120286   RtreeNode *pSavedNode = pCursor->pNode;
120287   int iSavedCell = pCursor->iCell;
120288
120289   assert( iHeight>=0 );
120290
120291   if( iHeight==0 ){
120292     rc = testRtreeEntry(pRtree, pCursor, &isEof);
120293   }else{
120294     rc = testRtreeCell(pRtree, pCursor, &isEof);
120295   }
120296   if( rc!=SQLITE_OK || isEof || iHeight==0 ){
120297     goto descend_to_cell_out;
120298   }
120299
120300   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
120301   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
120302   if( rc!=SQLITE_OK ){
120303     goto descend_to_cell_out;
120304   }
120305
120306   nodeRelease(pRtree, pCursor->pNode);
120307   pCursor->pNode = pChild;
120308   isEof = 1;
120309   for(ii=0; isEof && ii<NCELL(pChild); ii++){
120310     pCursor->iCell = ii;
120311     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
120312     if( rc!=SQLITE_OK ){
120313       goto descend_to_cell_out;
120314     }
120315   }
120316
120317   if( isEof ){
120318     assert( pCursor->pNode==pChild );
120319     nodeReference(pSavedNode);
120320     nodeRelease(pRtree, pChild);
120321     pCursor->pNode = pSavedNode;
120322     pCursor->iCell = iSavedCell;
120323   }
120324
120325 descend_to_cell_out:
120326   *pEof = isEof;
120327   return rc;
120328 }
120329
120330 /*
120331 ** One of the cells in node pNode is guaranteed to have a 64-bit 
120332 ** integer value equal to iRowid. Return the index of this cell.
120333 */
120334 static int nodeRowidIndex(
120335   Rtree *pRtree, 
120336   RtreeNode *pNode, 
120337   i64 iRowid,
120338   int *piIndex
120339 ){
120340   int ii;
120341   int nCell = NCELL(pNode);
120342   for(ii=0; ii<nCell; ii++){
120343     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
120344       *piIndex = ii;
120345       return SQLITE_OK;
120346     }
120347   }
120348   return SQLITE_CORRUPT;
120349 }
120350
120351 /*
120352 ** Return the index of the cell containing a pointer to node pNode
120353 ** in its parent. If pNode is the root node, return -1.
120354 */
120355 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
120356   RtreeNode *pParent = pNode->pParent;
120357   if( pParent ){
120358     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
120359   }
120360   *piIndex = -1;
120361   return SQLITE_OK;
120362 }
120363
120364 /* 
120365 ** Rtree virtual table module xNext method.
120366 */
120367 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
120368   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
120369   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
120370   int rc = SQLITE_OK;
120371
120372   /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
120373   ** already at EOF. It is against the rules to call the xNext() method of
120374   ** a cursor that has already reached EOF.
120375   */
120376   assert( pCsr->pNode );
120377
120378   if( pCsr->iStrategy==1 ){
120379     /* This "scan" is a direct lookup by rowid. There is no next entry. */
120380     nodeRelease(pRtree, pCsr->pNode);
120381     pCsr->pNode = 0;
120382   }else{
120383     /* Move to the next entry that matches the configured constraints. */
120384     int iHeight = 0;
120385     while( pCsr->pNode ){
120386       RtreeNode *pNode = pCsr->pNode;
120387       int nCell = NCELL(pNode);
120388       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
120389         int isEof;
120390         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
120391         if( rc!=SQLITE_OK || !isEof ){
120392           return rc;
120393         }
120394       }
120395       pCsr->pNode = pNode->pParent;
120396       rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
120397       if( rc!=SQLITE_OK ){
120398         return rc;
120399       }
120400       nodeReference(pCsr->pNode);
120401       nodeRelease(pRtree, pNode);
120402       iHeight++;
120403     }
120404   }
120405
120406   return rc;
120407 }
120408
120409 /* 
120410 ** Rtree virtual table module xRowid method.
120411 */
120412 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
120413   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
120414   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
120415
120416   assert(pCsr->pNode);
120417   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
120418
120419   return SQLITE_OK;
120420 }
120421
120422 /* 
120423 ** Rtree virtual table module xColumn method.
120424 */
120425 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
120426   Rtree *pRtree = (Rtree *)cur->pVtab;
120427   RtreeCursor *pCsr = (RtreeCursor *)cur;
120428
120429   if( i==0 ){
120430     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
120431     sqlite3_result_int64(ctx, iRowid);
120432   }else{
120433     RtreeCoord c;
120434     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
120435     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
120436       sqlite3_result_double(ctx, c.f);
120437     }else{
120438       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
120439       sqlite3_result_int(ctx, c.i);
120440     }
120441   }
120442
120443   return SQLITE_OK;
120444 }
120445
120446 /* 
120447 ** Use nodeAcquire() to obtain the leaf node containing the record with 
120448 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
120449 ** return SQLITE_OK. If there is no such record in the table, set
120450 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
120451 ** to zero and return an SQLite error code.
120452 */
120453 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
120454   int rc;
120455   *ppLeaf = 0;
120456   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
120457   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
120458     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
120459     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
120460     sqlite3_reset(pRtree->pReadRowid);
120461   }else{
120462     rc = sqlite3_reset(pRtree->pReadRowid);
120463   }
120464   return rc;
120465 }
120466
120467 /*
120468 ** This function is called to configure the RtreeConstraint object passed
120469 ** as the second argument for a MATCH constraint. The value passed as the
120470 ** first argument to this function is the right-hand operand to the MATCH
120471 ** operator.
120472 */
120473 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
120474   RtreeMatchArg *p;
120475   sqlite3_rtree_geometry *pGeom;
120476   int nBlob;
120477
120478   /* Check that value is actually a blob. */
120479   if( !sqlite3_value_type(pValue)==SQLITE_BLOB ) return SQLITE_ERROR;
120480
120481   /* Check that the blob is roughly the right size. */
120482   nBlob = sqlite3_value_bytes(pValue);
120483   if( nBlob<(int)sizeof(RtreeMatchArg) 
120484    || ((nBlob-sizeof(RtreeMatchArg))%sizeof(double))!=0
120485   ){
120486     return SQLITE_ERROR;
120487   }
120488
120489   pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
120490       sizeof(sqlite3_rtree_geometry) + nBlob
120491   );
120492   if( !pGeom ) return SQLITE_NOMEM;
120493   memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
120494   p = (RtreeMatchArg *)&pGeom[1];
120495
120496   memcpy(p, sqlite3_value_blob(pValue), nBlob);
120497   if( p->magic!=RTREE_GEOMETRY_MAGIC 
120498    || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(double))
120499   ){
120500     sqlite3_free(pGeom);
120501     return SQLITE_ERROR;
120502   }
120503
120504   pGeom->pContext = p->pContext;
120505   pGeom->nParam = p->nParam;
120506   pGeom->aParam = p->aParam;
120507
120508   pCons->xGeom = p->xGeom;
120509   pCons->pGeom = pGeom;
120510   return SQLITE_OK;
120511 }
120512
120513 /* 
120514 ** Rtree virtual table module xFilter method.
120515 */
120516 static int rtreeFilter(
120517   sqlite3_vtab_cursor *pVtabCursor, 
120518   int idxNum, const char *idxStr,
120519   int argc, sqlite3_value **argv
120520 ){
120521   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
120522   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
120523
120524   RtreeNode *pRoot = 0;
120525   int ii;
120526   int rc = SQLITE_OK;
120527
120528   rtreeReference(pRtree);
120529
120530   freeCursorConstraints(pCsr);
120531   pCsr->iStrategy = idxNum;
120532
120533   if( idxNum==1 ){
120534     /* Special case - lookup by rowid. */
120535     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
120536     i64 iRowid = sqlite3_value_int64(argv[0]);
120537     rc = findLeafNode(pRtree, iRowid, &pLeaf);
120538     pCsr->pNode = pLeaf; 
120539     if( pLeaf ){
120540       assert( rc==SQLITE_OK );
120541       rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
120542     }
120543   }else{
120544     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
120545     ** with the configured constraints. 
120546     */
120547     if( argc>0 ){
120548       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
120549       pCsr->nConstraint = argc;
120550       if( !pCsr->aConstraint ){
120551         rc = SQLITE_NOMEM;
120552       }else{
120553         memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
120554         assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 );
120555         for(ii=0; ii<argc; ii++){
120556           RtreeConstraint *p = &pCsr->aConstraint[ii];
120557           p->op = idxStr[ii*2];
120558           p->iCoord = idxStr[ii*2+1]-'a';
120559           if( p->op==RTREE_MATCH ){
120560             /* A MATCH operator. The right-hand-side must be a blob that
120561             ** can be cast into an RtreeMatchArg object. One created using
120562             ** an sqlite3_rtree_geometry_callback() SQL user function.
120563             */
120564             rc = deserializeGeometry(argv[ii], p);
120565             if( rc!=SQLITE_OK ){
120566               break;
120567             }
120568           }else{
120569             p->rValue = sqlite3_value_double(argv[ii]);
120570           }
120571         }
120572       }
120573     }
120574   
120575     if( rc==SQLITE_OK ){
120576       pCsr->pNode = 0;
120577       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
120578     }
120579     if( rc==SQLITE_OK ){
120580       int isEof = 1;
120581       int nCell = NCELL(pRoot);
120582       pCsr->pNode = pRoot;
120583       for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
120584         assert( pCsr->pNode==pRoot );
120585         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
120586         if( !isEof ){
120587           break;
120588         }
120589       }
120590       if( rc==SQLITE_OK && isEof ){
120591         assert( pCsr->pNode==pRoot );
120592         nodeRelease(pRtree, pRoot);
120593         pCsr->pNode = 0;
120594       }
120595       assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
120596     }
120597   }
120598
120599   rtreeRelease(pRtree);
120600   return rc;
120601 }
120602
120603 /*
120604 ** Rtree virtual table module xBestIndex method. There are three
120605 ** table scan strategies to choose from (in order from most to 
120606 ** least desirable):
120607 **
120608 **   idxNum     idxStr        Strategy
120609 **   ------------------------------------------------
120610 **     1        Unused        Direct lookup by rowid.
120611 **     2        See below     R-tree query or full-table scan.
120612 **   ------------------------------------------------
120613 **
120614 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
120615 ** 2 is used, idxStr is formatted to contain 2 bytes for each 
120616 ** constraint used. The first two bytes of idxStr correspond to 
120617 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
120618 ** (argvIndex==1) etc.
120619 **
120620 ** The first of each pair of bytes in idxStr identifies the constraint
120621 ** operator as follows:
120622 **
120623 **   Operator    Byte Value
120624 **   ----------------------
120625 **      =        0x41 ('A')
120626 **     <=        0x42 ('B')
120627 **      <        0x43 ('C')
120628 **     >=        0x44 ('D')
120629 **      >        0x45 ('E')
120630 **   MATCH       0x46 ('F')
120631 **   ----------------------
120632 **
120633 ** The second of each pair of bytes identifies the coordinate column
120634 ** to which the constraint applies. The leftmost coordinate column
120635 ** is 'a', the second from the left 'b' etc.
120636 */
120637 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
120638   int rc = SQLITE_OK;
120639   int ii, cCol;
120640
120641   int iIdx = 0;
120642   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
120643   memset(zIdxStr, 0, sizeof(zIdxStr));
120644   UNUSED_PARAMETER(tab);
120645
120646   assert( pIdxInfo->idxStr==0 );
120647   for(ii=0; ii<pIdxInfo->nConstraint; ii++){
120648     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
120649
120650     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
120651       /* We have an equality constraint on the rowid. Use strategy 1. */
120652       int jj;
120653       for(jj=0; jj<ii; jj++){
120654         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
120655         pIdxInfo->aConstraintUsage[jj].omit = 0;
120656       }
120657       pIdxInfo->idxNum = 1;
120658       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
120659       pIdxInfo->aConstraintUsage[jj].omit = 1;
120660
120661       /* This strategy involves a two rowid lookups on an B-Tree structures
120662       ** and then a linear search of an R-Tree node. This should be 
120663       ** considered almost as quick as a direct rowid lookup (for which 
120664       ** sqlite uses an internal cost of 0.0).
120665       */ 
120666       pIdxInfo->estimatedCost = 10.0;
120667       return SQLITE_OK;
120668     }
120669
120670     if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
120671       int j, opmsk;
120672       static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 };
120673       u8 op = 0;
120674       switch( p->op ){
120675         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
120676         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
120677         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
120678         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
120679         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
120680         default:
120681           assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
120682           op = RTREE_MATCH; 
120683           break;
120684       }
120685       assert( op!=0 );
120686
120687       /* Make sure this particular constraint has not been used before.
120688       ** If it has been used before, ignore it.
120689       **
120690       ** A <= or < can be used if there is a prior >= or >.
120691       ** A >= or > can be used if there is a prior < or <=.
120692       ** A <= or < is disqualified if there is a prior <=, <, or ==.
120693       ** A >= or > is disqualified if there is a prior >=, >, or ==.
120694       ** A == is disqualifed if there is any prior constraint.
120695       */
120696       assert( compatible[RTREE_EQ & 7]==0 );
120697       assert( compatible[RTREE_LT & 7]==1 );
120698       assert( compatible[RTREE_LE & 7]==1 );
120699       assert( compatible[RTREE_GT & 7]==2 );
120700       assert( compatible[RTREE_GE & 7]==2 );
120701       cCol = p->iColumn - 1 + 'a';
120702       opmsk = compatible[op & 7];
120703       for(j=0; j<iIdx; j+=2){
120704         if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){
120705           op = 0;
120706           break;
120707         }
120708       }
120709       if( op ){
120710         assert( iIdx<sizeof(zIdxStr)-1 );
120711         zIdxStr[iIdx++] = op;
120712         zIdxStr[iIdx++] = cCol;
120713         pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
120714         pIdxInfo->aConstraintUsage[ii].omit = 1;
120715       }
120716     }
120717   }
120718
120719   pIdxInfo->idxNum = 2;
120720   pIdxInfo->needToFreeIdxStr = 1;
120721   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
120722     return SQLITE_NOMEM;
120723   }
120724   assert( iIdx>=0 );
120725   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
120726   return rc;
120727 }
120728
120729 /*
120730 ** Return the N-dimensional volumn of the cell stored in *p.
120731 */
120732 static float cellArea(Rtree *pRtree, RtreeCell *p){
120733   float area = 1.0;
120734   int ii;
120735   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
120736     area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
120737   }
120738   return area;
120739 }
120740
120741 /*
120742 ** Return the margin length of cell p. The margin length is the sum
120743 ** of the objects size in each dimension.
120744 */
120745 static float cellMargin(Rtree *pRtree, RtreeCell *p){
120746   float margin = 0.0;
120747   int ii;
120748   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
120749     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
120750   }
120751   return margin;
120752 }
120753
120754 /*
120755 ** Store the union of cells p1 and p2 in p1.
120756 */
120757 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
120758   int ii;
120759   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
120760     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
120761       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
120762       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
120763     }
120764   }else{
120765     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
120766       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
120767       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
120768     }
120769   }
120770 }
120771
120772 /*
120773 ** Return true if the area covered by p2 is a subset of the area covered
120774 ** by p1. False otherwise.
120775 */
120776 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
120777   int ii;
120778   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
120779   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
120780     RtreeCoord *a1 = &p1->aCoord[ii];
120781     RtreeCoord *a2 = &p2->aCoord[ii];
120782     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
120783      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
120784     ){
120785       return 0;
120786     }
120787   }
120788   return 1;
120789 }
120790
120791 /*
120792 ** Return the amount cell p would grow by if it were unioned with pCell.
120793 */
120794 static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
120795   float area;
120796   RtreeCell cell;
120797   memcpy(&cell, p, sizeof(RtreeCell));
120798   area = cellArea(pRtree, &cell);
120799   cellUnion(pRtree, &cell, pCell);
120800   return (cellArea(pRtree, &cell)-area);
120801 }
120802
120803 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
120804 static float cellOverlap(
120805   Rtree *pRtree, 
120806   RtreeCell *p, 
120807   RtreeCell *aCell, 
120808   int nCell, 
120809   int iExclude
120810 ){
120811   int ii;
120812   float overlap = 0.0;
120813   for(ii=0; ii<nCell; ii++){
120814 #if VARIANT_RSTARTREE_CHOOSESUBTREE
120815     if( ii!=iExclude )
120816 #else
120817     assert( iExclude==-1 );
120818     UNUSED_PARAMETER(iExclude);
120819 #endif
120820     {
120821       int jj;
120822       float o = 1.0;
120823       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
120824         double x1;
120825         double x2;
120826
120827         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
120828         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
120829
120830         if( x2<x1 ){
120831           o = 0.0;
120832           break;
120833         }else{
120834           o = o * (x2-x1);
120835         }
120836       }
120837       overlap += o;
120838     }
120839   }
120840   return overlap;
120841 }
120842 #endif
120843
120844 #if VARIANT_RSTARTREE_CHOOSESUBTREE
120845 static float cellOverlapEnlargement(
120846   Rtree *pRtree, 
120847   RtreeCell *p, 
120848   RtreeCell *pInsert, 
120849   RtreeCell *aCell, 
120850   int nCell, 
120851   int iExclude
120852 ){
120853   float before;
120854   float after;
120855   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
120856   cellUnion(pRtree, p, pInsert);
120857   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
120858   return after-before;
120859 }
120860 #endif
120861
120862
120863 /*
120864 ** This function implements the ChooseLeaf algorithm from Gutman[84].
120865 ** ChooseSubTree in r*tree terminology.
120866 */
120867 static int ChooseLeaf(
120868   Rtree *pRtree,               /* Rtree table */
120869   RtreeCell *pCell,            /* Cell to insert into rtree */
120870   int iHeight,                 /* Height of sub-tree rooted at pCell */
120871   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
120872 ){
120873   int rc;
120874   int ii;
120875   RtreeNode *pNode;
120876   rc = nodeAcquire(pRtree, 1, 0, &pNode);
120877
120878   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
120879     int iCell;
120880     sqlite3_int64 iBest;
120881
120882     float fMinGrowth;
120883     float fMinArea;
120884     float fMinOverlap;
120885
120886     int nCell = NCELL(pNode);
120887     RtreeCell cell;
120888     RtreeNode *pChild;
120889
120890     RtreeCell *aCell = 0;
120891
120892 #if VARIANT_RSTARTREE_CHOOSESUBTREE
120893     if( ii==(pRtree->iDepth-1) ){
120894       int jj;
120895       aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
120896       if( !aCell ){
120897         rc = SQLITE_NOMEM;
120898         nodeRelease(pRtree, pNode);
120899         pNode = 0;
120900         continue;
120901       }
120902       for(jj=0; jj<nCell; jj++){
120903         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
120904       }
120905     }
120906 #endif
120907
120908     /* Select the child node which will be enlarged the least if pCell
120909     ** is inserted into it. Resolve ties by choosing the entry with
120910     ** the smallest area.
120911     */
120912     for(iCell=0; iCell<nCell; iCell++){
120913       int bBest = 0;
120914       float growth;
120915       float area;
120916       float overlap = 0.0;
120917       nodeGetCell(pRtree, pNode, iCell, &cell);
120918       growth = cellGrowth(pRtree, &cell, pCell);
120919       area = cellArea(pRtree, &cell);
120920
120921 #if VARIANT_RSTARTREE_CHOOSESUBTREE
120922       if( ii==(pRtree->iDepth-1) ){
120923         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
120924       }
120925       if( (iCell==0) 
120926        || (overlap<fMinOverlap) 
120927        || (overlap==fMinOverlap && growth<fMinGrowth)
120928        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
120929       ){
120930         bBest = 1;
120931       }
120932 #else
120933       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
120934         bBest = 1;
120935       }
120936 #endif
120937       if( bBest ){
120938         fMinOverlap = overlap;
120939         fMinGrowth = growth;
120940         fMinArea = area;
120941         iBest = cell.iRowid;
120942       }
120943     }
120944
120945     sqlite3_free(aCell);
120946     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
120947     nodeRelease(pRtree, pNode);
120948     pNode = pChild;
120949   }
120950
120951   *ppLeaf = pNode;
120952   return rc;
120953 }
120954
120955 /*
120956 ** A cell with the same content as pCell has just been inserted into
120957 ** the node pNode. This function updates the bounding box cells in
120958 ** all ancestor elements.
120959 */
120960 static int AdjustTree(
120961   Rtree *pRtree,                    /* Rtree table */
120962   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
120963   RtreeCell *pCell                  /* This cell was just inserted */
120964 ){
120965   RtreeNode *p = pNode;
120966   while( p->pParent ){
120967     RtreeNode *pParent = p->pParent;
120968     RtreeCell cell;
120969     int iCell;
120970
120971     if( nodeParentIndex(pRtree, p, &iCell) ){
120972       return SQLITE_CORRUPT;
120973     }
120974
120975     nodeGetCell(pRtree, pParent, iCell, &cell);
120976     if( !cellContains(pRtree, &cell, pCell) ){
120977       cellUnion(pRtree, &cell, pCell);
120978       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
120979     }
120980  
120981     p = pParent;
120982   }
120983   return SQLITE_OK;
120984 }
120985
120986 /*
120987 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
120988 */
120989 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
120990   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
120991   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
120992   sqlite3_step(pRtree->pWriteRowid);
120993   return sqlite3_reset(pRtree->pWriteRowid);
120994 }
120995
120996 /*
120997 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
120998 */
120999 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
121000   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
121001   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
121002   sqlite3_step(pRtree->pWriteParent);
121003   return sqlite3_reset(pRtree->pWriteParent);
121004 }
121005
121006 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
121007
121008 #if VARIANT_GUTTMAN_LINEAR_SPLIT
121009 /*
121010 ** Implementation of the linear variant of the PickNext() function from
121011 ** Guttman[84].
121012 */
121013 static RtreeCell *LinearPickNext(
121014   Rtree *pRtree,
121015   RtreeCell *aCell, 
121016   int nCell, 
121017   RtreeCell *pLeftBox, 
121018   RtreeCell *pRightBox,
121019   int *aiUsed
121020 ){
121021   int ii;
121022   for(ii=0; aiUsed[ii]; ii++);
121023   aiUsed[ii] = 1;
121024   return &aCell[ii];
121025 }
121026
121027 /*
121028 ** Implementation of the linear variant of the PickSeeds() function from
121029 ** Guttman[84].
121030 */
121031 static void LinearPickSeeds(
121032   Rtree *pRtree,
121033   RtreeCell *aCell, 
121034   int nCell, 
121035   int *piLeftSeed, 
121036   int *piRightSeed
121037 ){
121038   int i;
121039   int iLeftSeed = 0;
121040   int iRightSeed = 1;
121041   float maxNormalInnerWidth = 0.0;
121042
121043   /* Pick two "seed" cells from the array of cells. The algorithm used
121044   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The 
121045   ** indices of the two seed cells in the array are stored in local
121046   ** variables iLeftSeek and iRightSeed.
121047   */
121048   for(i=0; i<pRtree->nDim; i++){
121049     float x1 = DCOORD(aCell[0].aCoord[i*2]);
121050     float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
121051     float x3 = x1;
121052     float x4 = x2;
121053     int jj;
121054
121055     int iCellLeft = 0;
121056     int iCellRight = 0;
121057
121058     for(jj=1; jj<nCell; jj++){
121059       float left = DCOORD(aCell[jj].aCoord[i*2]);
121060       float right = DCOORD(aCell[jj].aCoord[i*2+1]);
121061
121062       if( left<x1 ) x1 = left;
121063       if( right>x4 ) x4 = right;
121064       if( left>x3 ){
121065         x3 = left;
121066         iCellRight = jj;
121067       }
121068       if( right<x2 ){
121069         x2 = right;
121070         iCellLeft = jj;
121071       }
121072     }
121073
121074     if( x4!=x1 ){
121075       float normalwidth = (x3 - x2) / (x4 - x1);
121076       if( normalwidth>maxNormalInnerWidth ){
121077         iLeftSeed = iCellLeft;
121078         iRightSeed = iCellRight;
121079       }
121080     }
121081   }
121082
121083   *piLeftSeed = iLeftSeed;
121084   *piRightSeed = iRightSeed;
121085 }
121086 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
121087
121088 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
121089 /*
121090 ** Implementation of the quadratic variant of the PickNext() function from
121091 ** Guttman[84].
121092 */
121093 static RtreeCell *QuadraticPickNext(
121094   Rtree *pRtree,
121095   RtreeCell *aCell, 
121096   int nCell, 
121097   RtreeCell *pLeftBox, 
121098   RtreeCell *pRightBox,
121099   int *aiUsed
121100 ){
121101   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
121102
121103   int iSelect = -1;
121104   float fDiff;
121105   int ii;
121106   for(ii=0; ii<nCell; ii++){
121107     if( aiUsed[ii]==0 ){
121108       float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
121109       float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
121110       float diff = FABS(right-left);
121111       if( iSelect<0 || diff>fDiff ){
121112         fDiff = diff;
121113         iSelect = ii;
121114       }
121115     }
121116   }
121117   aiUsed[iSelect] = 1;
121118   return &aCell[iSelect];
121119 }
121120
121121 /*
121122 ** Implementation of the quadratic variant of the PickSeeds() function from
121123 ** Guttman[84].
121124 */
121125 static void QuadraticPickSeeds(
121126   Rtree *pRtree,
121127   RtreeCell *aCell, 
121128   int nCell, 
121129   int *piLeftSeed, 
121130   int *piRightSeed
121131 ){
121132   int ii;
121133   int jj;
121134
121135   int iLeftSeed = 0;
121136   int iRightSeed = 1;
121137   float fWaste = 0.0;
121138
121139   for(ii=0; ii<nCell; ii++){
121140     for(jj=ii+1; jj<nCell; jj++){
121141       float right = cellArea(pRtree, &aCell[jj]);
121142       float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
121143       float waste = growth - right;
121144
121145       if( waste>fWaste ){
121146         iLeftSeed = ii;
121147         iRightSeed = jj;
121148         fWaste = waste;
121149       }
121150     }
121151   }
121152
121153   *piLeftSeed = iLeftSeed;
121154   *piRightSeed = iRightSeed;
121155 }
121156 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
121157
121158 /*
121159 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
121160 ** nIdx. The aIdx array contains the set of integers from 0 to 
121161 ** (nIdx-1) in no particular order. This function sorts the values
121162 ** in aIdx according to the indexed values in aDistance. For
121163 ** example, assuming the inputs:
121164 **
121165 **   aIdx      = { 0,   1,   2,   3 }
121166 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
121167 **
121168 ** this function sets the aIdx array to contain:
121169 **
121170 **   aIdx      = { 0,   1,   2,   3 }
121171 **
121172 ** The aSpare array is used as temporary working space by the
121173 ** sorting algorithm.
121174 */
121175 static void SortByDistance(
121176   int *aIdx, 
121177   int nIdx, 
121178   float *aDistance, 
121179   int *aSpare
121180 ){
121181   if( nIdx>1 ){
121182     int iLeft = 0;
121183     int iRight = 0;
121184
121185     int nLeft = nIdx/2;
121186     int nRight = nIdx-nLeft;
121187     int *aLeft = aIdx;
121188     int *aRight = &aIdx[nLeft];
121189
121190     SortByDistance(aLeft, nLeft, aDistance, aSpare);
121191     SortByDistance(aRight, nRight, aDistance, aSpare);
121192
121193     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
121194     aLeft = aSpare;
121195
121196     while( iLeft<nLeft || iRight<nRight ){
121197       if( iLeft==nLeft ){
121198         aIdx[iLeft+iRight] = aRight[iRight];
121199         iRight++;
121200       }else if( iRight==nRight ){
121201         aIdx[iLeft+iRight] = aLeft[iLeft];
121202         iLeft++;
121203       }else{
121204         float fLeft = aDistance[aLeft[iLeft]];
121205         float fRight = aDistance[aRight[iRight]];
121206         if( fLeft<fRight ){
121207           aIdx[iLeft+iRight] = aLeft[iLeft];
121208           iLeft++;
121209         }else{
121210           aIdx[iLeft+iRight] = aRight[iRight];
121211           iRight++;
121212         }
121213       }
121214     }
121215
121216 #if 0
121217     /* Check that the sort worked */
121218     {
121219       int jj;
121220       for(jj=1; jj<nIdx; jj++){
121221         float left = aDistance[aIdx[jj-1]];
121222         float right = aDistance[aIdx[jj]];
121223         assert( left<=right );
121224       }
121225     }
121226 #endif
121227   }
121228 }
121229
121230 /*
121231 ** Arguments aIdx, aCell and aSpare all point to arrays of size
121232 ** nIdx. The aIdx array contains the set of integers from 0 to 
121233 ** (nIdx-1) in no particular order. This function sorts the values
121234 ** in aIdx according to dimension iDim of the cells in aCell. The
121235 ** minimum value of dimension iDim is considered first, the
121236 ** maximum used to break ties.
121237 **
121238 ** The aSpare array is used as temporary working space by the
121239 ** sorting algorithm.
121240 */
121241 static void SortByDimension(
121242   Rtree *pRtree,
121243   int *aIdx, 
121244   int nIdx, 
121245   int iDim, 
121246   RtreeCell *aCell, 
121247   int *aSpare
121248 ){
121249   if( nIdx>1 ){
121250
121251     int iLeft = 0;
121252     int iRight = 0;
121253
121254     int nLeft = nIdx/2;
121255     int nRight = nIdx-nLeft;
121256     int *aLeft = aIdx;
121257     int *aRight = &aIdx[nLeft];
121258
121259     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
121260     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
121261
121262     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
121263     aLeft = aSpare;
121264     while( iLeft<nLeft || iRight<nRight ){
121265       double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
121266       double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
121267       double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
121268       double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
121269       if( (iLeft!=nLeft) && ((iRight==nRight)
121270        || (xleft1<xright1)
121271        || (xleft1==xright1 && xleft2<xright2)
121272       )){
121273         aIdx[iLeft+iRight] = aLeft[iLeft];
121274         iLeft++;
121275       }else{
121276         aIdx[iLeft+iRight] = aRight[iRight];
121277         iRight++;
121278       }
121279     }
121280
121281 #if 0
121282     /* Check that the sort worked */
121283     {
121284       int jj;
121285       for(jj=1; jj<nIdx; jj++){
121286         float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
121287         float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
121288         float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
121289         float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
121290         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
121291       }
121292     }
121293 #endif
121294   }
121295 }
121296
121297 #if VARIANT_RSTARTREE_SPLIT
121298 /*
121299 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
121300 */
121301 static int splitNodeStartree(
121302   Rtree *pRtree,
121303   RtreeCell *aCell,
121304   int nCell,
121305   RtreeNode *pLeft,
121306   RtreeNode *pRight,
121307   RtreeCell *pBboxLeft,
121308   RtreeCell *pBboxRight
121309 ){
121310   int **aaSorted;
121311   int *aSpare;
121312   int ii;
121313
121314   int iBestDim;
121315   int iBestSplit;
121316   float fBestMargin;
121317
121318   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
121319
121320   aaSorted = (int **)sqlite3_malloc(nByte);
121321   if( !aaSorted ){
121322     return SQLITE_NOMEM;
121323   }
121324
121325   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
121326   memset(aaSorted, 0, nByte);
121327   for(ii=0; ii<pRtree->nDim; ii++){
121328     int jj;
121329     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
121330     for(jj=0; jj<nCell; jj++){
121331       aaSorted[ii][jj] = jj;
121332     }
121333     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
121334   }
121335
121336   for(ii=0; ii<pRtree->nDim; ii++){
121337     float margin = 0.0;
121338     float fBestOverlap;
121339     float fBestArea;
121340     int iBestLeft;
121341     int nLeft;
121342
121343     for(
121344       nLeft=RTREE_MINCELLS(pRtree); 
121345       nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
121346       nLeft++
121347     ){
121348       RtreeCell left;
121349       RtreeCell right;
121350       int kk;
121351       float overlap;
121352       float area;
121353
121354       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
121355       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
121356       for(kk=1; kk<(nCell-1); kk++){
121357         if( kk<nLeft ){
121358           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
121359         }else{
121360           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
121361         }
121362       }
121363       margin += cellMargin(pRtree, &left);
121364       margin += cellMargin(pRtree, &right);
121365       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
121366       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
121367       if( (nLeft==RTREE_MINCELLS(pRtree))
121368        || (overlap<fBestOverlap)
121369        || (overlap==fBestOverlap && area<fBestArea)
121370       ){
121371         iBestLeft = nLeft;
121372         fBestOverlap = overlap;
121373         fBestArea = area;
121374       }
121375     }
121376
121377     if( ii==0 || margin<fBestMargin ){
121378       iBestDim = ii;
121379       fBestMargin = margin;
121380       iBestSplit = iBestLeft;
121381     }
121382   }
121383
121384   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
121385   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
121386   for(ii=0; ii<nCell; ii++){
121387     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
121388     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
121389     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
121390     nodeInsertCell(pRtree, pTarget, pCell);
121391     cellUnion(pRtree, pBbox, pCell);
121392   }
121393
121394   sqlite3_free(aaSorted);
121395   return SQLITE_OK;
121396 }
121397 #endif
121398
121399 #if VARIANT_GUTTMAN_SPLIT
121400 /*
121401 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
121402 */
121403 static int splitNodeGuttman(
121404   Rtree *pRtree,
121405   RtreeCell *aCell,
121406   int nCell,
121407   RtreeNode *pLeft,
121408   RtreeNode *pRight,
121409   RtreeCell *pBboxLeft,
121410   RtreeCell *pBboxRight
121411 ){
121412   int iLeftSeed = 0;
121413   int iRightSeed = 1;
121414   int *aiUsed;
121415   int i;
121416
121417   aiUsed = sqlite3_malloc(sizeof(int)*nCell);
121418   if( !aiUsed ){
121419     return SQLITE_NOMEM;
121420   }
121421   memset(aiUsed, 0, sizeof(int)*nCell);
121422
121423   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
121424
121425   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
121426   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
121427   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
121428   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
121429   aiUsed[iLeftSeed] = 1;
121430   aiUsed[iRightSeed] = 1;
121431
121432   for(i=nCell-2; i>0; i--){
121433     RtreeCell *pNext;
121434     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
121435     float diff =  
121436       cellGrowth(pRtree, pBboxLeft, pNext) - 
121437       cellGrowth(pRtree, pBboxRight, pNext)
121438     ;
121439     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
121440      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
121441     ){
121442       nodeInsertCell(pRtree, pRight, pNext);
121443       cellUnion(pRtree, pBboxRight, pNext);
121444     }else{
121445       nodeInsertCell(pRtree, pLeft, pNext);
121446       cellUnion(pRtree, pBboxLeft, pNext);
121447     }
121448   }
121449
121450   sqlite3_free(aiUsed);
121451   return SQLITE_OK;
121452 }
121453 #endif
121454
121455 static int updateMapping(
121456   Rtree *pRtree, 
121457   i64 iRowid, 
121458   RtreeNode *pNode, 
121459   int iHeight
121460 ){
121461   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
121462   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
121463   if( iHeight>0 ){
121464     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
121465     if( pChild ){
121466       nodeRelease(pRtree, pChild->pParent);
121467       nodeReference(pNode);
121468       pChild->pParent = pNode;
121469     }
121470   }
121471   return xSetMapping(pRtree, iRowid, pNode->iNode);
121472 }
121473
121474 static int SplitNode(
121475   Rtree *pRtree,
121476   RtreeNode *pNode,
121477   RtreeCell *pCell,
121478   int iHeight
121479 ){
121480   int i;
121481   int newCellIsRight = 0;
121482
121483   int rc = SQLITE_OK;
121484   int nCell = NCELL(pNode);
121485   RtreeCell *aCell;
121486   int *aiUsed;
121487
121488   RtreeNode *pLeft = 0;
121489   RtreeNode *pRight = 0;
121490
121491   RtreeCell leftbbox;
121492   RtreeCell rightbbox;
121493
121494   /* Allocate an array and populate it with a copy of pCell and 
121495   ** all cells from node pLeft. Then zero the original node.
121496   */
121497   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
121498   if( !aCell ){
121499     rc = SQLITE_NOMEM;
121500     goto splitnode_out;
121501   }
121502   aiUsed = (int *)&aCell[nCell+1];
121503   memset(aiUsed, 0, sizeof(int)*(nCell+1));
121504   for(i=0; i<nCell; i++){
121505     nodeGetCell(pRtree, pNode, i, &aCell[i]);
121506   }
121507   nodeZero(pRtree, pNode);
121508   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
121509   nCell++;
121510
121511   if( pNode->iNode==1 ){
121512     pRight = nodeNew(pRtree, pNode);
121513     pLeft = nodeNew(pRtree, pNode);
121514     pRtree->iDepth++;
121515     pNode->isDirty = 1;
121516     writeInt16(pNode->zData, pRtree->iDepth);
121517   }else{
121518     pLeft = pNode;
121519     pRight = nodeNew(pRtree, pLeft->pParent);
121520     nodeReference(pLeft);
121521   }
121522
121523   if( !pLeft || !pRight ){
121524     rc = SQLITE_NOMEM;
121525     goto splitnode_out;
121526   }
121527
121528   memset(pLeft->zData, 0, pRtree->iNodeSize);
121529   memset(pRight->zData, 0, pRtree->iNodeSize);
121530
121531   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
121532   if( rc!=SQLITE_OK ){
121533     goto splitnode_out;
121534   }
121535
121536   /* Ensure both child nodes have node numbers assigned to them by calling
121537   ** nodeWrite(). Node pRight always needs a node number, as it was created
121538   ** by nodeNew() above. But node pLeft sometimes already has a node number.
121539   ** In this case avoid the all to nodeWrite().
121540   */
121541   if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
121542    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
121543   ){
121544     goto splitnode_out;
121545   }
121546
121547   rightbbox.iRowid = pRight->iNode;
121548   leftbbox.iRowid = pLeft->iNode;
121549
121550   if( pNode->iNode==1 ){
121551     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
121552     if( rc!=SQLITE_OK ){
121553       goto splitnode_out;
121554     }
121555   }else{
121556     RtreeNode *pParent = pLeft->pParent;
121557     int iCell;
121558     rc = nodeParentIndex(pRtree, pLeft, &iCell);
121559     if( rc==SQLITE_OK ){
121560       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
121561       rc = AdjustTree(pRtree, pParent, &leftbbox);
121562     }
121563     if( rc!=SQLITE_OK ){
121564       goto splitnode_out;
121565     }
121566   }
121567   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
121568     goto splitnode_out;
121569   }
121570
121571   for(i=0; i<NCELL(pRight); i++){
121572     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
121573     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
121574     if( iRowid==pCell->iRowid ){
121575       newCellIsRight = 1;
121576     }
121577     if( rc!=SQLITE_OK ){
121578       goto splitnode_out;
121579     }
121580   }
121581   if( pNode->iNode==1 ){
121582     for(i=0; i<NCELL(pLeft); i++){
121583       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
121584       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
121585       if( rc!=SQLITE_OK ){
121586         goto splitnode_out;
121587       }
121588     }
121589   }else if( newCellIsRight==0 ){
121590     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
121591   }
121592
121593   if( rc==SQLITE_OK ){
121594     rc = nodeRelease(pRtree, pRight);
121595     pRight = 0;
121596   }
121597   if( rc==SQLITE_OK ){
121598     rc = nodeRelease(pRtree, pLeft);
121599     pLeft = 0;
121600   }
121601
121602 splitnode_out:
121603   nodeRelease(pRtree, pRight);
121604   nodeRelease(pRtree, pLeft);
121605   sqlite3_free(aCell);
121606   return rc;
121607 }
121608
121609 /*
121610 ** If node pLeaf is not the root of the r-tree and its pParent pointer is 
121611 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
121612 ** the pLeaf->pParent chain all the way up to the root node.
121613 **
121614 ** This operation is required when a row is deleted (or updated - an update
121615 ** is implemented as a delete followed by an insert). SQLite provides the
121616 ** rowid of the row to delete, which can be used to find the leaf on which
121617 ** the entry resides (argument pLeaf). Once the leaf is located, this 
121618 ** function is called to determine its ancestry.
121619 */
121620 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
121621   int rc = SQLITE_OK;
121622   RtreeNode *pChild = pLeaf;
121623   while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
121624     int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
121625     sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
121626     rc = sqlite3_step(pRtree->pReadParent);
121627     if( rc==SQLITE_ROW ){
121628       RtreeNode *pTest;           /* Used to test for reference loops */
121629       i64 iNode;                  /* Node number of parent node */
121630
121631       /* Before setting pChild->pParent, test that we are not creating a
121632       ** loop of references (as we would if, say, pChild==pParent). We don't
121633       ** want to do this as it leads to a memory leak when trying to delete
121634       ** the referenced counted node structures.
121635       */
121636       iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
121637       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
121638       if( !pTest ){
121639         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
121640       }
121641     }
121642     rc = sqlite3_reset(pRtree->pReadParent);
121643     if( rc==SQLITE_OK ) rc = rc2;
121644     if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT;
121645     pChild = pChild->pParent;
121646   }
121647   return rc;
121648 }
121649
121650 static int deleteCell(Rtree *, RtreeNode *, int, int);
121651
121652 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
121653   int rc;
121654   int rc2;
121655   RtreeNode *pParent;
121656   int iCell;
121657
121658   assert( pNode->nRef==1 );
121659
121660   /* Remove the entry in the parent cell. */
121661   rc = nodeParentIndex(pRtree, pNode, &iCell);
121662   if( rc==SQLITE_OK ){
121663     pParent = pNode->pParent;
121664     pNode->pParent = 0;
121665     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
121666   }
121667   rc2 = nodeRelease(pRtree, pParent);
121668   if( rc==SQLITE_OK ){
121669     rc = rc2;
121670   }
121671   if( rc!=SQLITE_OK ){
121672     return rc;
121673   }
121674
121675   /* Remove the xxx_node entry. */
121676   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
121677   sqlite3_step(pRtree->pDeleteNode);
121678   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
121679     return rc;
121680   }
121681
121682   /* Remove the xxx_parent entry. */
121683   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
121684   sqlite3_step(pRtree->pDeleteParent);
121685   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
121686     return rc;
121687   }
121688   
121689   /* Remove the node from the in-memory hash table and link it into
121690   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
121691   */
121692   nodeHashDelete(pRtree, pNode);
121693   pNode->iNode = iHeight;
121694   pNode->pNext = pRtree->pDeleted;
121695   pNode->nRef++;
121696   pRtree->pDeleted = pNode;
121697
121698   return SQLITE_OK;
121699 }
121700
121701 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
121702   RtreeNode *pParent = pNode->pParent;
121703   int rc = SQLITE_OK; 
121704   if( pParent ){
121705     int ii; 
121706     int nCell = NCELL(pNode);
121707     RtreeCell box;                            /* Bounding box for pNode */
121708     nodeGetCell(pRtree, pNode, 0, &box);
121709     for(ii=1; ii<nCell; ii++){
121710       RtreeCell cell;
121711       nodeGetCell(pRtree, pNode, ii, &cell);
121712       cellUnion(pRtree, &box, &cell);
121713     }
121714     box.iRowid = pNode->iNode;
121715     rc = nodeParentIndex(pRtree, pNode, &ii);
121716     if( rc==SQLITE_OK ){
121717       nodeOverwriteCell(pRtree, pParent, &box, ii);
121718       rc = fixBoundingBox(pRtree, pParent);
121719     }
121720   }
121721   return rc;
121722 }
121723
121724 /*
121725 ** Delete the cell at index iCell of node pNode. After removing the
121726 ** cell, adjust the r-tree data structure if required.
121727 */
121728 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
121729   RtreeNode *pParent;
121730   int rc;
121731
121732   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
121733     return rc;
121734   }
121735
121736   /* Remove the cell from the node. This call just moves bytes around
121737   ** the in-memory node image, so it cannot fail.
121738   */
121739   nodeDeleteCell(pRtree, pNode, iCell);
121740
121741   /* If the node is not the tree root and now has less than the minimum
121742   ** number of cells, remove it from the tree. Otherwise, update the
121743   ** cell in the parent node so that it tightly contains the updated
121744   ** node.
121745   */
121746   pParent = pNode->pParent;
121747   assert( pParent || pNode->iNode==1 );
121748   if( pParent ){
121749     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
121750       rc = removeNode(pRtree, pNode, iHeight);
121751     }else{
121752       rc = fixBoundingBox(pRtree, pNode);
121753     }
121754   }
121755
121756   return rc;
121757 }
121758
121759 static int Reinsert(
121760   Rtree *pRtree, 
121761   RtreeNode *pNode, 
121762   RtreeCell *pCell, 
121763   int iHeight
121764 ){
121765   int *aOrder;
121766   int *aSpare;
121767   RtreeCell *aCell;
121768   float *aDistance;
121769   int nCell;
121770   float aCenterCoord[RTREE_MAX_DIMENSIONS];
121771   int iDim;
121772   int ii;
121773   int rc = SQLITE_OK;
121774
121775   memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
121776
121777   nCell = NCELL(pNode)+1;
121778
121779   /* Allocate the buffers used by this operation. The allocation is
121780   ** relinquished before this function returns.
121781   */
121782   aCell = (RtreeCell *)sqlite3_malloc(nCell * (
121783     sizeof(RtreeCell) +         /* aCell array */
121784     sizeof(int)       +         /* aOrder array */
121785     sizeof(int)       +         /* aSpare array */
121786     sizeof(float)               /* aDistance array */
121787   ));
121788   if( !aCell ){
121789     return SQLITE_NOMEM;
121790   }
121791   aOrder    = (int *)&aCell[nCell];
121792   aSpare    = (int *)&aOrder[nCell];
121793   aDistance = (float *)&aSpare[nCell];
121794
121795   for(ii=0; ii<nCell; ii++){
121796     if( ii==(nCell-1) ){
121797       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
121798     }else{
121799       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
121800     }
121801     aOrder[ii] = ii;
121802     for(iDim=0; iDim<pRtree->nDim; iDim++){
121803       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
121804       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
121805     }
121806   }
121807   for(iDim=0; iDim<pRtree->nDim; iDim++){
121808     aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
121809   }
121810
121811   for(ii=0; ii<nCell; ii++){
121812     aDistance[ii] = 0.0;
121813     for(iDim=0; iDim<pRtree->nDim; iDim++){
121814       float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
121815           DCOORD(aCell[ii].aCoord[iDim*2]);
121816       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
121817     }
121818   }
121819
121820   SortByDistance(aOrder, nCell, aDistance, aSpare);
121821   nodeZero(pRtree, pNode);
121822
121823   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
121824     RtreeCell *p = &aCell[aOrder[ii]];
121825     nodeInsertCell(pRtree, pNode, p);
121826     if( p->iRowid==pCell->iRowid ){
121827       if( iHeight==0 ){
121828         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
121829       }else{
121830         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
121831       }
121832     }
121833   }
121834   if( rc==SQLITE_OK ){
121835     rc = fixBoundingBox(pRtree, pNode);
121836   }
121837   for(; rc==SQLITE_OK && ii<nCell; ii++){
121838     /* Find a node to store this cell in. pNode->iNode currently contains
121839     ** the height of the sub-tree headed by the cell.
121840     */
121841     RtreeNode *pInsert;
121842     RtreeCell *p = &aCell[aOrder[ii]];
121843     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
121844     if( rc==SQLITE_OK ){
121845       int rc2;
121846       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
121847       rc2 = nodeRelease(pRtree, pInsert);
121848       if( rc==SQLITE_OK ){
121849         rc = rc2;
121850       }
121851     }
121852   }
121853
121854   sqlite3_free(aCell);
121855   return rc;
121856 }
121857
121858 /*
121859 ** Insert cell pCell into node pNode. Node pNode is the head of a 
121860 ** subtree iHeight high (leaf nodes have iHeight==0).
121861 */
121862 static int rtreeInsertCell(
121863   Rtree *pRtree,
121864   RtreeNode *pNode,
121865   RtreeCell *pCell,
121866   int iHeight
121867 ){
121868   int rc = SQLITE_OK;
121869   if( iHeight>0 ){
121870     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
121871     if( pChild ){
121872       nodeRelease(pRtree, pChild->pParent);
121873       nodeReference(pNode);
121874       pChild->pParent = pNode;
121875     }
121876   }
121877   if( nodeInsertCell(pRtree, pNode, pCell) ){
121878 #if VARIANT_RSTARTREE_REINSERT
121879     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
121880       rc = SplitNode(pRtree, pNode, pCell, iHeight);
121881     }else{
121882       pRtree->iReinsertHeight = iHeight;
121883       rc = Reinsert(pRtree, pNode, pCell, iHeight);
121884     }
121885 #else
121886     rc = SplitNode(pRtree, pNode, pCell, iHeight);
121887 #endif
121888   }else{
121889     rc = AdjustTree(pRtree, pNode, pCell);
121890     if( rc==SQLITE_OK ){
121891       if( iHeight==0 ){
121892         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
121893       }else{
121894         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
121895       }
121896     }
121897   }
121898   return rc;
121899 }
121900
121901 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
121902   int ii;
121903   int rc = SQLITE_OK;
121904   int nCell = NCELL(pNode);
121905
121906   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
121907     RtreeNode *pInsert;
121908     RtreeCell cell;
121909     nodeGetCell(pRtree, pNode, ii, &cell);
121910
121911     /* Find a node to store this cell in. pNode->iNode currently contains
121912     ** the height of the sub-tree headed by the cell.
121913     */
121914     rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
121915     if( rc==SQLITE_OK ){
121916       int rc2;
121917       rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
121918       rc2 = nodeRelease(pRtree, pInsert);
121919       if( rc==SQLITE_OK ){
121920         rc = rc2;
121921       }
121922     }
121923   }
121924   return rc;
121925 }
121926
121927 /*
121928 ** Select a currently unused rowid for a new r-tree record.
121929 */
121930 static int newRowid(Rtree *pRtree, i64 *piRowid){
121931   int rc;
121932   sqlite3_bind_null(pRtree->pWriteRowid, 1);
121933   sqlite3_bind_null(pRtree->pWriteRowid, 2);
121934   sqlite3_step(pRtree->pWriteRowid);
121935   rc = sqlite3_reset(pRtree->pWriteRowid);
121936   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
121937   return rc;
121938 }
121939
121940 /*
121941 ** The xUpdate method for rtree module virtual tables.
121942 */
121943 static int rtreeUpdate(
121944   sqlite3_vtab *pVtab, 
121945   int nData, 
121946   sqlite3_value **azData, 
121947   sqlite_int64 *pRowid
121948 ){
121949   Rtree *pRtree = (Rtree *)pVtab;
121950   int rc = SQLITE_OK;
121951
121952   rtreeReference(pRtree);
121953
121954   assert(nData>=1);
121955
121956   /* If azData[0] is not an SQL NULL value, it is the rowid of a
121957   ** record to delete from the r-tree table. The following block does
121958   ** just that.
121959   */
121960   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
121961     i64 iDelete;                /* The rowid to delete */
121962     RtreeNode *pLeaf;           /* Leaf node containing record iDelete */
121963     int iCell;                  /* Index of iDelete cell in pLeaf */
121964     RtreeNode *pRoot;
121965
121966     /* Obtain a reference to the root node to initialise Rtree.iDepth */
121967     rc = nodeAcquire(pRtree, 1, 0, &pRoot);
121968
121969     /* Obtain a reference to the leaf node that contains the entry 
121970     ** about to be deleted. 
121971     */
121972     if( rc==SQLITE_OK ){
121973       iDelete = sqlite3_value_int64(azData[0]);
121974       rc = findLeafNode(pRtree, iDelete, &pLeaf);
121975     }
121976
121977     /* Delete the cell in question from the leaf node. */
121978     if( rc==SQLITE_OK ){
121979       int rc2;
121980       rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
121981       if( rc==SQLITE_OK ){
121982         rc = deleteCell(pRtree, pLeaf, iCell, 0);
121983       }
121984       rc2 = nodeRelease(pRtree, pLeaf);
121985       if( rc==SQLITE_OK ){
121986         rc = rc2;
121987       }
121988     }
121989
121990     /* Delete the corresponding entry in the <rtree>_rowid table. */
121991     if( rc==SQLITE_OK ){
121992       sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
121993       sqlite3_step(pRtree->pDeleteRowid);
121994       rc = sqlite3_reset(pRtree->pDeleteRowid);
121995     }
121996
121997     /* Check if the root node now has exactly one child. If so, remove
121998     ** it, schedule the contents of the child for reinsertion and 
121999     ** reduce the tree height by one.
122000     **
122001     ** This is equivalent to copying the contents of the child into
122002     ** the root node (the operation that Gutman's paper says to perform 
122003     ** in this scenario).
122004     */
122005     if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
122006       int rc2;
122007       RtreeNode *pChild;
122008       i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
122009       rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
122010       if( rc==SQLITE_OK ){
122011         rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
122012       }
122013       rc2 = nodeRelease(pRtree, pChild);
122014       if( rc==SQLITE_OK ) rc = rc2;
122015       if( rc==SQLITE_OK ){
122016         pRtree->iDepth--;
122017         writeInt16(pRoot->zData, pRtree->iDepth);
122018         pRoot->isDirty = 1;
122019       }
122020     }
122021
122022     /* Re-insert the contents of any underfull nodes removed from the tree. */
122023     for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
122024       if( rc==SQLITE_OK ){
122025         rc = reinsertNodeContent(pRtree, pLeaf);
122026       }
122027       pRtree->pDeleted = pLeaf->pNext;
122028       sqlite3_free(pLeaf);
122029     }
122030
122031     /* Release the reference to the root node. */
122032     if( rc==SQLITE_OK ){
122033       rc = nodeRelease(pRtree, pRoot);
122034     }else{
122035       nodeRelease(pRtree, pRoot);
122036     }
122037   }
122038
122039   /* If the azData[] array contains more than one element, elements
122040   ** (azData[2]..azData[argc-1]) contain a new record to insert into
122041   ** the r-tree structure.
122042   */
122043   if( rc==SQLITE_OK && nData>1 ){
122044     /* Insert a new record into the r-tree */
122045     RtreeCell cell;
122046     int ii;
122047     RtreeNode *pLeaf;
122048
122049     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
122050     assert( nData==(pRtree->nDim*2 + 3) );
122051     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
122052       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
122053         cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
122054         cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
122055         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
122056           rc = SQLITE_CONSTRAINT;
122057           goto constraint;
122058         }
122059       }
122060     }else{
122061       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
122062         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
122063         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
122064         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
122065           rc = SQLITE_CONSTRAINT;
122066           goto constraint;
122067         }
122068       }
122069     }
122070
122071     /* Figure out the rowid of the new row. */
122072     if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
122073       rc = newRowid(pRtree, &cell.iRowid);
122074     }else{
122075       cell.iRowid = sqlite3_value_int64(azData[2]);
122076       sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
122077       if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
122078         sqlite3_reset(pRtree->pReadRowid);
122079         rc = SQLITE_CONSTRAINT;
122080         goto constraint;
122081       }
122082       rc = sqlite3_reset(pRtree->pReadRowid);
122083     }
122084     *pRowid = cell.iRowid;
122085
122086     if( rc==SQLITE_OK ){
122087       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
122088     }
122089     if( rc==SQLITE_OK ){
122090       int rc2;
122091       pRtree->iReinsertHeight = -1;
122092       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
122093       rc2 = nodeRelease(pRtree, pLeaf);
122094       if( rc==SQLITE_OK ){
122095         rc = rc2;
122096       }
122097     }
122098   }
122099
122100 constraint:
122101   rtreeRelease(pRtree);
122102   return rc;
122103 }
122104
122105 /*
122106 ** The xRename method for rtree module virtual tables.
122107 */
122108 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
122109   Rtree *pRtree = (Rtree *)pVtab;
122110   int rc = SQLITE_NOMEM;
122111   char *zSql = sqlite3_mprintf(
122112     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
122113     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
122114     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
122115     , pRtree->zDb, pRtree->zName, zNewName 
122116     , pRtree->zDb, pRtree->zName, zNewName 
122117     , pRtree->zDb, pRtree->zName, zNewName
122118   );
122119   if( zSql ){
122120     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
122121     sqlite3_free(zSql);
122122   }
122123   return rc;
122124 }
122125
122126 static sqlite3_module rtreeModule = {
122127   0,                         /* iVersion */
122128   rtreeCreate,                /* xCreate - create a table */
122129   rtreeConnect,               /* xConnect - connect to an existing table */
122130   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
122131   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
122132   rtreeDestroy,               /* xDestroy - Drop a table */
122133   rtreeOpen,                  /* xOpen - open a cursor */
122134   rtreeClose,                 /* xClose - close a cursor */
122135   rtreeFilter,                /* xFilter - configure scan constraints */
122136   rtreeNext,                  /* xNext - advance a cursor */
122137   rtreeEof,                   /* xEof */
122138   rtreeColumn,                /* xColumn - read data */
122139   rtreeRowid,                 /* xRowid - read data */
122140   rtreeUpdate,                /* xUpdate - write data */
122141   0,                          /* xBegin - begin transaction */
122142   0,                          /* xSync - sync transaction */
122143   0,                          /* xCommit - commit transaction */
122144   0,                          /* xRollback - rollback transaction */
122145   0,                          /* xFindFunction - function overloading */
122146   rtreeRename                 /* xRename - rename the table */
122147 };
122148
122149 static int rtreeSqlInit(
122150   Rtree *pRtree, 
122151   sqlite3 *db, 
122152   const char *zDb, 
122153   const char *zPrefix, 
122154   int isCreate
122155 ){
122156   int rc = SQLITE_OK;
122157
122158   #define N_STATEMENT 9
122159   static const char *azSql[N_STATEMENT] = {
122160     /* Read and write the xxx_node table */
122161     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
122162     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
122163     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
122164
122165     /* Read and write the xxx_rowid table */
122166     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
122167     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
122168     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
122169
122170     /* Read and write the xxx_parent table */
122171     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
122172     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
122173     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
122174   };
122175   sqlite3_stmt **appStmt[N_STATEMENT];
122176   int i;
122177
122178   pRtree->db = db;
122179
122180   if( isCreate ){
122181     char *zCreate = sqlite3_mprintf(
122182 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
122183 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
122184 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
122185 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
122186       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
122187     );
122188     if( !zCreate ){
122189       return SQLITE_NOMEM;
122190     }
122191     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
122192     sqlite3_free(zCreate);
122193     if( rc!=SQLITE_OK ){
122194       return rc;
122195     }
122196   }
122197
122198   appStmt[0] = &pRtree->pReadNode;
122199   appStmt[1] = &pRtree->pWriteNode;
122200   appStmt[2] = &pRtree->pDeleteNode;
122201   appStmt[3] = &pRtree->pReadRowid;
122202   appStmt[4] = &pRtree->pWriteRowid;
122203   appStmt[5] = &pRtree->pDeleteRowid;
122204   appStmt[6] = &pRtree->pReadParent;
122205   appStmt[7] = &pRtree->pWriteParent;
122206   appStmt[8] = &pRtree->pDeleteParent;
122207
122208   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
122209     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
122210     if( zSql ){
122211       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); 
122212     }else{
122213       rc = SQLITE_NOMEM;
122214     }
122215     sqlite3_free(zSql);
122216   }
122217
122218   return rc;
122219 }
122220
122221 /*
122222 ** The second argument to this function contains the text of an SQL statement
122223 ** that returns a single integer value. The statement is compiled and executed
122224 ** using database connection db. If successful, the integer value returned
122225 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
122226 ** code is returned and the value of *piVal after returning is not defined.
122227 */
122228 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
122229   int rc = SQLITE_NOMEM;
122230   if( zSql ){
122231     sqlite3_stmt *pStmt = 0;
122232     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
122233     if( rc==SQLITE_OK ){
122234       if( SQLITE_ROW==sqlite3_step(pStmt) ){
122235         *piVal = sqlite3_column_int(pStmt, 0);
122236       }
122237       rc = sqlite3_finalize(pStmt);
122238     }
122239   }
122240   return rc;
122241 }
122242
122243 /*
122244 ** This function is called from within the xConnect() or xCreate() method to
122245 ** determine the node-size used by the rtree table being created or connected
122246 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
122247 ** Otherwise, an SQLite error code is returned.
122248 **
122249 ** If this function is being called as part of an xConnect(), then the rtree
122250 ** table already exists. In this case the node-size is determined by inspecting
122251 ** the root node of the tree.
122252 **
122253 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. 
122254 ** This ensures that each node is stored on a single database page. If the 
122255 ** database page-size is so large that more than RTREE_MAXCELLS entries 
122256 ** would fit in a single node, use a smaller node-size.
122257 */
122258 static int getNodeSize(
122259   sqlite3 *db,                    /* Database handle */
122260   Rtree *pRtree,                  /* Rtree handle */
122261   int isCreate                    /* True for xCreate, false for xConnect */
122262 ){
122263   int rc;
122264   char *zSql;
122265   if( isCreate ){
122266     int iPageSize;
122267     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
122268     rc = getIntFromStmt(db, zSql, &iPageSize);
122269     if( rc==SQLITE_OK ){
122270       pRtree->iNodeSize = iPageSize-64;
122271       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
122272         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
122273       }
122274     }
122275   }else{
122276     zSql = sqlite3_mprintf(
122277         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
122278         pRtree->zDb, pRtree->zName
122279     );
122280     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
122281   }
122282
122283   sqlite3_free(zSql);
122284   return rc;
122285 }
122286
122287 /* 
122288 ** This function is the implementation of both the xConnect and xCreate
122289 ** methods of the r-tree virtual table.
122290 **
122291 **   argv[0]   -> module name
122292 **   argv[1]   -> database name
122293 **   argv[2]   -> table name
122294 **   argv[...] -> column names...
122295 */
122296 static int rtreeInit(
122297   sqlite3 *db,                        /* Database connection */
122298   void *pAux,                         /* One of the RTREE_COORD_* constants */
122299   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
122300   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
122301   char **pzErr,                       /* OUT: Error message, if any */
122302   int isCreate                        /* True for xCreate, false for xConnect */
122303 ){
122304   int rc = SQLITE_OK;
122305   Rtree *pRtree;
122306   int nDb;              /* Length of string argv[1] */
122307   int nName;            /* Length of string argv[2] */
122308   int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
122309
122310   const char *aErrMsg[] = {
122311     0,                                                    /* 0 */
122312     "Wrong number of columns for an rtree table",         /* 1 */
122313     "Too few columns for an rtree table",                 /* 2 */
122314     "Too many columns for an rtree table"                 /* 3 */
122315   };
122316
122317   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
122318   if( aErrMsg[iErr] ){
122319     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
122320     return SQLITE_ERROR;
122321   }
122322
122323   /* Allocate the sqlite3_vtab structure */
122324   nDb = strlen(argv[1]);
122325   nName = strlen(argv[2]);
122326   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
122327   if( !pRtree ){
122328     return SQLITE_NOMEM;
122329   }
122330   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
122331   pRtree->nBusy = 1;
122332   pRtree->base.pModule = &rtreeModule;
122333   pRtree->zDb = (char *)&pRtree[1];
122334   pRtree->zName = &pRtree->zDb[nDb+1];
122335   pRtree->nDim = (argc-4)/2;
122336   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
122337   pRtree->eCoordType = eCoordType;
122338   memcpy(pRtree->zDb, argv[1], nDb);
122339   memcpy(pRtree->zName, argv[2], nName);
122340
122341   /* Figure out the node size to use. */
122342   rc = getNodeSize(db, pRtree, isCreate);
122343
122344   /* Create/Connect to the underlying relational database schema. If
122345   ** that is successful, call sqlite3_declare_vtab() to configure
122346   ** the r-tree table schema.
122347   */
122348   if( rc==SQLITE_OK ){
122349     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
122350       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
122351     }else{
122352       char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
122353       char *zTmp;
122354       int ii;
122355       for(ii=4; zSql && ii<argc; ii++){
122356         zTmp = zSql;
122357         zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
122358         sqlite3_free(zTmp);
122359       }
122360       if( zSql ){
122361         zTmp = zSql;
122362         zSql = sqlite3_mprintf("%s);", zTmp);
122363         sqlite3_free(zTmp);
122364       }
122365       if( !zSql ){
122366         rc = SQLITE_NOMEM;
122367       }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
122368         *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
122369       }
122370       sqlite3_free(zSql);
122371     }
122372   }
122373
122374   if( rc==SQLITE_OK ){
122375     *ppVtab = (sqlite3_vtab *)pRtree;
122376   }else{
122377     rtreeRelease(pRtree);
122378   }
122379   return rc;
122380 }
122381
122382
122383 /*
122384 ** Implementation of a scalar function that decodes r-tree nodes to
122385 ** human readable strings. This can be used for debugging and analysis.
122386 **
122387 ** The scalar function takes two arguments, a blob of data containing
122388 ** an r-tree node, and the number of dimensions the r-tree indexes.
122389 ** For a two-dimensional r-tree structure called "rt", to deserialize
122390 ** all nodes, a statement like:
122391 **
122392 **   SELECT rtreenode(2, data) FROM rt_node;
122393 **
122394 ** The human readable string takes the form of a Tcl list with one
122395 ** entry for each cell in the r-tree node. Each entry is itself a
122396 ** list, containing the 8-byte rowid/pageno followed by the 
122397 ** <num-dimension>*2 coordinates.
122398 */
122399 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
122400   char *zText = 0;
122401   RtreeNode node;
122402   Rtree tree;
122403   int ii;
122404
122405   UNUSED_PARAMETER(nArg);
122406   memset(&node, 0, sizeof(RtreeNode));
122407   memset(&tree, 0, sizeof(Rtree));
122408   tree.nDim = sqlite3_value_int(apArg[0]);
122409   tree.nBytesPerCell = 8 + 8 * tree.nDim;
122410   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
122411
122412   for(ii=0; ii<NCELL(&node); ii++){
122413     char zCell[512];
122414     int nCell = 0;
122415     RtreeCell cell;
122416     int jj;
122417
122418     nodeGetCell(&tree, &node, ii, &cell);
122419     sqlite3_snprintf(512-nCell,&zCell[nCell],"%d", cell.iRowid);
122420     nCell = strlen(zCell);
122421     for(jj=0; jj<tree.nDim*2; jj++){
122422       sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
122423       nCell = strlen(zCell);
122424     }
122425
122426     if( zText ){
122427       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
122428       sqlite3_free(zText);
122429       zText = zTextNew;
122430     }else{
122431       zText = sqlite3_mprintf("{%s}", zCell);
122432     }
122433   }
122434   
122435   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
122436 }
122437
122438 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
122439   UNUSED_PARAMETER(nArg);
122440   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 
122441    || sqlite3_value_bytes(apArg[0])<2
122442   ){
122443     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
122444   }else{
122445     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
122446     sqlite3_result_int(ctx, readInt16(zBlob));
122447   }
122448 }
122449
122450 /*
122451 ** Register the r-tree module with database handle db. This creates the
122452 ** virtual table module "rtree" and the debugging/analysis scalar 
122453 ** function "rtreenode".
122454 */
122455 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
122456   const int utf8 = SQLITE_UTF8;
122457   int rc;
122458
122459   rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
122460   if( rc==SQLITE_OK ){
122461     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
122462   }
122463   if( rc==SQLITE_OK ){
122464     void *c = (void *)RTREE_COORD_REAL32;
122465     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
122466   }
122467   if( rc==SQLITE_OK ){
122468     void *c = (void *)RTREE_COORD_INT32;
122469     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
122470   }
122471
122472   return rc;
122473 }
122474
122475 /*
122476 ** A version of sqlite3_free() that can be used as a callback. This is used
122477 ** in two places - as the destructor for the blob value returned by the
122478 ** invocation of a geometry function, and as the destructor for the geometry
122479 ** functions themselves.
122480 */
122481 static void doSqlite3Free(void *p){
122482   sqlite3_free(p);
122483 }
122484
122485 /*
122486 ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
122487 ** scalar user function. This C function is the callback used for all such
122488 ** registered SQL functions.
122489 **
122490 ** The scalar user functions return a blob that is interpreted by r-tree
122491 ** table MATCH operators.
122492 */
122493 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
122494   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
122495   RtreeMatchArg *pBlob;
122496   int nBlob;
122497
122498   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(double);
122499   pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
122500   if( !pBlob ){
122501     sqlite3_result_error_nomem(ctx);
122502   }else{
122503     int i;
122504     pBlob->magic = RTREE_GEOMETRY_MAGIC;
122505     pBlob->xGeom = pGeomCtx->xGeom;
122506     pBlob->pContext = pGeomCtx->pContext;
122507     pBlob->nParam = nArg;
122508     for(i=0; i<nArg; i++){
122509       pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
122510     }
122511     sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
122512   }
122513 }
122514
122515 /*
122516 ** Register a new geometry function for use with the r-tree MATCH operator.
122517 */
122518 SQLITE_API int sqlite3_rtree_geometry_callback(
122519   sqlite3 *db,
122520   const char *zGeom,
122521   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *),
122522   void *pContext
122523 ){
122524   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
122525
122526   /* Allocate and populate the context object. */
122527   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
122528   if( !pGeomCtx ) return SQLITE_NOMEM;
122529   pGeomCtx->xGeom = xGeom;
122530   pGeomCtx->pContext = pContext;
122531
122532   /* Create the new user-function. Register a destructor function to delete
122533   ** the context object when it is no longer required.  */
122534   return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY, 
122535       (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
122536   );
122537 }
122538
122539 #if !SQLITE_CORE
122540 SQLITE_API int sqlite3_extension_init(
122541   sqlite3 *db,
122542   char **pzErrMsg,
122543   const sqlite3_api_routines *pApi
122544 ){
122545   SQLITE_EXTENSION_INIT2(pApi)
122546   return sqlite3RtreeInit(db);
122547 }
122548 #endif
122549
122550 #endif
122551
122552 /************** End of rtree.c ***********************************************/
122553 /************** Begin file icu.c *********************************************/
122554 /*
122555 ** 2007 May 6
122556 **
122557 ** The author disclaims copyright to this source code.  In place of
122558 ** a legal notice, here is a blessing:
122559 **
122560 **    May you do good and not evil.
122561 **    May you find forgiveness for yourself and forgive others.
122562 **    May you share freely, never taking more than you give.
122563 **
122564 *************************************************************************
122565 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
122566 **
122567 ** This file implements an integration between the ICU library 
122568 ** ("International Components for Unicode", an open-source library 
122569 ** for handling unicode data) and SQLite. The integration uses 
122570 ** ICU to provide the following to SQLite:
122571 **
122572 **   * An implementation of the SQL regexp() function (and hence REGEXP
122573 **     operator) using the ICU uregex_XX() APIs.
122574 **
122575 **   * Implementations of the SQL scalar upper() and lower() functions
122576 **     for case mapping.
122577 **
122578 **   * Integration of ICU and SQLite collation seqences.
122579 **
122580 **   * An implementation of the LIKE operator that uses ICU to 
122581 **     provide case-independent matching.
122582 */
122583
122584 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
122585
122586 /* Include ICU headers */
122587 #include <unicode/utypes.h>
122588 #include <unicode/uregex.h>
122589 #include <unicode/ustring.h>
122590 #include <unicode/ucol.h>
122591
122592
122593 #ifndef SQLITE_CORE
122594   SQLITE_EXTENSION_INIT1
122595 #else
122596 #endif
122597
122598 /*
122599 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
122600 ** operator.
122601 */
122602 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
122603 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
122604 #endif
122605
122606 /*
122607 ** Version of sqlite3_free() that is always a function, never a macro.
122608 */
122609 static void xFree(void *p){
122610   sqlite3_free(p);
122611 }
122612
122613 /*
122614 ** Compare two UTF-8 strings for equality where the first string is
122615 ** a "LIKE" expression. Return true (1) if they are the same and 
122616 ** false (0) if they are different.
122617 */
122618 static int icuLikeCompare(
122619   const uint8_t *zPattern,   /* LIKE pattern */
122620   const uint8_t *zString,    /* The UTF-8 string to compare against */
122621   const UChar32 uEsc         /* The escape character */
122622 ){
122623   static const int MATCH_ONE = (UChar32)'_';
122624   static const int MATCH_ALL = (UChar32)'%';
122625
122626   int iPattern = 0;       /* Current byte index in zPattern */
122627   int iString = 0;        /* Current byte index in zString */
122628
122629   int prevEscape = 0;     /* True if the previous character was uEsc */
122630
122631   while( zPattern[iPattern]!=0 ){
122632
122633     /* Read (and consume) the next character from the input pattern. */
122634     UChar32 uPattern;
122635     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
122636     assert(uPattern!=0);
122637
122638     /* There are now 4 possibilities:
122639     **
122640     **     1. uPattern is an unescaped match-all character "%",
122641     **     2. uPattern is an unescaped match-one character "_",
122642     **     3. uPattern is an unescaped escape character, or
122643     **     4. uPattern is to be handled as an ordinary character
122644     */
122645     if( !prevEscape && uPattern==MATCH_ALL ){
122646       /* Case 1. */
122647       uint8_t c;
122648
122649       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
122650       ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
122651       ** test string.
122652       */
122653       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
122654         if( c==MATCH_ONE ){
122655           if( zString[iString]==0 ) return 0;
122656           U8_FWD_1_UNSAFE(zString, iString);
122657         }
122658         iPattern++;
122659       }
122660
122661       if( zPattern[iPattern]==0 ) return 1;
122662
122663       while( zString[iString] ){
122664         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
122665           return 1;
122666         }
122667         U8_FWD_1_UNSAFE(zString, iString);
122668       }
122669       return 0;
122670
122671     }else if( !prevEscape && uPattern==MATCH_ONE ){
122672       /* Case 2. */
122673       if( zString[iString]==0 ) return 0;
122674       U8_FWD_1_UNSAFE(zString, iString);
122675
122676     }else if( !prevEscape && uPattern==uEsc){
122677       /* Case 3. */
122678       prevEscape = 1;
122679
122680     }else{
122681       /* Case 4. */
122682       UChar32 uString;
122683       U8_NEXT_UNSAFE(zString, iString, uString);
122684       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
122685       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
122686       if( uString!=uPattern ){
122687         return 0;
122688       }
122689       prevEscape = 0;
122690     }
122691   }
122692
122693   return zString[iString]==0;
122694 }
122695
122696 /*
122697 ** Implementation of the like() SQL function.  This function implements
122698 ** the build-in LIKE operator.  The first argument to the function is the
122699 ** pattern and the second argument is the string.  So, the SQL statements:
122700 **
122701 **       A LIKE B
122702 **
122703 ** is implemented as like(B, A). If there is an escape character E, 
122704 **
122705 **       A LIKE B ESCAPE E
122706 **
122707 ** is mapped to like(B, A, E).
122708 */
122709 static void icuLikeFunc(
122710   sqlite3_context *context, 
122711   int argc, 
122712   sqlite3_value **argv
122713 ){
122714   const unsigned char *zA = sqlite3_value_text(argv[0]);
122715   const unsigned char *zB = sqlite3_value_text(argv[1]);
122716   UChar32 uEsc = 0;
122717
122718   /* Limit the length of the LIKE or GLOB pattern to avoid problems
122719   ** of deep recursion and N*N behavior in patternCompare().
122720   */
122721   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
122722     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
122723     return;
122724   }
122725
122726
122727   if( argc==3 ){
122728     /* The escape character string must consist of a single UTF-8 character.
122729     ** Otherwise, return an error.
122730     */
122731     int nE= sqlite3_value_bytes(argv[2]);
122732     const unsigned char *zE = sqlite3_value_text(argv[2]);
122733     int i = 0;
122734     if( zE==0 ) return;
122735     U8_NEXT(zE, i, nE, uEsc);
122736     if( i!=nE){
122737       sqlite3_result_error(context, 
122738           "ESCAPE expression must be a single character", -1);
122739       return;
122740     }
122741   }
122742
122743   if( zA && zB ){
122744     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
122745   }
122746 }
122747
122748 /*
122749 ** This function is called when an ICU function called from within
122750 ** the implementation of an SQL scalar function returns an error.
122751 **
122752 ** The scalar function context passed as the first argument is 
122753 ** loaded with an error message based on the following two args.
122754 */
122755 static void icuFunctionError(
122756   sqlite3_context *pCtx,       /* SQLite scalar function context */
122757   const char *zName,           /* Name of ICU function that failed */
122758   UErrorCode e                 /* Error code returned by ICU function */
122759 ){
122760   char zBuf[128];
122761   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
122762   zBuf[127] = '\0';
122763   sqlite3_result_error(pCtx, zBuf, -1);
122764 }
122765
122766 /*
122767 ** Function to delete compiled regexp objects. Registered as
122768 ** a destructor function with sqlite3_set_auxdata().
122769 */
122770 static void icuRegexpDelete(void *p){
122771   URegularExpression *pExpr = (URegularExpression *)p;
122772   uregex_close(pExpr);
122773 }
122774
122775 /*
122776 ** Implementation of SQLite REGEXP operator. This scalar function takes
122777 ** two arguments. The first is a regular expression pattern to compile
122778 ** the second is a string to match against that pattern. If either 
122779 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
122780 ** is 1 if the string matches the pattern, or 0 otherwise.
122781 **
122782 ** SQLite maps the regexp() function to the regexp() operator such
122783 ** that the following two are equivalent:
122784 **
122785 **     zString REGEXP zPattern
122786 **     regexp(zPattern, zString)
122787 **
122788 ** Uses the following ICU regexp APIs:
122789 **
122790 **     uregex_open()
122791 **     uregex_matches()
122792 **     uregex_close()
122793 */
122794 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
122795   UErrorCode status = U_ZERO_ERROR;
122796   URegularExpression *pExpr;
122797   UBool res;
122798   const UChar *zString = sqlite3_value_text16(apArg[1]);
122799
122800   /* If the left hand side of the regexp operator is NULL, 
122801   ** then the result is also NULL. 
122802   */
122803   if( !zString ){
122804     return;
122805   }
122806
122807   pExpr = sqlite3_get_auxdata(p, 0);
122808   if( !pExpr ){
122809     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
122810     if( !zPattern ){
122811       return;
122812     }
122813     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
122814
122815     if( U_SUCCESS(status) ){
122816       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
122817     }else{
122818       assert(!pExpr);
122819       icuFunctionError(p, "uregex_open", status);
122820       return;
122821     }
122822   }
122823
122824   /* Configure the text that the regular expression operates on. */
122825   uregex_setText(pExpr, zString, -1, &status);
122826   if( !U_SUCCESS(status) ){
122827     icuFunctionError(p, "uregex_setText", status);
122828     return;
122829   }
122830
122831   /* Attempt the match */
122832   res = uregex_matches(pExpr, 0, &status);
122833   if( !U_SUCCESS(status) ){
122834     icuFunctionError(p, "uregex_matches", status);
122835     return;
122836   }
122837
122838   /* Set the text that the regular expression operates on to a NULL
122839   ** pointer. This is not really necessary, but it is tidier than 
122840   ** leaving the regular expression object configured with an invalid
122841   ** pointer after this function returns.
122842   */
122843   uregex_setText(pExpr, 0, 0, &status);
122844
122845   /* Return 1 or 0. */
122846   sqlite3_result_int(p, res ? 1 : 0);
122847 }
122848
122849 /*
122850 ** Implementations of scalar functions for case mapping - upper() and 
122851 ** lower(). Function upper() converts its input to upper-case (ABC).
122852 ** Function lower() converts to lower-case (abc).
122853 **
122854 ** ICU provides two types of case mapping, "general" case mapping and
122855 ** "language specific". Refer to ICU documentation for the differences
122856 ** between the two.
122857 **
122858 ** To utilise "general" case mapping, the upper() or lower() scalar 
122859 ** functions are invoked with one argument:
122860 **
122861 **     upper('ABC') -> 'abc'
122862 **     lower('abc') -> 'ABC'
122863 **
122864 ** To access ICU "language specific" case mapping, upper() or lower()
122865 ** should be invoked with two arguments. The second argument is the name
122866 ** of the locale to use. Passing an empty string ("") or SQL NULL value
122867 ** as the second argument is the same as invoking the 1 argument version
122868 ** of upper() or lower().
122869 **
122870 **     lower('I', 'en_us') -> 'i'
122871 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
122872 **
122873 ** http://www.icu-project.org/userguide/posix.html#case_mappings
122874 */
122875 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
122876   const UChar *zInput;
122877   UChar *zOutput;
122878   int nInput;
122879   int nOutput;
122880
122881   UErrorCode status = U_ZERO_ERROR;
122882   const char *zLocale = 0;
122883
122884   assert(nArg==1 || nArg==2);
122885   if( nArg==2 ){
122886     zLocale = (const char *)sqlite3_value_text(apArg[1]);
122887   }
122888
122889   zInput = sqlite3_value_text16(apArg[0]);
122890   if( !zInput ){
122891     return;
122892   }
122893   nInput = sqlite3_value_bytes16(apArg[0]);
122894
122895   nOutput = nInput * 2 + 2;
122896   zOutput = sqlite3_malloc(nOutput);
122897   if( !zOutput ){
122898     return;
122899   }
122900
122901   if( sqlite3_user_data(p) ){
122902     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
122903   }else{
122904     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
122905   }
122906
122907   if( !U_SUCCESS(status) ){
122908     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
122909     return;
122910   }
122911
122912   sqlite3_result_text16(p, zOutput, -1, xFree);
122913 }
122914
122915 /*
122916 ** Collation sequence destructor function. The pCtx argument points to
122917 ** a UCollator structure previously allocated using ucol_open().
122918 */
122919 static void icuCollationDel(void *pCtx){
122920   UCollator *p = (UCollator *)pCtx;
122921   ucol_close(p);
122922 }
122923
122924 /*
122925 ** Collation sequence comparison function. The pCtx argument points to
122926 ** a UCollator structure previously allocated using ucol_open().
122927 */
122928 static int icuCollationColl(
122929   void *pCtx,
122930   int nLeft,
122931   const void *zLeft,
122932   int nRight,
122933   const void *zRight
122934 ){
122935   UCollationResult res;
122936   UCollator *p = (UCollator *)pCtx;
122937   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
122938   switch( res ){
122939     case UCOL_LESS:    return -1;
122940     case UCOL_GREATER: return +1;
122941     case UCOL_EQUAL:   return 0;
122942   }
122943   assert(!"Unexpected return value from ucol_strcoll()");
122944   return 0;
122945 }
122946
122947 /*
122948 ** Implementation of the scalar function icu_load_collation().
122949 **
122950 ** This scalar function is used to add ICU collation based collation 
122951 ** types to an SQLite database connection. It is intended to be called
122952 ** as follows:
122953 **
122954 **     SELECT icu_load_collation(<locale>, <collation-name>);
122955 **
122956 ** Where <locale> is a string containing an ICU locale identifier (i.e.
122957 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
122958 ** collation sequence to create.
122959 */
122960 static void icuLoadCollation(
122961   sqlite3_context *p, 
122962   int nArg, 
122963   sqlite3_value **apArg
122964 ){
122965   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
122966   UErrorCode status = U_ZERO_ERROR;
122967   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
122968   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
122969   UCollator *pUCollator;    /* ICU library collation object */
122970   int rc;                   /* Return code from sqlite3_create_collation_x() */
122971
122972   assert(nArg==2);
122973   zLocale = (const char *)sqlite3_value_text(apArg[0]);
122974   zName = (const char *)sqlite3_value_text(apArg[1]);
122975
122976   if( !zLocale || !zName ){
122977     return;
122978   }
122979
122980   pUCollator = ucol_open(zLocale, &status);
122981   if( !U_SUCCESS(status) ){
122982     icuFunctionError(p, "ucol_open", status);
122983     return;
122984   }
122985   assert(p);
122986
122987   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
122988       icuCollationColl, icuCollationDel
122989   );
122990   if( rc!=SQLITE_OK ){
122991     ucol_close(pUCollator);
122992     sqlite3_result_error(p, "Error registering collation function", -1);
122993   }
122994 }
122995
122996 /*
122997 ** Register the ICU extension functions with database db.
122998 */
122999 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
123000   struct IcuScalar {
123001     const char *zName;                        /* Function name */
123002     int nArg;                                 /* Number of arguments */
123003     int enc;                                  /* Optimal text encoding */
123004     void *pContext;                           /* sqlite3_user_data() context */
123005     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
123006   } scalars[] = {
123007     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
123008
123009     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
123010     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
123011     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
123012     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
123013
123014     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
123015     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
123016     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
123017     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
123018
123019     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
123020     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
123021
123022     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
123023   };
123024
123025   int rc = SQLITE_OK;
123026   int i;
123027
123028   for(i=0; rc==SQLITE_OK && i<(sizeof(scalars)/sizeof(struct IcuScalar)); i++){
123029     struct IcuScalar *p = &scalars[i];
123030     rc = sqlite3_create_function(
123031         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
123032     );
123033   }
123034
123035   return rc;
123036 }
123037
123038 #if !SQLITE_CORE
123039 SQLITE_API int sqlite3_extension_init(
123040   sqlite3 *db, 
123041   char **pzErrMsg,
123042   const sqlite3_api_routines *pApi
123043 ){
123044   SQLITE_EXTENSION_INIT2(pApi)
123045   return sqlite3IcuInit(db);
123046 }
123047 #endif
123048
123049 #endif
123050
123051 /************** End of icu.c *************************************************/
123052 /************** Begin file fts3_icu.c ****************************************/
123053 /*
123054 ** 2007 June 22
123055 **
123056 ** The author disclaims copyright to this source code.  In place of
123057 ** a legal notice, here is a blessing:
123058 **
123059 **    May you do good and not evil.
123060 **    May you find forgiveness for yourself and forgive others.
123061 **    May you share freely, never taking more than you give.
123062 **
123063 *************************************************************************
123064 ** This file implements a tokenizer for fts3 based on the ICU library.
123065 ** 
123066 ** $Id: fts3_icu.c,v 1.3 2008/09/01 18:34:20 danielk1977 Exp $
123067 */
123068
123069 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
123070 #ifdef SQLITE_ENABLE_ICU
123071
123072
123073 #include <unicode/ubrk.h>
123074 #include <unicode/utf16.h>
123075
123076 typedef struct IcuTokenizer IcuTokenizer;
123077 typedef struct IcuCursor IcuCursor;
123078
123079 struct IcuTokenizer {
123080   sqlite3_tokenizer base;
123081   char *zLocale;
123082 };
123083
123084 struct IcuCursor {
123085   sqlite3_tokenizer_cursor base;
123086
123087   UBreakIterator *pIter;      /* ICU break-iterator object */
123088   int nChar;                  /* Number of UChar elements in pInput */
123089   UChar *aChar;               /* Copy of input using utf-16 encoding */
123090   int *aOffset;               /* Offsets of each character in utf-8 input */
123091
123092   int nBuffer;
123093   char *zBuffer;
123094
123095   int iToken;
123096 };
123097
123098 /*
123099 ** Create a new tokenizer instance.
123100 */
123101 static int icuCreate(
123102   int argc,                            /* Number of entries in argv[] */
123103   const char * const *argv,            /* Tokenizer creation arguments */
123104   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
123105 ){
123106   IcuTokenizer *p;
123107   int n = 0;
123108
123109   if( argc>0 ){
123110     n = strlen(argv[0])+1;
123111   }
123112   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
123113   if( !p ){
123114     return SQLITE_NOMEM;
123115   }
123116   memset(p, 0, sizeof(IcuTokenizer));
123117
123118   if( n ){
123119     p->zLocale = (char *)&p[1];
123120     memcpy(p->zLocale, argv[0], n);
123121   }
123122
123123   *ppTokenizer = (sqlite3_tokenizer *)p;
123124
123125   return SQLITE_OK;
123126 }
123127
123128 /*
123129 ** Destroy a tokenizer
123130 */
123131 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
123132   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
123133   sqlite3_free(p);
123134   return SQLITE_OK;
123135 }
123136
123137 /*
123138 ** Prepare to begin tokenizing a particular string.  The input
123139 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
123140 ** used to incrementally tokenize this string is returned in 
123141 ** *ppCursor.
123142 */
123143 static int icuOpen(
123144   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
123145   const char *zInput,                    /* Input string */
123146   int nInput,                            /* Length of zInput in bytes */
123147   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
123148 ){
123149   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
123150   IcuCursor *pCsr;
123151
123152   const int32_t opt = U_FOLD_CASE_DEFAULT;
123153   UErrorCode status = U_ZERO_ERROR;
123154   int nChar;
123155
123156   UChar32 c;
123157   int iInput = 0;
123158   int iOut = 0;
123159
123160   *ppCursor = 0;
123161
123162   if( nInput<0 ){
123163     nInput = strlen(zInput);
123164   }
123165   nChar = nInput+1;
123166   pCsr = (IcuCursor *)sqlite3_malloc(
123167       sizeof(IcuCursor) +                /* IcuCursor */
123168       nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
123169       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
123170   );
123171   if( !pCsr ){
123172     return SQLITE_NOMEM;
123173   }
123174   memset(pCsr, 0, sizeof(IcuCursor));
123175   pCsr->aChar = (UChar *)&pCsr[1];
123176   pCsr->aOffset = (int *)&pCsr->aChar[nChar];
123177
123178   pCsr->aOffset[iOut] = iInput;
123179   U8_NEXT(zInput, iInput, nInput, c); 
123180   while( c>0 ){
123181     int isError = 0;
123182     c = u_foldCase(c, opt);
123183     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
123184     if( isError ){
123185       sqlite3_free(pCsr);
123186       return SQLITE_ERROR;
123187     }
123188     pCsr->aOffset[iOut] = iInput;
123189
123190     if( iInput<nInput ){
123191       U8_NEXT(zInput, iInput, nInput, c);
123192     }else{
123193       c = 0;
123194     }
123195   }
123196
123197   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
123198   if( !U_SUCCESS(status) ){
123199     sqlite3_free(pCsr);
123200     return SQLITE_ERROR;
123201   }
123202   pCsr->nChar = iOut;
123203
123204   ubrk_first(pCsr->pIter);
123205   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
123206   return SQLITE_OK;
123207 }
123208
123209 /*
123210 ** Close a tokenization cursor previously opened by a call to icuOpen().
123211 */
123212 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
123213   IcuCursor *pCsr = (IcuCursor *)pCursor;
123214   ubrk_close(pCsr->pIter);
123215   sqlite3_free(pCsr->zBuffer);
123216   sqlite3_free(pCsr);
123217   return SQLITE_OK;
123218 }
123219
123220 /*
123221 ** Extract the next token from a tokenization cursor.
123222 */
123223 static int icuNext(
123224   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
123225   const char **ppToken,               /* OUT: *ppToken is the token text */
123226   int *pnBytes,                       /* OUT: Number of bytes in token */
123227   int *piStartOffset,                 /* OUT: Starting offset of token */
123228   int *piEndOffset,                   /* OUT: Ending offset of token */
123229   int *piPosition                     /* OUT: Position integer of token */
123230 ){
123231   IcuCursor *pCsr = (IcuCursor *)pCursor;
123232
123233   int iStart = 0;
123234   int iEnd = 0;
123235   int nByte = 0;
123236
123237   while( iStart==iEnd ){
123238     UChar32 c;
123239
123240     iStart = ubrk_current(pCsr->pIter);
123241     iEnd = ubrk_next(pCsr->pIter);
123242     if( iEnd==UBRK_DONE ){
123243       return SQLITE_DONE;
123244     }
123245
123246     while( iStart<iEnd ){
123247       int iWhite = iStart;
123248       U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
123249       if( u_isspace(c) ){
123250         iStart = iWhite;
123251       }else{
123252         break;
123253       }
123254     }
123255     assert(iStart<=iEnd);
123256   }
123257
123258   do {
123259     UErrorCode status = U_ZERO_ERROR;
123260     if( nByte ){
123261       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
123262       if( !zNew ){
123263         return SQLITE_NOMEM;
123264       }
123265       pCsr->zBuffer = zNew;
123266       pCsr->nBuffer = nByte;
123267     }
123268
123269     u_strToUTF8(
123270         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
123271         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
123272         &status                                  /* Output success/failure */
123273     );
123274   } while( nByte>pCsr->nBuffer );
123275
123276   *ppToken = pCsr->zBuffer;
123277   *pnBytes = nByte;
123278   *piStartOffset = pCsr->aOffset[iStart];
123279   *piEndOffset = pCsr->aOffset[iEnd];
123280   *piPosition = pCsr->iToken++;
123281
123282   return SQLITE_OK;
123283 }
123284
123285 /*
123286 ** The set of routines that implement the simple tokenizer
123287 */
123288 static const sqlite3_tokenizer_module icuTokenizerModule = {
123289   0,                           /* iVersion */
123290   icuCreate,                   /* xCreate  */
123291   icuDestroy,                  /* xCreate  */
123292   icuOpen,                     /* xOpen    */
123293   icuClose,                    /* xClose   */
123294   icuNext,                     /* xNext    */
123295 };
123296
123297 /*
123298 ** Set *ppModule to point at the implementation of the ICU tokenizer.
123299 */
123300 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
123301   sqlite3_tokenizer_module const**ppModule
123302 ){
123303   *ppModule = &icuTokenizerModule;
123304 }
123305
123306 #endif /* defined(SQLITE_ENABLE_ICU) */
123307 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
123308
123309 /************** End of fts3_icu.c ********************************************/